Merge "Fixed silly doc typos"
[lhc/web/wiklou.git] / includes / db / Database.php
1 <?php
2 /**
3 * @defgroup Database Database
4 *
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup Database
25 */
26
27 /**
28 * Base interface for all DBMS-specific code. At a bare minimum, all of the
29 * following must be implemented to support MediaWiki
30 *
31 * @file
32 * @ingroup Database
33 */
34 interface DatabaseType {
35 /**
36 * Get the type of the DBMS, as it appears in $wgDBtype.
37 *
38 * @return string
39 */
40 function getType();
41
42 /**
43 * Open a connection to the database. Usually aborts on failure
44 *
45 * @param string $server database server host
46 * @param string $user database user name
47 * @param string $password database user password
48 * @param string $dbName database name
49 * @return bool
50 * @throws DBConnectionError
51 */
52 function open( $server, $user, $password, $dbName );
53
54 /**
55 * Fetch the next row from the given result object, in object form.
56 * Fields can be retrieved with $row->fieldname, with fields acting like
57 * member variables.
58 * If no more rows are available, false is returned.
59 *
60 * @param ResultWrapper|stdClass $res Object as returned from DatabaseBase::query(), etc.
61 * @return stdClass|bool
62 * @throws DBUnexpectedError Thrown if the database returns an error
63 */
64 function fetchObject( $res );
65
66 /**
67 * Fetch the next row from the given result object, in associative array
68 * form. Fields are retrieved with $row['fieldname'].
69 * If no more rows are available, false is returned.
70 *
71 * @param ResultWrapper $res Result object as returned from DatabaseBase::query(), etc.
72 * @return array|bool
73 * @throws DBUnexpectedError Thrown if the database returns an error
74 */
75 function fetchRow( $res );
76
77 /**
78 * Get the number of rows in a result object
79 *
80 * @param mixed $res A SQL result
81 * @return int
82 */
83 function numRows( $res );
84
85 /**
86 * Get the number of fields in a result object
87 * @see http://www.php.net/mysql_num_fields
88 *
89 * @param mixed $res A SQL result
90 * @return int
91 */
92 function numFields( $res );
93
94 /**
95 * Get a field name in a result object
96 * @see http://www.php.net/mysql_field_name
97 *
98 * @param mixed $res A SQL result
99 * @param int $n
100 * @return string
101 */
102 function fieldName( $res, $n );
103
104 /**
105 * Get the inserted value of an auto-increment row
106 *
107 * The value inserted should be fetched from nextSequenceValue()
108 *
109 * Example:
110 * $id = $dbw->nextSequenceValue( 'page_page_id_seq' );
111 * $dbw->insert( 'page', array( 'page_id' => $id ) );
112 * $id = $dbw->insertId();
113 *
114 * @return int
115 */
116 function insertId();
117
118 /**
119 * Change the position of the cursor in a result object
120 * @see http://www.php.net/mysql_data_seek
121 *
122 * @param mixed $res A SQL result
123 * @param int $row
124 */
125 function dataSeek( $res, $row );
126
127 /**
128 * Get the last error number
129 * @see http://www.php.net/mysql_errno
130 *
131 * @return int
132 */
133 function lastErrno();
134
135 /**
136 * Get a description of the last error
137 * @see http://www.php.net/mysql_error
138 *
139 * @return string
140 */
141 function lastError();
142
143 /**
144 * mysql_fetch_field() wrapper
145 * Returns false if the field doesn't exist
146 *
147 * @param string $table Table name
148 * @param string $field Field name
149 *
150 * @return Field
151 */
152 function fieldInfo( $table, $field );
153
154 /**
155 * Get information about an index into an object
156 * @param string $table Table name
157 * @param string $index Index name
158 * @param string $fname Calling function name
159 * @return mixed Database-specific index description class or false if the index does not exist
160 */
161 function indexInfo( $table, $index, $fname = __METHOD__ );
162
163 /**
164 * Get the number of rows affected by the last write query
165 * @see http://www.php.net/mysql_affected_rows
166 *
167 * @return int
168 */
169 function affectedRows();
170
171 /**
172 * Wrapper for addslashes()
173 *
174 * @param string $s String to be slashed.
175 * @return string Slashed string.
176 */
177 function strencode( $s );
178
179 /**
180 * Returns a wikitext link to the DB's website, e.g.,
181 * return "[http://www.mysql.com/ MySQL]";
182 * Should at least contain plain text, if for some reason
183 * your database has no website.
184 *
185 * @return string Wikitext of a link to the server software's web site
186 */
187 function getSoftwareLink();
188
189 /**
190 * A string describing the current software version, like from
191 * mysql_get_server_info().
192 *
193 * @return string Version information from the database server.
194 */
195 function getServerVersion();
196
197 /**
198 * A string describing the current software version, and possibly
199 * other details in a user-friendly way. Will be listed on Special:Version, etc.
200 * Use getServerVersion() to get machine-friendly information.
201 *
202 * @return string Version information from the database server
203 */
204 function getServerInfo();
205 }
206
207 /**
208 * Interface for classes that implement or wrap DatabaseBase
209 * @ingroup Database
210 */
211 interface IDatabase {
212 }
213
214 /**
215 * Database abstraction object
216 * @ingroup Database
217 */
218 abstract class DatabaseBase implements IDatabase, DatabaseType {
219 /** Number of times to re-try an operation in case of deadlock */
220 const DEADLOCK_TRIES = 4;
221
222 /** Minimum time to wait before retry, in microseconds */
223 const DEADLOCK_DELAY_MIN = 500000;
224
225 /** Maximum time to wait before retry */
226 const DEADLOCK_DELAY_MAX = 1500000;
227
228 # ------------------------------------------------------------------------------
229 # Variables
230 # ------------------------------------------------------------------------------
231
232 protected $mLastQuery = '';
233 protected $mDoneWrites = false;
234 protected $mPHPError = false;
235
236 protected $mServer, $mUser, $mPassword, $mDBname;
237
238 /** @var resource Database connection */
239 protected $mConn = null;
240 protected $mOpened = false;
241
242 /** @var callable[] */
243 protected $mTrxIdleCallbacks = array();
244 /** @var callable[] */
245 protected $mTrxPreCommitCallbacks = array();
246
247 protected $mTablePrefix;
248 protected $mFlags;
249 protected $mForeign;
250 protected $mErrorCount = 0;
251 protected $mLBInfo = array();
252 protected $mFakeSlaveLag = null, $mFakeMaster = false;
253 protected $mDefaultBigSelects = null;
254 protected $mSchemaVars = false;
255
256 protected $preparedArgs;
257
258 protected $htmlErrors;
259
260 protected $delimiter = ';';
261
262 /**
263 * Either 1 if a transaction is active or 0 otherwise.
264 * The other Trx fields may not be meaningfull if this is 0.
265 *
266 * @var int
267 */
268 protected $mTrxLevel = 0;
269
270 /**
271 * Remembers the function name given for starting the most recent transaction via begin().
272 * Used to provide additional context for error reporting.
273 *
274 * @var string
275 * @see DatabaseBase::mTrxLevel
276 */
277 private $mTrxFname = null;
278
279 /**
280 * Record if possible write queries were done in the last transaction started
281 *
282 * @var bool
283 * @see DatabaseBase::mTrxLevel
284 */
285 private $mTrxDoneWrites = false;
286
287 /**
288 * Record if the current transaction was started implicitly due to DBO_TRX being set.
289 *
290 * @var bool
291 * @see DatabaseBase::mTrxLevel
292 */
293 private $mTrxAutomatic = false;
294
295 /**
296 * Array of levels of atomicity within transactions
297 *
298 * @var SplStack
299 */
300 private $mTrxAtomicLevels;
301
302 /**
303 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
304 *
305 * @var bool
306 */
307 private $mTrxAutomaticAtomic = false;
308
309 /**
310 * @since 1.21
311 * @var resource File handle for upgrade
312 */
313 protected $fileHandle = null;
314
315 /**
316 * @since 1.22
317 * @var string[] Process cache of VIEWs names in the database
318 */
319 protected $allViews = null;
320
321 # ------------------------------------------------------------------------------
322 # Accessors
323 # ------------------------------------------------------------------------------
324 # These optionally set a variable and return the previous state
325
326 /**
327 * A string describing the current software version, and possibly
328 * other details in a user-friendly way. Will be listed on Special:Version, etc.
329 * Use getServerVersion() to get machine-friendly information.
330 *
331 * @return string Version information from the database server
332 */
333 public function getServerInfo() {
334 return $this->getServerVersion();
335 }
336
337 /**
338 * @return string command delimiter used by this database engine
339 */
340 public function getDelimiter() {
341 return $this->delimiter;
342 }
343
344 /**
345 * Boolean, controls output of large amounts of debug information.
346 * @param bool|null $debug
347 * - true to enable debugging
348 * - false to disable debugging
349 * - omitted or null to do nothing
350 *
351 * @return bool|null previous value of the flag
352 */
353 public function debug( $debug = null ) {
354 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
355 }
356
357 /**
358 * Turns buffering of SQL result sets on (true) or off (false). Default is
359 * "on".
360 *
361 * Unbuffered queries are very troublesome in MySQL:
362 *
363 * - If another query is executed while the first query is being read
364 * out, the first query is killed. This means you can't call normal
365 * MediaWiki functions while you are reading an unbuffered query result
366 * from a normal wfGetDB() connection.
367 *
368 * - Unbuffered queries cause the MySQL server to use large amounts of
369 * memory and to hold broad locks which block other queries.
370 *
371 * If you want to limit client-side memory, it's almost always better to
372 * split up queries into batches using a LIMIT clause than to switch off
373 * buffering.
374 *
375 * @param null|bool $buffer
376 * @return null|bool The previous value of the flag
377 */
378 public function bufferResults( $buffer = null ) {
379 if ( is_null( $buffer ) ) {
380 return !(bool)( $this->mFlags & DBO_NOBUFFER );
381 } else {
382 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
383 }
384 }
385
386 /**
387 * Turns on (false) or off (true) the automatic generation and sending
388 * of a "we're sorry, but there has been a database error" page on
389 * database errors. Default is on (false). When turned off, the
390 * code should use lastErrno() and lastError() to handle the
391 * situation as appropriate.
392 *
393 * Do not use this function outside of the Database classes.
394 *
395 * @param null|bool $ignoreErrors
396 * @return bool The previous value of the flag.
397 */
398 public function ignoreErrors( $ignoreErrors = null ) {
399 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
400 }
401
402 /**
403 * Gets the current transaction level.
404 *
405 * Historically, transactions were allowed to be "nested". This is no
406 * longer supported, so this function really only returns a boolean.
407 *
408 * @return int The previous value
409 */
410 public function trxLevel() {
411 return $this->mTrxLevel;
412 }
413
414 /**
415 * Get/set the number of errors logged. Only useful when errors are ignored
416 * @param int $count The count to set, or omitted to leave it unchanged.
417 * @return int The error count
418 */
419 public function errorCount( $count = null ) {
420 return wfSetVar( $this->mErrorCount, $count );
421 }
422
423 /**
424 * Get/set the table prefix.
425 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
426 * @return string The previous table prefix.
427 */
428 public function tablePrefix( $prefix = null ) {
429 return wfSetVar( $this->mTablePrefix, $prefix );
430 }
431
432 /**
433 * Set the filehandle to copy write statements to.
434 *
435 * @param resource $fh File handle
436 */
437 public function setFileHandle( $fh ) {
438 $this->fileHandle = $fh;
439 }
440
441 /**
442 * Get properties passed down from the server info array of the load
443 * balancer.
444 *
445 * @param string $name The entry of the info array to get, or null to get the
446 * whole array
447 *
448 * @return LoadBalancer|null
449 */
450 public function getLBInfo( $name = null ) {
451 if ( is_null( $name ) ) {
452 return $this->mLBInfo;
453 } else {
454 if ( array_key_exists( $name, $this->mLBInfo ) ) {
455 return $this->mLBInfo[$name];
456 } else {
457 return null;
458 }
459 }
460 }
461
462 /**
463 * Set the LB info array, or a member of it. If called with one parameter,
464 * the LB info array is set to that parameter. If it is called with two
465 * parameters, the member with the given name is set to the given value.
466 *
467 * @param string $name
468 * @param $value
469 */
470 public function setLBInfo( $name, $value = null ) {
471 if ( is_null( $value ) ) {
472 $this->mLBInfo = $name;
473 } else {
474 $this->mLBInfo[$name] = $value;
475 }
476 }
477
478 /**
479 * Set lag time in seconds for a fake slave
480 *
481 * @param int $lag
482 */
483 public function setFakeSlaveLag( $lag ) {
484 $this->mFakeSlaveLag = $lag;
485 }
486
487 /**
488 * Make this connection a fake master
489 *
490 * @param bool $enabled
491 */
492 public function setFakeMaster( $enabled = true ) {
493 $this->mFakeMaster = $enabled;
494 }
495
496 /**
497 * Returns true if this database supports (and uses) cascading deletes
498 *
499 * @return bool
500 */
501 public function cascadingDeletes() {
502 return false;
503 }
504
505 /**
506 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
507 *
508 * @return bool
509 */
510 public function cleanupTriggers() {
511 return false;
512 }
513
514 /**
515 * Returns true if this database is strict about what can be put into an IP field.
516 * Specifically, it uses a NULL value instead of an empty string.
517 *
518 * @return bool
519 */
520 public function strictIPs() {
521 return false;
522 }
523
524 /**
525 * Returns true if this database uses timestamps rather than integers
526 *
527 * @return bool
528 */
529 public function realTimestamps() {
530 return false;
531 }
532
533 /**
534 * Returns true if this database does an implicit sort when doing GROUP BY
535 *
536 * @return bool
537 */
538 public function implicitGroupby() {
539 return true;
540 }
541
542 /**
543 * Returns true if this database does an implicit order by when the column has an index
544 * For example: SELECT page_title FROM page LIMIT 1
545 *
546 * @return bool
547 */
548 public function implicitOrderby() {
549 return true;
550 }
551
552 /**
553 * Returns true if this database can do a native search on IP columns
554 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
555 *
556 * @return bool
557 */
558 public function searchableIPs() {
559 return false;
560 }
561
562 /**
563 * Returns true if this database can use functional indexes
564 *
565 * @return bool
566 */
567 public function functionalIndexes() {
568 return false;
569 }
570
571 /**
572 * Return the last query that went through DatabaseBase::query()
573 * @return string
574 */
575 public function lastQuery() {
576 return $this->mLastQuery;
577 }
578
579 /**
580 * Returns true if the connection may have been used for write queries.
581 * Should return true if unsure.
582 *
583 * @return bool
584 */
585 public function doneWrites() {
586 return $this->mDoneWrites;
587 }
588
589 /**
590 * Returns true if there is a transaction open with possible write
591 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
592 *
593 * @return bool
594 */
595 public function writesOrCallbacksPending() {
596 return $this->mTrxLevel && (
597 $this->mTrxDoneWrites || $this->mTrxIdleCallbacks || $this->mTrxPreCommitCallbacks
598 );
599 }
600
601 /**
602 * Is a connection to the database open?
603 * @return bool
604 */
605 public function isOpen() {
606 return $this->mOpened;
607 }
608
609 /**
610 * Set a flag for this connection
611 *
612 * @param int $flag DBO_* constants from Defines.php:
613 * - DBO_DEBUG: output some debug info (same as debug())
614 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
615 * - DBO_TRX: automatically start transactions
616 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
617 * and removes it in command line mode
618 * - DBO_PERSISTENT: use persistant database connection
619 */
620 public function setFlag( $flag ) {
621 global $wgDebugDBTransactions;
622 $this->mFlags |= $flag;
623 if ( ( $flag & DBO_TRX ) & $wgDebugDBTransactions ) {
624 wfDebug( "Implicit transactions are now disabled.\n" );
625 }
626 }
627
628 /**
629 * Clear a flag for this connection
630 *
631 * @param int $flag DBO_* constants from Defines.php:
632 * - DBO_DEBUG: output some debug info (same as debug())
633 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
634 * - DBO_TRX: automatically start transactions
635 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
636 * and removes it in command line mode
637 * - DBO_PERSISTENT: use persistant database connection
638 */
639 public function clearFlag( $flag ) {
640 global $wgDebugDBTransactions;
641 $this->mFlags &= ~$flag;
642 if ( ( $flag & DBO_TRX ) && $wgDebugDBTransactions ) {
643 wfDebug( "Implicit transactions are now disabled.\n" );
644 }
645 }
646
647 /**
648 * Returns a boolean whether the flag $flag is set for this connection
649 *
650 * @param int $flag DBO_* constants from Defines.php:
651 * - DBO_DEBUG: output some debug info (same as debug())
652 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
653 * - DBO_TRX: automatically start transactions
654 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
655 * and removes it in command line mode
656 * - DBO_PERSISTENT: use persistant database connection
657 * @return bool
658 */
659 public function getFlag( $flag ) {
660 return !!( $this->mFlags & $flag );
661 }
662
663 /**
664 * General read-only accessor
665 *
666 * @param string $name
667 * @return string
668 */
669 public function getProperty( $name ) {
670 return $this->$name;
671 }
672
673 /**
674 * @return string
675 */
676 public function getWikiID() {
677 if ( $this->mTablePrefix ) {
678 return "{$this->mDBname}-{$this->mTablePrefix}";
679 } else {
680 return $this->mDBname;
681 }
682 }
683
684 /**
685 * Return a path to the DBMS-specific schema file, otherwise default to tables.sql
686 *
687 * @return string
688 */
689 public function getSchemaPath() {
690 global $IP;
691 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
692 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
693 } else {
694 return "$IP/maintenance/tables.sql";
695 }
696 }
697
698 # ------------------------------------------------------------------------------
699 # Other functions
700 # ------------------------------------------------------------------------------
701
702 /**
703 * Constructor.
704 *
705 * FIXME: It is possible to construct a Database object with no associated
706 * connection object, by specifying no parameters to __construct(). This
707 * feature is deprecated and should be removed.
708 *
709 * DatabaseBase subclasses should not be constructed directly in external
710 * code. DatabaseBase::factory() should be used instead.
711 *
712 * @param array $params Parameters passed from DatabaseBase::factory()
713 */
714 function __construct( $params = null ) {
715 global $wgDBprefix, $wgCommandLineMode, $wgDebugDBTransactions;
716
717 $this->mTrxAtomicLevels = new SplStack;
718
719 if ( is_array( $params ) ) { // MW 1.22
720 $server = $params['host'];
721 $user = $params['user'];
722 $password = $params['password'];
723 $dbName = $params['dbname'];
724 $flags = $params['flags'];
725 $tablePrefix = $params['tablePrefix'];
726 $foreign = $params['foreign'];
727 } else { // legacy calling pattern
728 wfDeprecated( __METHOD__ . " method called without parameter array.", "1.23" );
729 $args = func_get_args();
730 $server = isset( $args[0] ) ? $args[0] : false;
731 $user = isset( $args[1] ) ? $args[1] : false;
732 $password = isset( $args[2] ) ? $args[2] : false;
733 $dbName = isset( $args[3] ) ? $args[3] : false;
734 $flags = isset( $args[4] ) ? $args[4] : 0;
735 $tablePrefix = isset( $args[5] ) ? $args[5] : 'get from global';
736 $foreign = isset( $args[6] ) ? $args[6] : false;
737 }
738
739 $this->mFlags = $flags;
740 if ( $this->mFlags & DBO_DEFAULT ) {
741 if ( $wgCommandLineMode ) {
742 $this->mFlags &= ~DBO_TRX;
743 if ( $wgDebugDBTransactions ) {
744 wfDebug( "Implicit transaction open disabled.\n" );
745 }
746 } else {
747 $this->mFlags |= DBO_TRX;
748 if ( $wgDebugDBTransactions ) {
749 wfDebug( "Implicit transaction open enabled.\n" );
750 }
751 }
752 }
753
754 /** Get the default table prefix*/
755 if ( $tablePrefix == 'get from global' ) {
756 $this->mTablePrefix = $wgDBprefix;
757 } else {
758 $this->mTablePrefix = $tablePrefix;
759 }
760
761 $this->mForeign = $foreign;
762
763 if ( $user ) {
764 $this->open( $server, $user, $password, $dbName );
765 }
766 }
767
768 /**
769 * Called by serialize. Throw an exception when DB connection is serialized.
770 * This causes problems on some database engines because the connection is
771 * not restored on unserialize.
772 */
773 public function __sleep() {
774 throw new MWException( 'Database serialization may cause problems, since ' .
775 'the connection is not restored on wakeup.' );
776 }
777
778 /**
779 * Given a DB type, construct the name of the appropriate child class of
780 * DatabaseBase. This is designed to replace all of the manual stuff like:
781 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
782 * as well as validate against the canonical list of DB types we have
783 *
784 * This factory function is mostly useful for when you need to connect to a
785 * database other than the MediaWiki default (such as for external auth,
786 * an extension, et cetera). Do not use this to connect to the MediaWiki
787 * database. Example uses in core:
788 * @see LoadBalancer::reallyOpenConnection()
789 * @see ForeignDBRepo::getMasterDB()
790 * @see WebInstaller_DBConnect::execute()
791 *
792 * @since 1.18
793 *
794 * @param string $dbType A possible DB type
795 * @param array $p An array of options to pass to the constructor.
796 * Valid options are: host, user, password, dbname, flags, tablePrefix, driver
797 * @throws MWException If the database driver or extension cannot be found
798 * @return DatabaseBase|null DatabaseBase subclass or null
799 */
800 final public static function factory( $dbType, $p = array() ) {
801 $canonicalDBTypes = array(
802 'mysql' => array( 'mysqli', 'mysql' ),
803 'postgres' => array(),
804 'sqlite' => array(),
805 'oracle' => array(),
806 'mssql' => array(),
807 );
808
809 $driver = false;
810 $dbType = strtolower( $dbType );
811 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
812 $possibleDrivers = $canonicalDBTypes[$dbType];
813 if ( !empty( $p['driver'] ) ) {
814 if ( in_array( $p['driver'], $possibleDrivers ) ) {
815 $driver = $p['driver'];
816 } else {
817 throw new MWException( __METHOD__ .
818 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
819 }
820 } else {
821 foreach ( $possibleDrivers as $posDriver ) {
822 if ( extension_loaded( $posDriver ) ) {
823 $driver = $posDriver;
824 break;
825 }
826 }
827 }
828 } else {
829 $driver = $dbType;
830 }
831 if ( $driver === false ) {
832 throw new MWException( __METHOD__ .
833 " no viable database extension found for type '$dbType'" );
834 }
835
836 $class = 'Database' . ucfirst( $driver );
837 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
838 $params = array(
839 'host' => isset( $p['host'] ) ? $p['host'] : false,
840 'user' => isset( $p['user'] ) ? $p['user'] : false,
841 'password' => isset( $p['password'] ) ? $p['password'] : false,
842 'dbname' => isset( $p['dbname'] ) ? $p['dbname'] : false,
843 'flags' => isset( $p['flags'] ) ? $p['flags'] : 0,
844 'tablePrefix' => isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : 'get from global',
845 'foreign' => isset( $p['foreign'] ) ? $p['foreign'] : false
846 );
847
848 return new $class( $params );
849 } else {
850 return null;
851 }
852 }
853
854 protected function installErrorHandler() {
855 $this->mPHPError = false;
856 $this->htmlErrors = ini_set( 'html_errors', '0' );
857 set_error_handler( array( $this, 'connectionErrorHandler' ) );
858 }
859
860 /**
861 * @return bool|string
862 */
863 protected function restoreErrorHandler() {
864 restore_error_handler();
865 if ( $this->htmlErrors !== false ) {
866 ini_set( 'html_errors', $this->htmlErrors );
867 }
868 if ( $this->mPHPError ) {
869 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
870 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
871
872 return $error;
873 } else {
874 return false;
875 }
876 }
877
878 /**
879 * @param $errno
880 * @param string $errstr
881 */
882 public function connectionErrorHandler( $errno, $errstr ) {
883 $this->mPHPError = $errstr;
884 }
885
886 /**
887 * Closes a database connection.
888 * if it is open : commits any open transactions
889 *
890 * @throws MWException
891 * @return bool Operation success. true if already closed.
892 */
893 public function close() {
894 if ( count( $this->mTrxIdleCallbacks ) ) { // sanity
895 throw new MWException( "Transaction idle callbacks still pending." );
896 }
897 $this->mOpened = false;
898 if ( $this->mConn ) {
899 if ( $this->trxLevel() ) {
900 if ( !$this->mTrxAutomatic ) {
901 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
902 " performing implicit commit before closing connection!" );
903 }
904
905 $this->commit( __METHOD__, 'flush' );
906 }
907
908 $ret = $this->closeConnection();
909 $this->mConn = false;
910
911 return $ret;
912 } else {
913 return true;
914 }
915 }
916
917 /**
918 * Closes underlying database connection
919 * @since 1.20
920 * @return bool Whether connection was closed successfully
921 */
922 abstract protected function closeConnection();
923
924 /**
925 * @param string $error Fallback error message, used if none is given by DB
926 * @throws DBConnectionError
927 */
928 function reportConnectionError( $error = 'Unknown error' ) {
929 $myError = $this->lastError();
930 if ( $myError ) {
931 $error = $myError;
932 }
933
934 # New method
935 throw new DBConnectionError( $this, $error );
936 }
937
938 /**
939 * The DBMS-dependent part of query()
940 *
941 * @param string $sql SQL query.
942 * @return ResultWrapper|bool Result object to feed to fetchObject,
943 * fetchRow, ...; or false on failure
944 */
945 abstract protected function doQuery( $sql );
946
947 /**
948 * Determine whether a query writes to the DB.
949 * Should return true if unsure.
950 *
951 * @param string $sql
952 * @return bool
953 */
954 public function isWriteQuery( $sql ) {
955 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
956 }
957
958 /**
959 * Run an SQL query and return the result. Normally throws a DBQueryError
960 * on failure. If errors are ignored, returns false instead.
961 *
962 * In new code, the query wrappers select(), insert(), update(), delete(),
963 * etc. should be used where possible, since they give much better DBMS
964 * independence and automatically quote or validate user input in a variety
965 * of contexts. This function is generally only useful for queries which are
966 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
967 * as CREATE TABLE.
968 *
969 * However, the query wrappers themselves should call this function.
970 *
971 * @param string $sql SQL query
972 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
973 * comment (you can use __METHOD__ or add some extra info)
974 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
975 * maybe best to catch the exception instead?
976 * @throws MWException
977 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
978 * for a successful read query, or false on failure if $tempIgnore set
979 */
980 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
981 global $wgUser, $wgDebugDBTransactions;
982
983 $this->mLastQuery = $sql;
984 if ( !$this->mDoneWrites && $this->isWriteQuery( $sql ) ) {
985 # Set a flag indicating that writes have been done
986 wfDebug( __METHOD__ . ": Writes done: $sql\n" );
987 $this->mDoneWrites = true;
988 }
989
990 # Add a comment for easy SHOW PROCESSLIST interpretation
991 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
992 $userName = $wgUser->getName();
993 if ( mb_strlen( $userName ) > 15 ) {
994 $userName = mb_substr( $userName, 0, 15 ) . '...';
995 }
996 $userName = str_replace( '/', '', $userName );
997 } else {
998 $userName = '';
999 }
1000
1001 // Add trace comment to the begin of the sql string, right after the operator.
1002 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
1003 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
1004
1005 # If DBO_TRX is set, start a transaction
1006 if ( ( $this->mFlags & DBO_TRX ) && !$this->mTrxLevel &&
1007 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
1008 ) {
1009 # Avoid establishing transactions for SHOW and SET statements too -
1010 # that would delay transaction initializations to once connection
1011 # is really used by application
1012 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
1013 if ( strpos( $sqlstart, "SHOW " ) !== 0 && strpos( $sqlstart, "SET " ) !== 0 ) {
1014 if ( $wgDebugDBTransactions ) {
1015 wfDebug( "Implicit transaction start.\n" );
1016 }
1017 $this->begin( __METHOD__ . " ($fname)" );
1018 $this->mTrxAutomatic = true;
1019 }
1020 }
1021
1022 # Keep track of whether the transaction has write queries pending
1023 if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $this->isWriteQuery( $sql ) ) {
1024 $this->mTrxDoneWrites = true;
1025 Profiler::instance()->transactionWritingIn( $this->mServer, $this->mDBname );
1026 }
1027
1028 $queryProf = '';
1029 $totalProf = '';
1030 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1031
1032 if ( !Profiler::instance()->isStub() ) {
1033 # generalizeSQL will probably cut down the query to reasonable
1034 # logging size most of the time. The substr is really just a sanity check.
1035 if ( $isMaster ) {
1036 $queryProf = 'query-m: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
1037 $totalProf = 'DatabaseBase::query-master';
1038 } else {
1039 $queryProf = 'query: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
1040 $totalProf = 'DatabaseBase::query';
1041 }
1042 wfProfileIn( $totalProf );
1043 wfProfileIn( $queryProf );
1044 }
1045
1046 if ( $this->debug() ) {
1047 static $cnt = 0;
1048
1049 $cnt++;
1050 $sqlx = substr( $commentedSql, 0, 500 );
1051 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1052
1053 $master = $isMaster ? 'master' : 'slave';
1054 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1055 }
1056
1057 $queryId = MWDebug::query( $sql, $fname, $isMaster );
1058
1059 # Do the query and handle errors
1060 $ret = $this->doQuery( $commentedSql );
1061
1062 MWDebug::queryTime( $queryId );
1063
1064 # Try reconnecting if the connection was lost
1065 if ( false === $ret && $this->wasErrorReissuable() ) {
1066 # Transaction is gone, like it or not
1067 $hadTrx = $this->mTrxLevel; // possible lost transaction
1068 wfDebug( "Connection lost, reconnecting...\n" );
1069 $this->mTrxLevel = 0;
1070 wfDebug( "Connection lost, reconnecting...\n" );
1071
1072 if ( $this->ping() ) {
1073 wfDebug( "Reconnected\n" );
1074 $sqlx = substr( $commentedSql, 0, 500 );
1075 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1076 global $wgRequestTime;
1077 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
1078 if ( $elapsed < 300 ) {
1079 # Not a database error to lose a transaction after a minute or two
1080 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
1081 }
1082 if ( !$hadTrx ) {
1083 # Should be safe to silently retry
1084 $ret = $this->doQuery( $commentedSql );
1085 }
1086 } else {
1087 wfDebug( "Failed\n" );
1088 }
1089 }
1090
1091 if ( false === $ret ) {
1092 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1093 }
1094
1095 if ( !Profiler::instance()->isStub() ) {
1096 wfProfileOut( $queryProf );
1097 wfProfileOut( $totalProf );
1098 }
1099
1100 return $this->resultObject( $ret );
1101 }
1102
1103 /**
1104 * Report a query error. Log the error, and if neither the object ignore
1105 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1106 *
1107 * @param string $error
1108 * @param int $errno
1109 * @param string $sql
1110 * @param string $fname
1111 * @param bool $tempIgnore
1112 * @throws DBQueryError
1113 */
1114 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1115 # Ignore errors during error handling to avoid infinite recursion
1116 $ignore = $this->ignoreErrors( true );
1117 ++$this->mErrorCount;
1118
1119 if ( $ignore || $tempIgnore ) {
1120 wfDebug( "SQL ERROR (ignored): $error\n" );
1121 $this->ignoreErrors( $ignore );
1122 } else {
1123 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1124 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
1125 wfDebug( "SQL ERROR: " . $error . "\n" );
1126 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1127 }
1128 }
1129
1130 /**
1131 * Intended to be compatible with the PEAR::DB wrapper functions.
1132 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1133 *
1134 * ? = scalar value, quoted as necessary
1135 * ! = raw SQL bit (a function for instance)
1136 * & = filename; reads the file and inserts as a blob
1137 * (we don't use this though...)
1138 *
1139 * @param string $sql
1140 * @param string $func
1141 *
1142 * @return array
1143 */
1144 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1145 /* MySQL doesn't support prepared statements (yet), so just
1146 * pack up the query for reference. We'll manually replace
1147 * the bits later.
1148 */
1149 return array( 'query' => $sql, 'func' => $func );
1150 }
1151
1152 /**
1153 * Free a prepared query, generated by prepare().
1154 * @param string $prepared
1155 */
1156 protected function freePrepared( $prepared ) {
1157 /* No-op by default */
1158 }
1159
1160 /**
1161 * Execute a prepared query with the various arguments
1162 * @param string $prepared the prepared sql
1163 * @param mixed $args Either an array here, or put scalars as varargs
1164 *
1165 * @return ResultWrapper
1166 */
1167 public function execute( $prepared, $args = null ) {
1168 if ( !is_array( $args ) ) {
1169 # Pull the var args
1170 $args = func_get_args();
1171 array_shift( $args );
1172 }
1173
1174 $sql = $this->fillPrepared( $prepared['query'], $args );
1175
1176 return $this->query( $sql, $prepared['func'] );
1177 }
1178
1179 /**
1180 * For faking prepared SQL statements on DBs that don't support it directly.
1181 *
1182 * @param string $preparedQuery A 'preparable' SQL statement
1183 * @param array $args of Arguments to fill it with
1184 * @return string Executable SQL
1185 */
1186 public function fillPrepared( $preparedQuery, $args ) {
1187 reset( $args );
1188 $this->preparedArgs =& $args;
1189
1190 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1191 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1192 }
1193
1194 /**
1195 * preg_callback func for fillPrepared()
1196 * The arguments should be in $this->preparedArgs and must not be touched
1197 * while we're doing this.
1198 *
1199 * @param array $matches
1200 * @throws DBUnexpectedError
1201 * @return string
1202 */
1203 protected function fillPreparedArg( $matches ) {
1204 switch ( $matches[1] ) {
1205 case '\\?':
1206 return '?';
1207 case '\\!':
1208 return '!';
1209 case '\\&':
1210 return '&';
1211 }
1212
1213 list( /* $n */, $arg ) = each( $this->preparedArgs );
1214
1215 switch ( $matches[1] ) {
1216 case '?':
1217 return $this->addQuotes( $arg );
1218 case '!':
1219 return $arg;
1220 case '&':
1221 # return $this->addQuotes( file_get_contents( $arg ) );
1222 throw new DBUnexpectedError(
1223 $this,
1224 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1225 );
1226 default:
1227 throw new DBUnexpectedError(
1228 $this,
1229 'Received invalid match. This should never happen!'
1230 );
1231 }
1232 }
1233
1234 /**
1235 * Free a result object returned by query() or select(). It's usually not
1236 * necessary to call this, just use unset() or let the variable holding
1237 * the result object go out of scope.
1238 *
1239 * @param mixed $res A SQL result
1240 */
1241 public function freeResult( $res ) {
1242 }
1243
1244 /**
1245 * A SELECT wrapper which returns a single field from a single result row.
1246 *
1247 * Usually throws a DBQueryError on failure. If errors are explicitly
1248 * ignored, returns false on failure.
1249 *
1250 * If no result rows are returned from the query, false is returned.
1251 *
1252 * @param string|array $table Table name. See DatabaseBase::select() for details.
1253 * @param string $var The field name to select. This must be a valid SQL
1254 * fragment: do not use unvalidated user input.
1255 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1256 * @param string $fname The function name of the caller.
1257 * @param string|array $options The query options. See DatabaseBase::select() for details.
1258 *
1259 * @return bool|mixed The value from the field, or false on failure.
1260 */
1261 public function selectField( $table, $var, $cond = '', $fname = __METHOD__,
1262 $options = array()
1263 ) {
1264 if ( !is_array( $options ) ) {
1265 $options = array( $options );
1266 }
1267
1268 $options['LIMIT'] = 1;
1269
1270 $res = $this->select( $table, $var, $cond, $fname, $options );
1271
1272 if ( $res === false || !$this->numRows( $res ) ) {
1273 return false;
1274 }
1275
1276 $row = $this->fetchRow( $res );
1277
1278 if ( $row !== false ) {
1279 return reset( $row );
1280 } else {
1281 return false;
1282 }
1283 }
1284
1285 /**
1286 * Returns an optional USE INDEX clause to go after the table, and a
1287 * string to go at the end of the query.
1288 *
1289 * @param array $options Associative array of options to be turned into
1290 * an SQL query, valid keys are listed in the function.
1291 * @return array
1292 * @see DatabaseBase::select()
1293 */
1294 public function makeSelectOptions( $options ) {
1295 $preLimitTail = $postLimitTail = '';
1296 $startOpts = '';
1297
1298 $noKeyOptions = array();
1299
1300 foreach ( $options as $key => $option ) {
1301 if ( is_numeric( $key ) ) {
1302 $noKeyOptions[$option] = true;
1303 }
1304 }
1305
1306 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1307
1308 $preLimitTail .= $this->makeOrderBy( $options );
1309
1310 // if (isset($options['LIMIT'])) {
1311 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1312 // isset($options['OFFSET']) ? $options['OFFSET']
1313 // : false);
1314 // }
1315
1316 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1317 $postLimitTail .= ' FOR UPDATE';
1318 }
1319
1320 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1321 $postLimitTail .= ' LOCK IN SHARE MODE';
1322 }
1323
1324 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1325 $startOpts .= 'DISTINCT';
1326 }
1327
1328 # Various MySQL extensions
1329 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1330 $startOpts .= ' /*! STRAIGHT_JOIN */';
1331 }
1332
1333 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1334 $startOpts .= ' HIGH_PRIORITY';
1335 }
1336
1337 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1338 $startOpts .= ' SQL_BIG_RESULT';
1339 }
1340
1341 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1342 $startOpts .= ' SQL_BUFFER_RESULT';
1343 }
1344
1345 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1346 $startOpts .= ' SQL_SMALL_RESULT';
1347 }
1348
1349 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1350 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1351 }
1352
1353 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1354 $startOpts .= ' SQL_CACHE';
1355 }
1356
1357 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1358 $startOpts .= ' SQL_NO_CACHE';
1359 }
1360
1361 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1362 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1363 } else {
1364 $useIndex = '';
1365 }
1366
1367 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1368 }
1369
1370 /**
1371 * Returns an optional GROUP BY with an optional HAVING
1372 *
1373 * @param array $options Associative array of options
1374 * @return string
1375 * @see DatabaseBase::select()
1376 * @since 1.21
1377 */
1378 public function makeGroupByWithHaving( $options ) {
1379 $sql = '';
1380 if ( isset( $options['GROUP BY'] ) ) {
1381 $gb = is_array( $options['GROUP BY'] )
1382 ? implode( ',', $options['GROUP BY'] )
1383 : $options['GROUP BY'];
1384 $sql .= ' GROUP BY ' . $gb;
1385 }
1386 if ( isset( $options['HAVING'] ) ) {
1387 $having = is_array( $options['HAVING'] )
1388 ? $this->makeList( $options['HAVING'], LIST_AND )
1389 : $options['HAVING'];
1390 $sql .= ' HAVING ' . $having;
1391 }
1392
1393 return $sql;
1394 }
1395
1396 /**
1397 * Returns an optional ORDER BY
1398 *
1399 * @param array $options Associative array of options
1400 * @return string
1401 * @see DatabaseBase::select()
1402 * @since 1.21
1403 */
1404 public function makeOrderBy( $options ) {
1405 if ( isset( $options['ORDER BY'] ) ) {
1406 $ob = is_array( $options['ORDER BY'] )
1407 ? implode( ',', $options['ORDER BY'] )
1408 : $options['ORDER BY'];
1409
1410 return ' ORDER BY ' . $ob;
1411 }
1412
1413 return '';
1414 }
1415
1416 /**
1417 * Execute a SELECT query constructed using the various parameters provided.
1418 * See below for full details of the parameters.
1419 *
1420 * @param string|array $table Table name
1421 * @param string|array $vars Field names
1422 * @param string|array $conds Conditions
1423 * @param string $fname Caller function name
1424 * @param array $options Query options
1425 * @param array $join_conds Join conditions
1426 *
1427 * @param string|array $table
1428 *
1429 * May be either an array of table names, or a single string holding a table
1430 * name. If an array is given, table aliases can be specified, for example:
1431 *
1432 * array( 'a' => 'user' )
1433 *
1434 * This includes the user table in the query, with the alias "a" available
1435 * for use in field names (e.g. a.user_name).
1436 *
1437 * All of the table names given here are automatically run through
1438 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1439 * added, and various other table name mappings to be performed.
1440 *
1441 *
1442 * @param string|array $vars
1443 *
1444 * May be either a field name or an array of field names. The field names
1445 * can be complete fragments of SQL, for direct inclusion into the SELECT
1446 * query. If an array is given, field aliases can be specified, for example:
1447 *
1448 * array( 'maxrev' => 'MAX(rev_id)' )
1449 *
1450 * This includes an expression with the alias "maxrev" in the query.
1451 *
1452 * If an expression is given, care must be taken to ensure that it is
1453 * DBMS-independent.
1454 *
1455 *
1456 * @param string|array $conds
1457 *
1458 * May be either a string containing a single condition, or an array of
1459 * conditions. If an array is given, the conditions constructed from each
1460 * element are combined with AND.
1461 *
1462 * Array elements may take one of two forms:
1463 *
1464 * - Elements with a numeric key are interpreted as raw SQL fragments.
1465 * - Elements with a string key are interpreted as equality conditions,
1466 * where the key is the field name.
1467 * - If the value of such an array element is a scalar (such as a
1468 * string), it will be treated as data and thus quoted appropriately.
1469 * If it is null, an IS NULL clause will be added.
1470 * - If the value is an array, an IN(...) clause will be constructed,
1471 * such that the field name may match any of the elements in the
1472 * array. The elements of the array will be quoted.
1473 *
1474 * Note that expressions are often DBMS-dependent in their syntax.
1475 * DBMS-independent wrappers are provided for constructing several types of
1476 * expression commonly used in condition queries. See:
1477 * - DatabaseBase::buildLike()
1478 * - DatabaseBase::conditional()
1479 *
1480 *
1481 * @param string|array $options
1482 *
1483 * Optional: Array of query options. Boolean options are specified by
1484 * including them in the array as a string value with a numeric key, for
1485 * example:
1486 *
1487 * array( 'FOR UPDATE' )
1488 *
1489 * The supported options are:
1490 *
1491 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1492 * with LIMIT can theoretically be used for paging through a result set,
1493 * but this is discouraged in MediaWiki for performance reasons.
1494 *
1495 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1496 * and then the first rows are taken until the limit is reached. LIMIT
1497 * is applied to a result set after OFFSET.
1498 *
1499 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1500 * changed until the next COMMIT.
1501 *
1502 * - DISTINCT: Boolean: return only unique result rows.
1503 *
1504 * - GROUP BY: May be either an SQL fragment string naming a field or
1505 * expression to group by, or an array of such SQL fragments.
1506 *
1507 * - HAVING: May be either an string containing a HAVING clause or an array of
1508 * conditions building the HAVING clause. If an array is given, the conditions
1509 * constructed from each element are combined with AND.
1510 *
1511 * - ORDER BY: May be either an SQL fragment giving a field name or
1512 * expression to order by, or an array of such SQL fragments.
1513 *
1514 * - USE INDEX: This may be either a string giving the index name to use
1515 * for the query, or an array. If it is an associative array, each key
1516 * gives the table name (or alias), each value gives the index name to
1517 * use for that table. All strings are SQL fragments and so should be
1518 * validated by the caller.
1519 *
1520 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1521 * instead of SELECT.
1522 *
1523 * And also the following boolean MySQL extensions, see the MySQL manual
1524 * for documentation:
1525 *
1526 * - LOCK IN SHARE MODE
1527 * - STRAIGHT_JOIN
1528 * - HIGH_PRIORITY
1529 * - SQL_BIG_RESULT
1530 * - SQL_BUFFER_RESULT
1531 * - SQL_SMALL_RESULT
1532 * - SQL_CALC_FOUND_ROWS
1533 * - SQL_CACHE
1534 * - SQL_NO_CACHE
1535 *
1536 *
1537 * @param string|array $join_conds
1538 *
1539 * Optional associative array of table-specific join conditions. In the
1540 * most common case, this is unnecessary, since the join condition can be
1541 * in $conds. However, it is useful for doing a LEFT JOIN.
1542 *
1543 * The key of the array contains the table name or alias. The value is an
1544 * array with two elements, numbered 0 and 1. The first gives the type of
1545 * join, the second is an SQL fragment giving the join condition for that
1546 * table. For example:
1547 *
1548 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1549 *
1550 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1551 * with no rows in it will be returned. If there was a query error, a
1552 * DBQueryError exception will be thrown, except if the "ignore errors"
1553 * option was set, in which case false will be returned.
1554 */
1555 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1556 $options = array(), $join_conds = array() ) {
1557 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1558
1559 return $this->query( $sql, $fname );
1560 }
1561
1562 /**
1563 * The equivalent of DatabaseBase::select() except that the constructed SQL
1564 * is returned, instead of being immediately executed. This can be useful for
1565 * doing UNION queries, where the SQL text of each query is needed. In general,
1566 * however, callers outside of Database classes should just use select().
1567 *
1568 * @param string|array $table Table name
1569 * @param string|array $vars Field names
1570 * @param string|array $conds Conditions
1571 * @param string $fname Caller function name
1572 * @param string|array $options Query options
1573 * @param string|array $join_conds Join conditions
1574 *
1575 * @return string SQL query string.
1576 * @see DatabaseBase::select()
1577 */
1578 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1579 $options = array(), $join_conds = array()
1580 ) {
1581 if ( is_array( $vars ) ) {
1582 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1583 }
1584
1585 $options = (array)$options;
1586 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1587 ? $options['USE INDEX']
1588 : array();
1589
1590 if ( is_array( $table ) ) {
1591 $from = ' FROM ' .
1592 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1593 } elseif ( $table != '' ) {
1594 if ( $table[0] == ' ' ) {
1595 $from = ' FROM ' . $table;
1596 } else {
1597 $from = ' FROM ' .
1598 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1599 }
1600 } else {
1601 $from = '';
1602 }
1603
1604 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1605 $this->makeSelectOptions( $options );
1606
1607 if ( !empty( $conds ) ) {
1608 if ( is_array( $conds ) ) {
1609 $conds = $this->makeList( $conds, LIST_AND );
1610 }
1611 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1612 } else {
1613 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1614 }
1615
1616 if ( isset( $options['LIMIT'] ) ) {
1617 $sql = $this->limitResult( $sql, $options['LIMIT'],
1618 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1619 }
1620 $sql = "$sql $postLimitTail";
1621
1622 if ( isset( $options['EXPLAIN'] ) ) {
1623 $sql = 'EXPLAIN ' . $sql;
1624 }
1625
1626 return $sql;
1627 }
1628
1629 /**
1630 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1631 * that a single row object is returned. If the query returns no rows,
1632 * false is returned.
1633 *
1634 * @param string|array $table Table name
1635 * @param string|array $vars Field names
1636 * @param array $conds Conditions
1637 * @param string $fname Caller function name
1638 * @param string|array $options Query options
1639 * @param array|string $join_conds Join conditions
1640 *
1641 * @return stdClass|bool
1642 */
1643 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1644 $options = array(), $join_conds = array()
1645 ) {
1646 $options = (array)$options;
1647 $options['LIMIT'] = 1;
1648 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1649
1650 if ( $res === false ) {
1651 return false;
1652 }
1653
1654 if ( !$this->numRows( $res ) ) {
1655 return false;
1656 }
1657
1658 $obj = $this->fetchObject( $res );
1659
1660 return $obj;
1661 }
1662
1663 /**
1664 * Estimate rows in dataset.
1665 *
1666 * MySQL allows you to estimate the number of rows that would be returned
1667 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1668 * index cardinality statistics, and is notoriously inaccurate, especially
1669 * when large numbers of rows have recently been added or deleted.
1670 *
1671 * For DBMSs that don't support fast result size estimation, this function
1672 * will actually perform the SELECT COUNT(*).
1673 *
1674 * Takes the same arguments as DatabaseBase::select().
1675 *
1676 * @param string $table Table name
1677 * @param string $vars Unused
1678 * @param array|string $conds Filters on the table
1679 * @param string $fname Function name for profiling
1680 * @param array $options Options for select
1681 * @return int Row count
1682 */
1683 public function estimateRowCount( $table, $vars = '*', $conds = '',
1684 $fname = __METHOD__, $options = array()
1685 ) {
1686 $rows = 0;
1687 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1688
1689 if ( $res ) {
1690 $row = $this->fetchRow( $res );
1691 $rows = ( isset( $row['rowcount'] ) ) ? $row['rowcount'] : 0;
1692 }
1693
1694 return $rows;
1695 }
1696
1697 /**
1698 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1699 * It's only slightly flawed. Don't use for anything important.
1700 *
1701 * @param string $sql A SQL Query
1702 *
1703 * @return string
1704 */
1705 static function generalizeSQL( $sql ) {
1706 # This does the same as the regexp below would do, but in such a way
1707 # as to avoid crashing php on some large strings.
1708 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1709
1710 $sql = str_replace( "\\\\", '', $sql );
1711 $sql = str_replace( "\\'", '', $sql );
1712 $sql = str_replace( "\\\"", '', $sql );
1713 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1714 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1715
1716 # All newlines, tabs, etc replaced by single space
1717 $sql = preg_replace( '/\s+/', ' ', $sql );
1718
1719 # All numbers => N
1720 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1721 $sql = preg_replace( '/-?\d+/s', 'N', $sql );
1722
1723 return $sql;
1724 }
1725
1726 /**
1727 * Determines whether a field exists in a table
1728 *
1729 * @param string $table Table name
1730 * @param string $field Filed to check on that table
1731 * @param string $fname Calling function name (optional)
1732 * @return bool Whether $table has filed $field
1733 */
1734 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1735 $info = $this->fieldInfo( $table, $field );
1736
1737 return (bool)$info;
1738 }
1739
1740 /**
1741 * Determines whether an index exists
1742 * Usually throws a DBQueryError on failure
1743 * If errors are explicitly ignored, returns NULL on failure
1744 *
1745 * @param string $table
1746 * @param string $index
1747 * @param string $fname
1748 * @return bool|null
1749 */
1750 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1751 if ( !$this->tableExists( $table ) ) {
1752 return null;
1753 }
1754
1755 $info = $this->indexInfo( $table, $index, $fname );
1756 if ( is_null( $info ) ) {
1757 return null;
1758 } else {
1759 return $info !== false;
1760 }
1761 }
1762
1763 /**
1764 * Query whether a given table exists
1765 *
1766 * @param string $table
1767 * @param string $fname
1768 * @return bool
1769 */
1770 public function tableExists( $table, $fname = __METHOD__ ) {
1771 $table = $this->tableName( $table );
1772 $old = $this->ignoreErrors( true );
1773 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1774 $this->ignoreErrors( $old );
1775
1776 return (bool)$res;
1777 }
1778
1779 /**
1780 * Determines if a given index is unique
1781 *
1782 * @param string $table
1783 * @param string $index
1784 *
1785 * @return bool
1786 */
1787 public function indexUnique( $table, $index ) {
1788 $indexInfo = $this->indexInfo( $table, $index );
1789
1790 if ( !$indexInfo ) {
1791 return null;
1792 }
1793
1794 return !$indexInfo[0]->Non_unique;
1795 }
1796
1797 /**
1798 * Helper for DatabaseBase::insert().
1799 *
1800 * @param array $options
1801 * @return string
1802 */
1803 protected function makeInsertOptions( $options ) {
1804 return implode( ' ', $options );
1805 }
1806
1807 /**
1808 * INSERT wrapper, inserts an array into a table.
1809 *
1810 * $a may be either:
1811 *
1812 * - A single associative array. The array keys are the field names, and
1813 * the values are the values to insert. The values are treated as data
1814 * and will be quoted appropriately. If NULL is inserted, this will be
1815 * converted to a database NULL.
1816 * - An array with numeric keys, holding a list of associative arrays.
1817 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1818 * each subarray must be identical to each other, and in the same order.
1819 *
1820 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1821 * returns success.
1822 *
1823 * $options is an array of options, with boolean options encoded as values
1824 * with numeric keys, in the same style as $options in
1825 * DatabaseBase::select(). Supported options are:
1826 *
1827 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1828 * any rows which cause duplicate key errors are not inserted. It's
1829 * possible to determine how many rows were successfully inserted using
1830 * DatabaseBase::affectedRows().
1831 *
1832 * @param string $table Table name. This will be passed through
1833 * DatabaseBase::tableName().
1834 * @param array $a Array of rows to insert
1835 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1836 * @param array $options of options
1837 *
1838 * @return bool
1839 */
1840 public function insert( $table, $a, $fname = __METHOD__, $options = array() ) {
1841 # No rows to insert, easy just return now
1842 if ( !count( $a ) ) {
1843 return true;
1844 }
1845
1846 $table = $this->tableName( $table );
1847
1848 if ( !is_array( $options ) ) {
1849 $options = array( $options );
1850 }
1851
1852 $fh = null;
1853 if ( isset( $options['fileHandle'] ) ) {
1854 $fh = $options['fileHandle'];
1855 }
1856 $options = $this->makeInsertOptions( $options );
1857
1858 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1859 $multi = true;
1860 $keys = array_keys( $a[0] );
1861 } else {
1862 $multi = false;
1863 $keys = array_keys( $a );
1864 }
1865
1866 $sql = 'INSERT ' . $options .
1867 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1868
1869 if ( $multi ) {
1870 $first = true;
1871 foreach ( $a as $row ) {
1872 if ( $first ) {
1873 $first = false;
1874 } else {
1875 $sql .= ',';
1876 }
1877 $sql .= '(' . $this->makeList( $row ) . ')';
1878 }
1879 } else {
1880 $sql .= '(' . $this->makeList( $a ) . ')';
1881 }
1882
1883 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1884 return false;
1885 } elseif ( $fh !== null ) {
1886 return true;
1887 }
1888
1889 return (bool)$this->query( $sql, $fname );
1890 }
1891
1892 /**
1893 * Make UPDATE options for the DatabaseBase::update function
1894 *
1895 * @param array $options The options passed to DatabaseBase::update
1896 * @return string
1897 */
1898 protected function makeUpdateOptions( $options ) {
1899 if ( !is_array( $options ) ) {
1900 $options = array( $options );
1901 }
1902
1903 $opts = array();
1904
1905 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1906 $opts[] = $this->lowPriorityOption();
1907 }
1908
1909 if ( in_array( 'IGNORE', $options ) ) {
1910 $opts[] = 'IGNORE';
1911 }
1912
1913 return implode( ' ', $opts );
1914 }
1915
1916 /**
1917 * UPDATE wrapper. Takes a condition array and a SET array.
1918 *
1919 * @param string $table Name of the table to UPDATE. This will be passed through
1920 * DatabaseBase::tableName().
1921 * @param array $values An array of values to SET. For each array element,
1922 * the key gives the field name, and the value gives the data to set
1923 * that field to. The data will be quoted by DatabaseBase::addQuotes().
1924 * @param array $conds An array of conditions (WHERE). See
1925 * DatabaseBase::select() for the details of the format of condition
1926 * arrays. Use '*' to update all rows.
1927 * @param string $fname The function name of the caller (from __METHOD__),
1928 * for logging and profiling.
1929 * @param array $options An array of UPDATE options, can be:
1930 * - IGNORE: Ignore unique key conflicts
1931 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1932 * @return bool
1933 */
1934 function update( $table, $values, $conds, $fname = __METHOD__, $options = array() ) {
1935 $table = $this->tableName( $table );
1936 $opts = $this->makeUpdateOptions( $options );
1937 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1938
1939 if ( $conds !== array() && $conds !== '*' ) {
1940 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1941 }
1942
1943 return $this->query( $sql, $fname );
1944 }
1945
1946 /**
1947 * Makes an encoded list of strings from an array
1948 *
1949 * @param array $a Containing the data
1950 * @param int $mode Constant
1951 * - LIST_COMMA: Comma separated, no field names
1952 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
1953 * documentation for $conds in DatabaseBase::select().
1954 * - LIST_OR: ORed WHERE clause (without the WHERE)
1955 * - LIST_SET: Comma separated with field names, like a SET clause
1956 * - LIST_NAMES: Comma separated field names
1957 * @throws MWException|DBUnexpectedError
1958 * @return string
1959 */
1960 public function makeList( $a, $mode = LIST_COMMA ) {
1961 if ( !is_array( $a ) ) {
1962 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1963 }
1964
1965 $first = true;
1966 $list = '';
1967
1968 foreach ( $a as $field => $value ) {
1969 if ( !$first ) {
1970 if ( $mode == LIST_AND ) {
1971 $list .= ' AND ';
1972 } elseif ( $mode == LIST_OR ) {
1973 $list .= ' OR ';
1974 } else {
1975 $list .= ',';
1976 }
1977 } else {
1978 $first = false;
1979 }
1980
1981 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
1982 $list .= "($value)";
1983 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
1984 $list .= "$value";
1985 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
1986 if ( count( $value ) == 0 ) {
1987 throw new MWException( __METHOD__ . ": empty input for field $field" );
1988 } elseif ( count( $value ) == 1 ) {
1989 // Special-case single values, as IN isn't terribly efficient
1990 // Don't necessarily assume the single key is 0; we don't
1991 // enforce linear numeric ordering on other arrays here.
1992 $value = array_values( $value );
1993 $list .= $field . " = " . $this->addQuotes( $value[0] );
1994 } else {
1995 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1996 }
1997 } elseif ( $value === null ) {
1998 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1999 $list .= "$field IS ";
2000 } elseif ( $mode == LIST_SET ) {
2001 $list .= "$field = ";
2002 }
2003 $list .= 'NULL';
2004 } else {
2005 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
2006 $list .= "$field = ";
2007 }
2008 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
2009 }
2010 }
2011
2012 return $list;
2013 }
2014
2015 /**
2016 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2017 * The keys on each level may be either integers or strings.
2018 *
2019 * @param array $data organized as 2-d
2020 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2021 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2022 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2023 * @return Mixed: string SQL fragment, or false if no items in array.
2024 */
2025 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2026 $conds = array();
2027
2028 foreach ( $data as $base => $sub ) {
2029 if ( count( $sub ) ) {
2030 $conds[] = $this->makeList(
2031 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2032 LIST_AND );
2033 }
2034 }
2035
2036 if ( $conds ) {
2037 return $this->makeList( $conds, LIST_OR );
2038 } else {
2039 // Nothing to search for...
2040 return false;
2041 }
2042 }
2043
2044 /**
2045 * Return aggregated value alias
2046 *
2047 * @param $valuedata
2048 * @param string $valuename
2049 *
2050 * @return string
2051 */
2052 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2053 return $valuename;
2054 }
2055
2056 /**
2057 * @param string $field
2058 * @return string
2059 */
2060 public function bitNot( $field ) {
2061 return "(~$field)";
2062 }
2063
2064 /**
2065 * @param string $fieldLeft
2066 * @param string $fieldRight
2067 * @return string
2068 */
2069 public function bitAnd( $fieldLeft, $fieldRight ) {
2070 return "($fieldLeft & $fieldRight)";
2071 }
2072
2073 /**
2074 * @param string $fieldLeft
2075 * @param string $fieldRight
2076 * @return string
2077 */
2078 public function bitOr( $fieldLeft, $fieldRight ) {
2079 return "($fieldLeft | $fieldRight)";
2080 }
2081
2082 /**
2083 * Build a concatenation list to feed into a SQL query
2084 * @param array $stringList List of raw SQL expressions; caller is
2085 * responsible for any quoting
2086 * @return string
2087 */
2088 public function buildConcat( $stringList ) {
2089 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2090 }
2091
2092 /**
2093 * Build a GROUP_CONCAT or equivalent statement for a query.
2094 *
2095 * This is useful for combining a field for several rows into a single string.
2096 * NULL values will not appear in the output, duplicated values will appear,
2097 * and the resulting delimiter-separated values have no defined sort order.
2098 * Code using the results may need to use the PHP unique() or sort() methods.
2099 *
2100 * @param string $delim Glue to bind the results together
2101 * @param string|array $table Table name
2102 * @param string $field Field name
2103 * @param string|array $conds Conditions
2104 * @param string|array $join_conds Join conditions
2105 * @return string SQL text
2106 * @since 1.23
2107 */
2108 public function buildGroupConcatField(
2109 $delim, $table, $field, $conds = '', $join_conds = array()
2110 ) {
2111 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2112
2113 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2114 }
2115
2116 /**
2117 * Change the current database
2118 *
2119 * @todo Explain what exactly will fail if this is not overridden.
2120 *
2121 * @param $db
2122 *
2123 * @return bool Success or failure
2124 */
2125 public function selectDB( $db ) {
2126 # Stub. Shouldn't cause serious problems if it's not overridden, but
2127 # if your database engine supports a concept similar to MySQL's
2128 # databases you may as well.
2129 $this->mDBname = $db;
2130
2131 return true;
2132 }
2133
2134 /**
2135 * Get the current DB name
2136 */
2137 public function getDBname() {
2138 return $this->mDBname;
2139 }
2140
2141 /**
2142 * Get the server hostname or IP address
2143 */
2144 public function getServer() {
2145 return $this->mServer;
2146 }
2147
2148 /**
2149 * Format a table name ready for use in constructing an SQL query
2150 *
2151 * This does two important things: it quotes the table names to clean them up,
2152 * and it adds a table prefix if only given a table name with no quotes.
2153 *
2154 * All functions of this object which require a table name call this function
2155 * themselves. Pass the canonical name to such functions. This is only needed
2156 * when calling query() directly.
2157 *
2158 * @param string $name Database table name
2159 * @param string $format One of:
2160 * quoted - Automatically pass the table name through addIdentifierQuotes()
2161 * so that it can be used in a query.
2162 * raw - Do not add identifier quotes to the table name
2163 * @return string Full database name
2164 */
2165 public function tableName( $name, $format = 'quoted' ) {
2166 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
2167 # Skip the entire process when we have a string quoted on both ends.
2168 # Note that we check the end so that we will still quote any use of
2169 # use of `database`.table. But won't break things if someone wants
2170 # to query a database table with a dot in the name.
2171 if ( $this->isQuotedIdentifier( $name ) ) {
2172 return $name;
2173 }
2174
2175 # Lets test for any bits of text that should never show up in a table
2176 # name. Basically anything like JOIN or ON which are actually part of
2177 # SQL queries, but may end up inside of the table value to combine
2178 # sql. Such as how the API is doing.
2179 # Note that we use a whitespace test rather than a \b test to avoid
2180 # any remote case where a word like on may be inside of a table name
2181 # surrounded by symbols which may be considered word breaks.
2182 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2183 return $name;
2184 }
2185
2186 # Split database and table into proper variables.
2187 # We reverse the explode so that database.table and table both output
2188 # the correct table.
2189 $dbDetails = explode( '.', $name, 2 );
2190 if ( count( $dbDetails ) == 2 ) {
2191 list( $database, $table ) = $dbDetails;
2192 # We don't want any prefix added in this case
2193 $prefix = '';
2194 } else {
2195 list( $table ) = $dbDetails;
2196 if ( $wgSharedDB !== null # We have a shared database
2197 && $this->mForeign == false # We're not working on a foreign database
2198 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2199 && in_array( $table, $wgSharedTables ) # A shared table is selected
2200 ) {
2201 $database = $wgSharedDB;
2202 $prefix = $wgSharedPrefix === null ? $this->mTablePrefix : $wgSharedPrefix;
2203 } else {
2204 $database = null;
2205 $prefix = $this->mTablePrefix; # Default prefix
2206 }
2207 }
2208
2209 # Quote $table and apply the prefix if not quoted.
2210 $tableName = "{$prefix}{$table}";
2211 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) ) {
2212 $tableName = $this->addIdentifierQuotes( $tableName );
2213 }
2214
2215 # Quote $database and merge it with the table name if needed
2216 if ( $database !== null ) {
2217 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2218 $database = $this->addIdentifierQuotes( $database );
2219 }
2220 $tableName = $database . '.' . $tableName;
2221 }
2222
2223 return $tableName;
2224 }
2225
2226 /**
2227 * Fetch a number of table names into an array
2228 * This is handy when you need to construct SQL for joins
2229 *
2230 * Example:
2231 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2232 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2233 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2234 *
2235 * @return array
2236 */
2237 public function tableNames() {
2238 $inArray = func_get_args();
2239 $retVal = array();
2240
2241 foreach ( $inArray as $name ) {
2242 $retVal[$name] = $this->tableName( $name );
2243 }
2244
2245 return $retVal;
2246 }
2247
2248 /**
2249 * Fetch a number of table names into an zero-indexed numerical array
2250 * This is handy when you need to construct SQL for joins
2251 *
2252 * Example:
2253 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2254 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2255 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2256 *
2257 * @return array
2258 */
2259 public function tableNamesN() {
2260 $inArray = func_get_args();
2261 $retVal = array();
2262
2263 foreach ( $inArray as $name ) {
2264 $retVal[] = $this->tableName( $name );
2265 }
2266
2267 return $retVal;
2268 }
2269
2270 /**
2271 * Get an aliased table name
2272 * e.g. tableName AS newTableName
2273 *
2274 * @param string $name Table name, see tableName()
2275 * @param string|bool $alias Alias (optional)
2276 * @return string SQL name for aliased table. Will not alias a table to its own name
2277 */
2278 public function tableNameWithAlias( $name, $alias = false ) {
2279 if ( !$alias || $alias == $name ) {
2280 return $this->tableName( $name );
2281 } else {
2282 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2283 }
2284 }
2285
2286 /**
2287 * Gets an array of aliased table names
2288 *
2289 * @param array $tables array( [alias] => table )
2290 * @return string[] See tableNameWithAlias()
2291 */
2292 public function tableNamesWithAlias( $tables ) {
2293 $retval = array();
2294 foreach ( $tables as $alias => $table ) {
2295 if ( is_numeric( $alias ) ) {
2296 $alias = $table;
2297 }
2298 $retval[] = $this->tableNameWithAlias( $table, $alias );
2299 }
2300
2301 return $retval;
2302 }
2303
2304 /**
2305 * Get an aliased field name
2306 * e.g. fieldName AS newFieldName
2307 *
2308 * @param string $name Field name
2309 * @param string|bool $alias Alias (optional)
2310 * @return string SQL name for aliased field. Will not alias a field to its own name
2311 */
2312 public function fieldNameWithAlias( $name, $alias = false ) {
2313 if ( !$alias || (string)$alias === (string)$name ) {
2314 return $name;
2315 } else {
2316 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2317 }
2318 }
2319
2320 /**
2321 * Gets an array of aliased field names
2322 *
2323 * @param array $fields array( [alias] => field )
2324 * @return string[] See fieldNameWithAlias()
2325 */
2326 public function fieldNamesWithAlias( $fields ) {
2327 $retval = array();
2328 foreach ( $fields as $alias => $field ) {
2329 if ( is_numeric( $alias ) ) {
2330 $alias = $field;
2331 }
2332 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2333 }
2334
2335 return $retval;
2336 }
2337
2338 /**
2339 * Get the aliased table name clause for a FROM clause
2340 * which might have a JOIN and/or USE INDEX clause
2341 *
2342 * @param array $tables ( [alias] => table )
2343 * @param array $use_index Same as for select()
2344 * @param array $join_conds Same as for select()
2345 * @return string
2346 */
2347 protected function tableNamesWithUseIndexOrJOIN(
2348 $tables, $use_index = array(), $join_conds = array()
2349 ) {
2350 $ret = array();
2351 $retJOIN = array();
2352 $use_index = (array)$use_index;
2353 $join_conds = (array)$join_conds;
2354
2355 foreach ( $tables as $alias => $table ) {
2356 if ( !is_string( $alias ) ) {
2357 // No alias? Set it equal to the table name
2358 $alias = $table;
2359 }
2360 // Is there a JOIN clause for this table?
2361 if ( isset( $join_conds[$alias] ) ) {
2362 list( $joinType, $conds ) = $join_conds[$alias];
2363 $tableClause = $joinType;
2364 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2365 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2366 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2367 if ( $use != '' ) {
2368 $tableClause .= ' ' . $use;
2369 }
2370 }
2371 $on = $this->makeList( (array)$conds, LIST_AND );
2372 if ( $on != '' ) {
2373 $tableClause .= ' ON (' . $on . ')';
2374 }
2375
2376 $retJOIN[] = $tableClause;
2377 // Is there an INDEX clause for this table?
2378 } elseif ( isset( $use_index[$alias] ) ) {
2379 $tableClause = $this->tableNameWithAlias( $table, $alias );
2380 $tableClause .= ' ' . $this->useIndexClause(
2381 implode( ',', (array)$use_index[$alias] ) );
2382
2383 $ret[] = $tableClause;
2384 } else {
2385 $tableClause = $this->tableNameWithAlias( $table, $alias );
2386
2387 $ret[] = $tableClause;
2388 }
2389 }
2390
2391 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2392 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
2393 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
2394
2395 // Compile our final table clause
2396 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2397 }
2398
2399 /**
2400 * Get the name of an index in a given table
2401 *
2402 * @param string $index
2403 * @return string
2404 */
2405 protected function indexName( $index ) {
2406 // Backwards-compatibility hack
2407 $renamed = array(
2408 'ar_usertext_timestamp' => 'usertext_timestamp',
2409 'un_user_id' => 'user_id',
2410 'un_user_ip' => 'user_ip',
2411 );
2412
2413 if ( isset( $renamed[$index] ) ) {
2414 return $renamed[$index];
2415 } else {
2416 return $index;
2417 }
2418 }
2419
2420 /**
2421 * Adds quotes and backslashes.
2422 *
2423 * @param string $s
2424 * @return string
2425 */
2426 public function addQuotes( $s ) {
2427 if ( $s === null ) {
2428 return 'NULL';
2429 } else {
2430 # This will also quote numeric values. This should be harmless,
2431 # and protects against weird problems that occur when they really
2432 # _are_ strings such as article titles and string->number->string
2433 # conversion is not 1:1.
2434 return "'" . $this->strencode( $s ) . "'";
2435 }
2436 }
2437
2438 /**
2439 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2440 * MySQL uses `backticks` while basically everything else uses double quotes.
2441 * Since MySQL is the odd one out here the double quotes are our generic
2442 * and we implement backticks in DatabaseMysql.
2443 *
2444 * @param string $s
2445 * @return string
2446 */
2447 public function addIdentifierQuotes( $s ) {
2448 return '"' . str_replace( '"', '""', $s ) . '"';
2449 }
2450
2451 /**
2452 * Returns if the given identifier looks quoted or not according to
2453 * the database convention for quoting identifiers .
2454 *
2455 * @param string $name
2456 * @return bool
2457 */
2458 public function isQuotedIdentifier( $name ) {
2459 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2460 }
2461
2462 /**
2463 * @param string $s
2464 * @return string
2465 */
2466 protected function escapeLikeInternal( $s ) {
2467 $s = str_replace( '\\', '\\\\', $s );
2468 $s = $this->strencode( $s );
2469 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
2470
2471 return $s;
2472 }
2473
2474 /**
2475 * LIKE statement wrapper, receives a variable-length argument list with
2476 * parts of pattern to match containing either string literals that will be
2477 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2478 * the function could be provided with an array of aforementioned
2479 * parameters.
2480 *
2481 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2482 * a LIKE clause that searches for subpages of 'My page title'.
2483 * Alternatively:
2484 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2485 * $query .= $dbr->buildLike( $pattern );
2486 *
2487 * @since 1.16
2488 * @return string Fully built LIKE statement
2489 */
2490 public function buildLike() {
2491 $params = func_get_args();
2492
2493 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2494 $params = $params[0];
2495 }
2496
2497 $s = '';
2498
2499 foreach ( $params as $value ) {
2500 if ( $value instanceof LikeMatch ) {
2501 $s .= $value->toString();
2502 } else {
2503 $s .= $this->escapeLikeInternal( $value );
2504 }
2505 }
2506
2507 return " LIKE '" . $s . "' ";
2508 }
2509
2510 /**
2511 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2512 *
2513 * @return LikeMatch
2514 */
2515 public function anyChar() {
2516 return new LikeMatch( '_' );
2517 }
2518
2519 /**
2520 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2521 *
2522 * @return LikeMatch
2523 */
2524 public function anyString() {
2525 return new LikeMatch( '%' );
2526 }
2527
2528 /**
2529 * Returns an appropriately quoted sequence value for inserting a new row.
2530 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2531 * subclass will return an integer, and save the value for insertId()
2532 *
2533 * Any implementation of this function should *not* involve reusing
2534 * sequence numbers created for rolled-back transactions.
2535 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2536 * @param string $seqName
2537 * @return null|int
2538 */
2539 public function nextSequenceValue( $seqName ) {
2540 return null;
2541 }
2542
2543 /**
2544 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2545 * is only needed because a) MySQL must be as efficient as possible due to
2546 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2547 * which index to pick. Anyway, other databases might have different
2548 * indexes on a given table. So don't bother overriding this unless you're
2549 * MySQL.
2550 * @param string $index
2551 * @return string
2552 */
2553 public function useIndexClause( $index ) {
2554 return '';
2555 }
2556
2557 /**
2558 * REPLACE query wrapper.
2559 *
2560 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2561 * except that when there is a duplicate key error, the old row is deleted
2562 * and the new row is inserted in its place.
2563 *
2564 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2565 * perform the delete, we need to know what the unique indexes are so that
2566 * we know how to find the conflicting rows.
2567 *
2568 * It may be more efficient to leave off unique indexes which are unlikely
2569 * to collide. However if you do this, you run the risk of encountering
2570 * errors which wouldn't have occurred in MySQL.
2571 *
2572 * @param string $table The table to replace the row(s) in.
2573 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2574 * a field name or an array of field names
2575 * @param array $rows Can be either a single row to insert, or multiple rows,
2576 * in the same format as for DatabaseBase::insert()
2577 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2578 */
2579 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2580 $quotedTable = $this->tableName( $table );
2581
2582 if ( count( $rows ) == 0 ) {
2583 return;
2584 }
2585
2586 # Single row case
2587 if ( !is_array( reset( $rows ) ) ) {
2588 $rows = array( $rows );
2589 }
2590
2591 foreach ( $rows as $row ) {
2592 # Delete rows which collide
2593 if ( $uniqueIndexes ) {
2594 $sql = "DELETE FROM $quotedTable WHERE ";
2595 $first = true;
2596 foreach ( $uniqueIndexes as $index ) {
2597 if ( $first ) {
2598 $first = false;
2599 $sql .= '( ';
2600 } else {
2601 $sql .= ' ) OR ( ';
2602 }
2603 if ( is_array( $index ) ) {
2604 $first2 = true;
2605 foreach ( $index as $col ) {
2606 if ( $first2 ) {
2607 $first2 = false;
2608 } else {
2609 $sql .= ' AND ';
2610 }
2611 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2612 }
2613 } else {
2614 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2615 }
2616 }
2617 $sql .= ' )';
2618 $this->query( $sql, $fname );
2619 }
2620
2621 # Now insert the row
2622 $this->insert( $table, $row, $fname );
2623 }
2624 }
2625
2626 /**
2627 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2628 * statement.
2629 *
2630 * @param string $table Table name
2631 * @param array|string $rows Row(s) to insert
2632 * @param string $fname Caller function name
2633 *
2634 * @return ResultWrapper
2635 */
2636 protected function nativeReplace( $table, $rows, $fname ) {
2637 $table = $this->tableName( $table );
2638
2639 # Single row case
2640 if ( !is_array( reset( $rows ) ) ) {
2641 $rows = array( $rows );
2642 }
2643
2644 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2645 $first = true;
2646
2647 foreach ( $rows as $row ) {
2648 if ( $first ) {
2649 $first = false;
2650 } else {
2651 $sql .= ',';
2652 }
2653
2654 $sql .= '(' . $this->makeList( $row ) . ')';
2655 }
2656
2657 return $this->query( $sql, $fname );
2658 }
2659
2660 /**
2661 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2662 *
2663 * This updates any conflicting rows (according to the unique indexes) using
2664 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2665 *
2666 * $rows may be either:
2667 * - A single associative array. The array keys are the field names, and
2668 * the values are the values to insert. The values are treated as data
2669 * and will be quoted appropriately. If NULL is inserted, this will be
2670 * converted to a database NULL.
2671 * - An array with numeric keys, holding a list of associative arrays.
2672 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2673 * each subarray must be identical to each other, and in the same order.
2674 *
2675 * It may be more efficient to leave off unique indexes which are unlikely
2676 * to collide. However if you do this, you run the risk of encountering
2677 * errors which wouldn't have occurred in MySQL.
2678 *
2679 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2680 * returns success.
2681 *
2682 * @since 1.22
2683 *
2684 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2685 * @param array $rows A single row or list of rows to insert
2686 * @param array $uniqueIndexes List of single field names or field name tuples
2687 * @param array $set An array of values to SET. For each array element, the
2688 * key gives the field name, and the value gives the data to set that
2689 * field to. The data will be quoted by DatabaseBase::addQuotes().
2690 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2691 * @throws Exception
2692 * @return bool
2693 */
2694 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2695 $fname = __METHOD__
2696 ) {
2697 if ( !count( $rows ) ) {
2698 return true; // nothing to do
2699 }
2700 $rows = is_array( reset( $rows ) ) ? $rows : array( $rows );
2701
2702 if ( count( $uniqueIndexes ) ) {
2703 $clauses = array(); // list WHERE clauses that each identify a single row
2704 foreach ( $rows as $row ) {
2705 foreach ( $uniqueIndexes as $index ) {
2706 $index = is_array( $index ) ? $index : array( $index ); // columns
2707 $rowKey = array(); // unique key to this row
2708 foreach ( $index as $column ) {
2709 $rowKey[$column] = $row[$column];
2710 }
2711 $clauses[] = $this->makeList( $rowKey, LIST_AND );
2712 }
2713 }
2714 $where = array( $this->makeList( $clauses, LIST_OR ) );
2715 } else {
2716 $where = false;
2717 }
2718
2719 $useTrx = !$this->mTrxLevel;
2720 if ( $useTrx ) {
2721 $this->begin( $fname );
2722 }
2723 try {
2724 # Update any existing conflicting row(s)
2725 if ( $where !== false ) {
2726 $ok = $this->update( $table, $set, $where, $fname );
2727 } else {
2728 $ok = true;
2729 }
2730 # Now insert any non-conflicting row(s)
2731 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2732 } catch ( Exception $e ) {
2733 if ( $useTrx ) {
2734 $this->rollback( $fname );
2735 }
2736 throw $e;
2737 }
2738 if ( $useTrx ) {
2739 $this->commit( $fname );
2740 }
2741
2742 return $ok;
2743 }
2744
2745 /**
2746 * DELETE where the condition is a join.
2747 *
2748 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2749 * we use sub-selects
2750 *
2751 * For safety, an empty $conds will not delete everything. If you want to
2752 * delete all rows where the join condition matches, set $conds='*'.
2753 *
2754 * DO NOT put the join condition in $conds.
2755 *
2756 * @param string $delTable The table to delete from.
2757 * @param string $joinTable The other table.
2758 * @param string $delVar The variable to join on, in the first table.
2759 * @param string$joinVar The variable to join on, in the second table.
2760 * @param array $conds Condition array of field names mapped to variables,
2761 * ANDed together in the WHERE clause
2762 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2763 * @throws DBUnexpectedError
2764 */
2765 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2766 $fname = __METHOD__
2767 ) {
2768 if ( !$conds ) {
2769 throw new DBUnexpectedError( $this,
2770 'DatabaseBase::deleteJoin() called with empty $conds' );
2771 }
2772
2773 $delTable = $this->tableName( $delTable );
2774 $joinTable = $this->tableName( $joinTable );
2775 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2776 if ( $conds != '*' ) {
2777 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
2778 }
2779 $sql .= ')';
2780
2781 $this->query( $sql, $fname );
2782 }
2783
2784 /**
2785 * Returns the size of a text field, or -1 for "unlimited"
2786 *
2787 * @param string $table
2788 * @param string $field
2789 * @return int
2790 */
2791 public function textFieldSize( $table, $field ) {
2792 $table = $this->tableName( $table );
2793 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2794 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2795 $row = $this->fetchObject( $res );
2796
2797 $m = array();
2798
2799 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2800 $size = $m[1];
2801 } else {
2802 $size = -1;
2803 }
2804
2805 return $size;
2806 }
2807
2808 /**
2809 * A string to insert into queries to show that they're low-priority, like
2810 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2811 * string and nothing bad should happen.
2812 *
2813 * @return string Returns the text of the low priority option if it is
2814 * supported, or a blank string otherwise
2815 */
2816 public function lowPriorityOption() {
2817 return '';
2818 }
2819
2820 /**
2821 * DELETE query wrapper.
2822 *
2823 * @param array $table Table name
2824 * @param string|array $conds of conditions. See $conds in DatabaseBase::select()
2825 * for the format. Use $conds == "*" to delete all rows
2826 * @param string $fname name of the calling function
2827 * @throws DBUnexpectedError
2828 * @return bool|ResultWrapper
2829 */
2830 public function delete( $table, $conds, $fname = __METHOD__ ) {
2831 if ( !$conds ) {
2832 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2833 }
2834
2835 $table = $this->tableName( $table );
2836 $sql = "DELETE FROM $table";
2837
2838 if ( $conds != '*' ) {
2839 if ( is_array( $conds ) ) {
2840 $conds = $this->makeList( $conds, LIST_AND );
2841 }
2842 $sql .= ' WHERE ' . $conds;
2843 }
2844
2845 return $this->query( $sql, $fname );
2846 }
2847
2848 /**
2849 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2850 * into another table.
2851 *
2852 * @param string $destTable The table name to insert into
2853 * @param string|array $srcTable May be either a table name, or an array of table names
2854 * to include in a join.
2855 *
2856 * @param array $varMap Must be an associative array of the form
2857 * array( 'dest1' => 'source1', ...). Source items may be literals
2858 * rather than field names, but strings should be quoted with
2859 * DatabaseBase::addQuotes()
2860 *
2861 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
2862 * the details of the format of condition arrays. May be "*" to copy the
2863 * whole table.
2864 *
2865 * @param string $fname The function name of the caller, from __METHOD__
2866 *
2867 * @param array $insertOptions Options for the INSERT part of the query, see
2868 * DatabaseBase::insert() for details.
2869 * @param array $selectOptions Options for the SELECT part of the query, see
2870 * DatabaseBase::select() for details.
2871 *
2872 * @return ResultWrapper
2873 */
2874 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2875 $fname = __METHOD__,
2876 $insertOptions = array(), $selectOptions = array()
2877 ) {
2878 $destTable = $this->tableName( $destTable );
2879
2880 if ( !is_array( $insertOptions ) ) {
2881 $insertOptions = array( $insertOptions );
2882 }
2883
2884 $insertOptions = $this->makeInsertOptions( $insertOptions );
2885
2886 if ( !is_array( $selectOptions ) ) {
2887 $selectOptions = array( $selectOptions );
2888 }
2889
2890 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2891
2892 if ( is_array( $srcTable ) ) {
2893 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2894 } else {
2895 $srcTable = $this->tableName( $srcTable );
2896 }
2897
2898 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2899 " SELECT $startOpts " . implode( ',', $varMap ) .
2900 " FROM $srcTable $useIndex ";
2901
2902 if ( $conds != '*' ) {
2903 if ( is_array( $conds ) ) {
2904 $conds = $this->makeList( $conds, LIST_AND );
2905 }
2906 $sql .= " WHERE $conds";
2907 }
2908
2909 $sql .= " $tailOpts";
2910
2911 return $this->query( $sql, $fname );
2912 }
2913
2914 /**
2915 * Construct a LIMIT query with optional offset. This is used for query
2916 * pages. The SQL should be adjusted so that only the first $limit rows
2917 * are returned. If $offset is provided as well, then the first $offset
2918 * rows should be discarded, and the next $limit rows should be returned.
2919 * If the result of the query is not ordered, then the rows to be returned
2920 * are theoretically arbitrary.
2921 *
2922 * $sql is expected to be a SELECT, if that makes a difference.
2923 *
2924 * The version provided by default works in MySQL and SQLite. It will very
2925 * likely need to be overridden for most other DBMSes.
2926 *
2927 * @param string $sql SQL query we will append the limit too
2928 * @param int $limit The SQL limit
2929 * @param int|bool $offset The SQL offset (default false)
2930 * @throws DBUnexpectedError
2931 * @return string
2932 */
2933 public function limitResult( $sql, $limit, $offset = false ) {
2934 if ( !is_numeric( $limit ) ) {
2935 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2936 }
2937
2938 return "$sql LIMIT "
2939 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2940 . "{$limit} ";
2941 }
2942
2943 /**
2944 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2945 * within the UNION construct.
2946 * @return Boolean
2947 */
2948 public function unionSupportsOrderAndLimit() {
2949 return true; // True for almost every DB supported
2950 }
2951
2952 /**
2953 * Construct a UNION query
2954 * This is used for providing overload point for other DB abstractions
2955 * not compatible with the MySQL syntax.
2956 * @param array $sqls SQL statements to combine
2957 * @param bool $all Use UNION ALL
2958 * @return string SQL fragment
2959 */
2960 public function unionQueries( $sqls, $all ) {
2961 $glue = $all ? ') UNION ALL (' : ') UNION (';
2962
2963 return '(' . implode( $glue, $sqls ) . ')';
2964 }
2965
2966 /**
2967 * Returns an SQL expression for a simple conditional. This doesn't need
2968 * to be overridden unless CASE isn't supported in your DBMS.
2969 *
2970 * @param string|array $cond SQL expression which will result in a boolean value
2971 * @param string $trueVal SQL expression to return if true
2972 * @param string $falseVal SQL expression to return if false
2973 * @return string SQL fragment
2974 */
2975 public function conditional( $cond, $trueVal, $falseVal ) {
2976 if ( is_array( $cond ) ) {
2977 $cond = $this->makeList( $cond, LIST_AND );
2978 }
2979
2980 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2981 }
2982
2983 /**
2984 * Returns a comand for str_replace function in SQL query.
2985 * Uses REPLACE() in MySQL
2986 *
2987 * @param string $orig Column to modify
2988 * @param string $old Column to seek
2989 * @param string $new Column to replace with
2990 *
2991 * @return string
2992 */
2993 public function strreplace( $orig, $old, $new ) {
2994 return "REPLACE({$orig}, {$old}, {$new})";
2995 }
2996
2997 /**
2998 * Determines how long the server has been up
2999 * STUB
3000 *
3001 * @return int
3002 */
3003 public function getServerUptime() {
3004 return 0;
3005 }
3006
3007 /**
3008 * Determines if the last failure was due to a deadlock
3009 * STUB
3010 *
3011 * @return bool
3012 */
3013 public function wasDeadlock() {
3014 return false;
3015 }
3016
3017 /**
3018 * Determines if the last failure was due to a lock timeout
3019 * STUB
3020 *
3021 * @return bool
3022 */
3023 public function wasLockTimeout() {
3024 return false;
3025 }
3026
3027 /**
3028 * Determines if the last query error was something that should be dealt
3029 * with by pinging the connection and reissuing the query.
3030 * STUB
3031 *
3032 * @return bool
3033 */
3034 public function wasErrorReissuable() {
3035 return false;
3036 }
3037
3038 /**
3039 * Determines if the last failure was due to the database being read-only.
3040 * STUB
3041 *
3042 * @return bool
3043 */
3044 public function wasReadOnlyError() {
3045 return false;
3046 }
3047
3048 /**
3049 * Perform a deadlock-prone transaction.
3050 *
3051 * This function invokes a callback function to perform a set of write
3052 * queries. If a deadlock occurs during the processing, the transaction
3053 * will be rolled back and the callback function will be called again.
3054 *
3055 * Usage:
3056 * $dbw->deadlockLoop( callback, ... );
3057 *
3058 * Extra arguments are passed through to the specified callback function.
3059 *
3060 * Returns whatever the callback function returned on its successful,
3061 * iteration, or false on error, for example if the retry limit was
3062 * reached.
3063 *
3064 * @return bool
3065 */
3066 public function deadlockLoop() {
3067 $this->begin( __METHOD__ );
3068 $args = func_get_args();
3069 $function = array_shift( $args );
3070 $oldIgnore = $this->ignoreErrors( true );
3071 $tries = self::DEADLOCK_TRIES;
3072
3073 if ( is_array( $function ) ) {
3074 $fname = $function[0];
3075 } else {
3076 $fname = $function;
3077 }
3078
3079 do {
3080 $retVal = call_user_func_array( $function, $args );
3081 $error = $this->lastError();
3082 $errno = $this->lastErrno();
3083 $sql = $this->lastQuery();
3084
3085 if ( $errno ) {
3086 if ( $this->wasDeadlock() ) {
3087 # Retry
3088 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
3089 } else {
3090 $this->reportQueryError( $error, $errno, $sql, $fname );
3091 }
3092 }
3093 } while ( $this->wasDeadlock() && --$tries > 0 );
3094
3095 $this->ignoreErrors( $oldIgnore );
3096
3097 if ( $tries <= 0 ) {
3098 $this->rollback( __METHOD__ );
3099 $this->reportQueryError( $error, $errno, $sql, $fname );
3100
3101 return false;
3102 } else {
3103 $this->commit( __METHOD__ );
3104
3105 return $retVal;
3106 }
3107 }
3108
3109 /**
3110 * Wait for the slave to catch up to a given master position.
3111 *
3112 * @param DBMasterPos $pos
3113 * @param int $timeout The maximum number of seconds to wait for
3114 * synchronisation
3115 * @return int Zzero if the slave was past that position already,
3116 * greater than zero if we waited for some period of time, less than
3117 * zero if we timed out.
3118 */
3119 public function masterPosWait( DBMasterPos $pos, $timeout ) {
3120 wfProfileIn( __METHOD__ );
3121
3122 if ( !is_null( $this->mFakeSlaveLag ) ) {
3123 $wait = intval( ( $pos->pos - microtime( true ) + $this->mFakeSlaveLag ) * 1e6 );
3124
3125 if ( $wait > $timeout * 1e6 ) {
3126 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
3127 wfProfileOut( __METHOD__ );
3128
3129 return -1;
3130 } elseif ( $wait > 0 ) {
3131 wfDebug( "Fake slave waiting $wait us\n" );
3132 usleep( $wait );
3133 wfProfileOut( __METHOD__ );
3134
3135 return 1;
3136 } else {
3137 wfDebug( "Fake slave up to date ($wait us)\n" );
3138 wfProfileOut( __METHOD__ );
3139
3140 return 0;
3141 }
3142 }
3143
3144 wfProfileOut( __METHOD__ );
3145
3146 # Real waits are implemented in the subclass.
3147 return 0;
3148 }
3149
3150 /**
3151 * Get the replication position of this slave
3152 *
3153 * @return DBMasterPos|bool False if this is not a slave.
3154 */
3155 public function getSlavePos() {
3156 if ( !is_null( $this->mFakeSlaveLag ) ) {
3157 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag );
3158 wfDebug( __METHOD__ . ": fake slave pos = $pos\n" );
3159
3160 return $pos;
3161 } else {
3162 # Stub
3163 return false;
3164 }
3165 }
3166
3167 /**
3168 * Get the position of this master
3169 *
3170 * @return DBMasterPos|bool False if this is not a master
3171 */
3172 public function getMasterPos() {
3173 if ( $this->mFakeMaster ) {
3174 return new MySQLMasterPos( 'fake', microtime( true ) );
3175 } else {
3176 return false;
3177 }
3178 }
3179
3180 /**
3181 * Run an anonymous function as soon as there is no transaction pending.
3182 * If there is a transaction and it is rolled back, then the callback is cancelled.
3183 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3184 * Callbacks must commit any transactions that they begin.
3185 *
3186 * This is useful for updates to different systems or when separate transactions are needed.
3187 * For example, one might want to enqueue jobs into a system outside the database, but only
3188 * after the database is updated so that the jobs will see the data when they actually run.
3189 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3190 *
3191 * @param callable $callback
3192 * @since 1.20
3193 */
3194 final public function onTransactionIdle( $callback ) {
3195 $this->mTrxIdleCallbacks[] = array( $callback, wfGetCaller() );
3196 if ( !$this->mTrxLevel ) {
3197 $this->runOnTransactionIdleCallbacks();
3198 }
3199 }
3200
3201 /**
3202 * Run an anonymous function before the current transaction commits or now if there is none.
3203 * If there is a transaction and it is rolled back, then the callback is cancelled.
3204 * Callbacks must not start nor commit any transactions.
3205 *
3206 * This is useful for updates that easily cause deadlocks if locks are held too long
3207 * but where atomicity is strongly desired for these updates and some related updates.
3208 *
3209 * @param callable $callback
3210 * @since 1.22
3211 */
3212 final public function onTransactionPreCommitOrIdle( $callback ) {
3213 if ( $this->mTrxLevel ) {
3214 $this->mTrxPreCommitCallbacks[] = array( $callback, wfGetCaller() );
3215 } else {
3216 $this->onTransactionIdle( $callback ); // this will trigger immediately
3217 }
3218 }
3219
3220 /**
3221 * Actually any "on transaction idle" callbacks.
3222 *
3223 * @since 1.20
3224 */
3225 protected function runOnTransactionIdleCallbacks() {
3226 $autoTrx = $this->getFlag( DBO_TRX ); // automatic begin() enabled?
3227
3228 $e = null; // last exception
3229 do { // callbacks may add callbacks :)
3230 $callbacks = $this->mTrxIdleCallbacks;
3231 $this->mTrxIdleCallbacks = array(); // recursion guard
3232 foreach ( $callbacks as $callback ) {
3233 try {
3234 list( $phpCallback ) = $callback;
3235 $this->clearFlag( DBO_TRX ); // make each query its own transaction
3236 call_user_func( $phpCallback );
3237 $this->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
3238 } catch ( Exception $e ) {
3239 }
3240 }
3241 } while ( count( $this->mTrxIdleCallbacks ) );
3242
3243 if ( $e instanceof Exception ) {
3244 throw $e; // re-throw any last exception
3245 }
3246 }
3247
3248 /**
3249 * Actually any "on transaction pre-commit" callbacks.
3250 *
3251 * @since 1.22
3252 */
3253 protected function runOnTransactionPreCommitCallbacks() {
3254 $e = null; // last exception
3255 do { // callbacks may add callbacks :)
3256 $callbacks = $this->mTrxPreCommitCallbacks;
3257 $this->mTrxPreCommitCallbacks = array(); // recursion guard
3258 foreach ( $callbacks as $callback ) {
3259 try {
3260 list( $phpCallback ) = $callback;
3261 call_user_func( $phpCallback );
3262 } catch ( Exception $e ) {
3263 }
3264 }
3265 } while ( count( $this->mTrxPreCommitCallbacks ) );
3266
3267 if ( $e instanceof Exception ) {
3268 throw $e; // re-throw any last exception
3269 }
3270 }
3271
3272 /**
3273 * Begin an atomic section of statements
3274 *
3275 * If a transaction has been started already, just keep track of the given
3276 * section name to make sure the transaction is not committed pre-maturely.
3277 * This function can be used in layers (with sub-sections), so use a stack
3278 * to keep track of the different atomic sections. If there is no transaction,
3279 * start one implicitly.
3280 *
3281 * The goal of this function is to create an atomic section of SQL queries
3282 * without having to start a new transaction if it already exists.
3283 *
3284 * Atomic sections are more strict than transactions. With transactions,
3285 * attempting to begin a new transaction when one is already running results
3286 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3287 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3288 * and any database transactions cannot be began or committed until all atomic
3289 * levels are closed. There is no such thing as implicitly opening or closing
3290 * an atomic section.
3291 *
3292 * @since 1.23
3293 * @param string $fname
3294 * @throws DBError
3295 */
3296 final public function startAtomic( $fname = __METHOD__ ) {
3297 if ( !$this->mTrxLevel ) {
3298 $this->begin( $fname );
3299 $this->mTrxAutomatic = true;
3300 $this->mTrxAutomaticAtomic = true;
3301 }
3302
3303 $this->mTrxAtomicLevels->push( $fname );
3304 }
3305
3306 /**
3307 * Ends an atomic section of SQL statements
3308 *
3309 * Ends the next section of atomic SQL statements and commits the transaction
3310 * if necessary.
3311 *
3312 * @since 1.23
3313 * @see DatabaseBase::startAtomic
3314 * @param string $fname
3315 * @throws DBError
3316 */
3317 final public function endAtomic( $fname = __METHOD__ ) {
3318 if ( !$this->mTrxLevel ) {
3319 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3320 }
3321 if ( $this->mTrxAtomicLevels->isEmpty() ||
3322 $this->mTrxAtomicLevels->pop() !== $fname
3323 ) {
3324 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3325 }
3326
3327 if ( $this->mTrxAtomicLevels->isEmpty() && $this->mTrxAutomaticAtomic ) {
3328 $this->commit( $fname, 'flush' );
3329 }
3330 }
3331
3332 /**
3333 * Begin a transaction. If a transaction is already in progress,
3334 * that transaction will be committed before the new transaction is started.
3335 *
3336 * Note that when the DBO_TRX flag is set (which is usually the case for web
3337 * requests, but not for maintenance scripts), any previous database query
3338 * will have started a transaction automatically.
3339 *
3340 * Nesting of transactions is not supported. Attempts to nest transactions
3341 * will cause a warning, unless the current transaction was started
3342 * automatically because of the DBO_TRX flag.
3343 *
3344 * @param string $fname
3345 * @throws DBError
3346 */
3347 final public function begin( $fname = __METHOD__ ) {
3348 global $wgDebugDBTransactions;
3349
3350 if ( $this->mTrxLevel ) { // implicit commit
3351 if ( !$this->mTrxAtomicLevels->isEmpty() ) {
3352 // If the current transaction was an automatic atomic one, then we definitely have
3353 // a problem. Same if there is any unclosed atomic level.
3354 throw new DBUnexpectedError( $this,
3355 "Attempted to start explicit transaction when atomic levels are still open."
3356 );
3357 } elseif ( !$this->mTrxAutomatic ) {
3358 // We want to warn about inadvertently nested begin/commit pairs, but not about
3359 // auto-committing implicit transactions that were started by query() via DBO_TRX
3360 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3361 " performing implicit commit!";
3362 wfWarn( $msg );
3363 wfLogDBError( $msg );
3364 } else {
3365 // if the transaction was automatic and has done write operations,
3366 // log it if $wgDebugDBTransactions is enabled.
3367 if ( $this->mTrxDoneWrites && $wgDebugDBTransactions ) {
3368 wfDebug( "$fname: Automatic transaction with writes in progress" .
3369 " (from {$this->mTrxFname}), performing implicit commit!\n"
3370 );
3371 }
3372 }
3373
3374 $this->runOnTransactionPreCommitCallbacks();
3375 $this->doCommit( $fname );
3376 if ( $this->mTrxDoneWrites ) {
3377 Profiler::instance()->transactionWritingOut( $this->mServer, $this->mDBname );
3378 }
3379 $this->runOnTransactionIdleCallbacks();
3380 }
3381
3382 $this->doBegin( $fname );
3383 $this->mTrxFname = $fname;
3384 $this->mTrxDoneWrites = false;
3385 $this->mTrxAutomatic = false;
3386 $this->mTrxAutomaticAtomic = false;
3387 $this->mTrxAtomicLevels = new SplStack;
3388 $this->mTrxIdleCallbacks = array();
3389 $this->mTrxPreCommitCallbacks = array();
3390 }
3391
3392 /**
3393 * Issues the BEGIN command to the database server.
3394 *
3395 * @see DatabaseBase::begin()
3396 * @param string $fname
3397 */
3398 protected function doBegin( $fname ) {
3399 $this->query( 'BEGIN', $fname );
3400 $this->mTrxLevel = 1;
3401 }
3402
3403 /**
3404 * Commits a transaction previously started using begin().
3405 * If no transaction is in progress, a warning is issued.
3406 *
3407 * Nesting of transactions is not supported.
3408 *
3409 * @param string $fname
3410 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3411 * explicitly committing implicit transactions, or calling commit when no
3412 * transaction is in progress. This will silently break any ongoing
3413 * explicit transaction. Only set the flush flag if you are sure that it
3414 * is safe to ignore these warnings in your context.
3415 * @throws DBUnexpectedError
3416 */
3417 final public function commit( $fname = __METHOD__, $flush = '' ) {
3418 if ( !$this->mTrxAtomicLevels->isEmpty() ) {
3419 // There are still atomic sections open. This cannot be ignored
3420 throw new DBUnexpectedError(
3421 $this,
3422 "Attempted to commit transaction while atomic sections are still open"
3423 );
3424 }
3425
3426 if ( $flush != 'flush' ) {
3427 if ( !$this->mTrxLevel ) {
3428 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3429 } elseif ( $this->mTrxAutomatic ) {
3430 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3431 }
3432 } else {
3433 if ( !$this->mTrxLevel ) {
3434 return; // nothing to do
3435 } elseif ( !$this->mTrxAutomatic ) {
3436 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3437 }
3438 }
3439
3440 $this->runOnTransactionPreCommitCallbacks();
3441 $this->doCommit( $fname );
3442 if ( $this->mTrxDoneWrites ) {
3443 Profiler::instance()->transactionWritingOut( $this->mServer, $this->mDBname );
3444 }
3445 $this->runOnTransactionIdleCallbacks();
3446 }
3447
3448 /**
3449 * Issues the COMMIT command to the database server.
3450 *
3451 * @see DatabaseBase::commit()
3452 * @param string $fname
3453 */
3454 protected function doCommit( $fname ) {
3455 if ( $this->mTrxLevel ) {
3456 $this->query( 'COMMIT', $fname );
3457 $this->mTrxLevel = 0;
3458 }
3459 }
3460
3461 /**
3462 * Rollback a transaction previously started using begin().
3463 * If no transaction is in progress, a warning is issued.
3464 *
3465 * No-op on non-transactional databases.
3466 *
3467 * @param string $fname
3468 */
3469 final public function rollback( $fname = __METHOD__ ) {
3470 if ( !$this->mTrxLevel ) {
3471 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3472 }
3473 $this->doRollback( $fname );
3474 $this->mTrxIdleCallbacks = array(); // cancel
3475 $this->mTrxPreCommitCallbacks = array(); // cancel
3476 $this->mTrxAtomicLevels = new SplStack;
3477 if ( $this->mTrxDoneWrites ) {
3478 Profiler::instance()->transactionWritingOut( $this->mServer, $this->mDBname );
3479 }
3480 }
3481
3482 /**
3483 * Issues the ROLLBACK command to the database server.
3484 *
3485 * @see DatabaseBase::rollback()
3486 * @param string $fname
3487 */
3488 protected function doRollback( $fname ) {
3489 if ( $this->mTrxLevel ) {
3490 $this->query( 'ROLLBACK', $fname, true );
3491 $this->mTrxLevel = 0;
3492 }
3493 }
3494
3495 /**
3496 * Creates a new table with structure copied from existing table
3497 * Note that unlike most database abstraction functions, this function does not
3498 * automatically append database prefix, because it works at a lower
3499 * abstraction level.
3500 * The table names passed to this function shall not be quoted (this
3501 * function calls addIdentifierQuotes when needed).
3502 *
3503 * @param string $oldName Name of table whose structure should be copied
3504 * @param string $newName Name of table to be created
3505 * @param bool $temporary Whether the new table should be temporary
3506 * @param string $fname Calling function name
3507 * @throws MWException
3508 * @return bool True if operation was successful
3509 */
3510 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3511 $fname = __METHOD__
3512 ) {
3513 throw new MWException(
3514 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3515 }
3516
3517 /**
3518 * List all tables on the database
3519 *
3520 * @param string $prefix Only show tables with this prefix, e.g. mw_
3521 * @param string $fname Calling function name
3522 * @throws MWException
3523 */
3524 function listTables( $prefix = null, $fname = __METHOD__ ) {
3525 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3526 }
3527
3528 /**
3529 * Reset the views process cache set by listViews()
3530 * @since 1.22
3531 */
3532 final public function clearViewsCache() {
3533 $this->allViews = null;
3534 }
3535
3536 /**
3537 * Lists all the VIEWs in the database
3538 *
3539 * For caching purposes the list of all views should be stored in
3540 * $this->allViews. The process cache can be cleared with clearViewsCache()
3541 *
3542 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3543 * @param string $fname Name of calling function
3544 * @throws MWException
3545 * @since 1.22
3546 */
3547 public function listViews( $prefix = null, $fname = __METHOD__ ) {
3548 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3549 }
3550
3551 /**
3552 * Differentiates between a TABLE and a VIEW
3553 *
3554 * @param string $name Name of the database-structure to test.
3555 * @throws MWException
3556 * @since 1.22
3557 */
3558 public function isView( $name ) {
3559 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3560 }
3561
3562 /**
3563 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3564 * to the format used for inserting into timestamp fields in this DBMS.
3565 *
3566 * The result is unquoted, and needs to be passed through addQuotes()
3567 * before it can be included in raw SQL.
3568 *
3569 * @param string|int $ts
3570 *
3571 * @return string
3572 */
3573 public function timestamp( $ts = 0 ) {
3574 return wfTimestamp( TS_MW, $ts );
3575 }
3576
3577 /**
3578 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3579 * to the format used for inserting into timestamp fields in this DBMS. If
3580 * NULL is input, it is passed through, allowing NULL values to be inserted
3581 * into timestamp fields.
3582 *
3583 * The result is unquoted, and needs to be passed through addQuotes()
3584 * before it can be included in raw SQL.
3585 *
3586 * @param string|int $ts
3587 *
3588 * @return string
3589 */
3590 public function timestampOrNull( $ts = null ) {
3591 if ( is_null( $ts ) ) {
3592 return null;
3593 } else {
3594 return $this->timestamp( $ts );
3595 }
3596 }
3597
3598 /**
3599 * Take the result from a query, and wrap it in a ResultWrapper if
3600 * necessary. Boolean values are passed through as is, to indicate success
3601 * of write queries or failure.
3602 *
3603 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3604 * resource, and it was necessary to call this function to convert it to
3605 * a wrapper. Nowadays, raw database objects are never exposed to external
3606 * callers, so this is unnecessary in external code. For compatibility with
3607 * old code, ResultWrapper objects are passed through unaltered.
3608 *
3609 * @param bool|ResultWrapper|resource $result
3610 * @return bool|ResultWrapper
3611 */
3612 public function resultObject( $result ) {
3613 if ( empty( $result ) ) {
3614 return false;
3615 } elseif ( $result instanceof ResultWrapper ) {
3616 return $result;
3617 } elseif ( $result === true ) {
3618 // Successful write query
3619 return $result;
3620 } else {
3621 return new ResultWrapper( $this, $result );
3622 }
3623 }
3624
3625 /**
3626 * Ping the server and try to reconnect if it there is no connection
3627 *
3628 * @return bool Success or failure
3629 */
3630 public function ping() {
3631 # Stub. Not essential to override.
3632 return true;
3633 }
3634
3635 /**
3636 * Get slave lag. Currently supported only by MySQL.
3637 *
3638 * Note that this function will generate a fatal error on many
3639 * installations. Most callers should use LoadBalancer::safeGetLag()
3640 * instead.
3641 *
3642 * @return int Database replication lag in seconds
3643 */
3644 public function getLag() {
3645 return intval( $this->mFakeSlaveLag );
3646 }
3647
3648 /**
3649 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3650 *
3651 * @return int
3652 */
3653 function maxListLen() {
3654 return 0;
3655 }
3656
3657 /**
3658 * Some DBMSs have a special format for inserting into blob fields, they
3659 * don't allow simple quoted strings to be inserted. To insert into such
3660 * a field, pass the data through this function before passing it to
3661 * DatabaseBase::insert().
3662 *
3663 * @param string $b
3664 * @return string
3665 */
3666 public function encodeBlob( $b ) {
3667 return $b;
3668 }
3669
3670 /**
3671 * Some DBMSs return a special placeholder object representing blob fields
3672 * in result objects. Pass the object through this function to return the
3673 * original string.
3674 *
3675 * @param string $b
3676 * @return string
3677 */
3678 public function decodeBlob( $b ) {
3679 return $b;
3680 }
3681
3682 /**
3683 * Override database's default behavior. $options include:
3684 * 'connTimeout' : Set the connection timeout value in seconds.
3685 * May be useful for very long batch queries such as
3686 * full-wiki dumps, where a single query reads out over
3687 * hours or days.
3688 *
3689 * @param array $options
3690 * @return void
3691 */
3692 public function setSessionOptions( array $options ) {
3693 }
3694
3695 /**
3696 * Read and execute SQL commands from a file.
3697 *
3698 * Returns true on success, error string or exception on failure (depending
3699 * on object's error ignore settings).
3700 *
3701 * @param string $filename File name to open
3702 * @param bool|callable $lineCallback Optional function called before reading each line
3703 * @param bool|callable $resultCallback Optional function called for each MySQL result
3704 * @param bool|string $fname Calling function name or false if name should be
3705 * generated dynamically using $filename
3706 * @param bool|callable $inputCallback Optional function called for each
3707 * complete line sent
3708 * @throws Exception|MWException
3709 * @return bool|string
3710 */
3711 public function sourceFile(
3712 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3713 ) {
3714 wfSuppressWarnings();
3715 $fp = fopen( $filename, 'r' );
3716 wfRestoreWarnings();
3717
3718 if ( false === $fp ) {
3719 throw new MWException( "Could not open \"{$filename}\".\n" );
3720 }
3721
3722 if ( !$fname ) {
3723 $fname = __METHOD__ . "( $filename )";
3724 }
3725
3726 try {
3727 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3728 } catch ( MWException $e ) {
3729 fclose( $fp );
3730 throw $e;
3731 }
3732
3733 fclose( $fp );
3734
3735 return $error;
3736 }
3737
3738 /**
3739 * Get the full path of a patch file. Originally based on archive()
3740 * from updaters.inc. Keep in mind this always returns a patch, as
3741 * it fails back to MySQL if no DB-specific patch can be found
3742 *
3743 * @param string $patch The name of the patch, like patch-something.sql
3744 * @return string Full path to patch file
3745 */
3746 public function patchPath( $patch ) {
3747 global $IP;
3748
3749 $dbType = $this->getType();
3750 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3751 return "$IP/maintenance/$dbType/archives/$patch";
3752 } else {
3753 return "$IP/maintenance/archives/$patch";
3754 }
3755 }
3756
3757 /**
3758 * Set variables to be used in sourceFile/sourceStream, in preference to the
3759 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3760 * all. If it's set to false, $GLOBALS will be used.
3761 *
3762 * @param bool|array $vars Mapping variable name to value.
3763 */
3764 public function setSchemaVars( $vars ) {
3765 $this->mSchemaVars = $vars;
3766 }
3767
3768 /**
3769 * Read and execute commands from an open file handle.
3770 *
3771 * Returns true on success, error string or exception on failure (depending
3772 * on object's error ignore settings).
3773 *
3774 * @param resource $fp File handle
3775 * @param bool|callable $lineCallback Optional function called before reading each query
3776 * @param bool|callable $resultCallback Optional function called for each MySQL result
3777 * @param string $fname Calling function name
3778 * @param bool|callable $inputCallback Optional function called for each complete query sent
3779 * @return bool|string
3780 */
3781 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3782 $fname = __METHOD__, $inputCallback = false
3783 ) {
3784 $cmd = '';
3785
3786 while ( !feof( $fp ) ) {
3787 if ( $lineCallback ) {
3788 call_user_func( $lineCallback );
3789 }
3790
3791 $line = trim( fgets( $fp ) );
3792
3793 if ( $line == '' ) {
3794 continue;
3795 }
3796
3797 if ( '-' == $line[0] && '-' == $line[1] ) {
3798 continue;
3799 }
3800
3801 if ( $cmd != '' ) {
3802 $cmd .= ' ';
3803 }
3804
3805 $done = $this->streamStatementEnd( $cmd, $line );
3806
3807 $cmd .= "$line\n";
3808
3809 if ( $done || feof( $fp ) ) {
3810 $cmd = $this->replaceVars( $cmd );
3811
3812 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) || !$inputCallback ) {
3813 $res = $this->query( $cmd, $fname );
3814
3815 if ( $resultCallback ) {
3816 call_user_func( $resultCallback, $res, $this );
3817 }
3818
3819 if ( false === $res ) {
3820 $err = $this->lastError();
3821
3822 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3823 }
3824 }
3825 $cmd = '';
3826 }
3827 }
3828
3829 return true;
3830 }
3831
3832 /**
3833 * Called by sourceStream() to check if we've reached a statement end
3834 *
3835 * @param string $sql SQL assembled so far
3836 * @param string $newLine New line about to be added to $sql
3837 * @return bool Whether $newLine contains end of the statement
3838 */
3839 public function streamStatementEnd( &$sql, &$newLine ) {
3840 if ( $this->delimiter ) {
3841 $prev = $newLine;
3842 $newLine = preg_replace( '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
3843 if ( $newLine != $prev ) {
3844 return true;
3845 }
3846 }
3847
3848 return false;
3849 }
3850
3851 /**
3852 * Database independent variable replacement. Replaces a set of variables
3853 * in an SQL statement with their contents as given by $this->getSchemaVars().
3854 *
3855 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3856 *
3857 * - '{$var}' should be used for text and is passed through the database's
3858 * addQuotes method.
3859 * - `{$var}` should be used for identifiers (eg: table and database names),
3860 * it is passed through the database's addIdentifierQuotes method which
3861 * can be overridden if the database uses something other than backticks.
3862 * - / *$var* / is just encoded, besides traditional table prefix and
3863 * table options its use should be avoided.
3864 *
3865 * @param string $ins SQL statement to replace variables in
3866 * @return string The new SQL statement with variables replaced
3867 */
3868 protected function replaceSchemaVars( $ins ) {
3869 $vars = $this->getSchemaVars();
3870 foreach ( $vars as $var => $value ) {
3871 // replace '{$var}'
3872 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
3873 // replace `{$var}`
3874 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
3875 // replace /*$var*/
3876 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ), $ins );
3877 }
3878
3879 return $ins;
3880 }
3881
3882 /**
3883 * Replace variables in sourced SQL
3884 *
3885 * @param string $ins
3886 * @return string
3887 */
3888 protected function replaceVars( $ins ) {
3889 $ins = $this->replaceSchemaVars( $ins );
3890
3891 // Table prefixes
3892 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3893 array( $this, 'tableNameCallback' ), $ins );
3894
3895 // Index names
3896 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
3897 array( $this, 'indexNameCallback' ), $ins );
3898
3899 return $ins;
3900 }
3901
3902 /**
3903 * Get schema variables. If none have been set via setSchemaVars(), then
3904 * use some defaults from the current object.
3905 *
3906 * @return array
3907 */
3908 protected function getSchemaVars() {
3909 if ( $this->mSchemaVars ) {
3910 return $this->mSchemaVars;
3911 } else {
3912 return $this->getDefaultSchemaVars();
3913 }
3914 }
3915
3916 /**
3917 * Get schema variables to use if none have been set via setSchemaVars().
3918 *
3919 * Override this in derived classes to provide variables for tables.sql
3920 * and SQL patch files.
3921 *
3922 * @return array
3923 */
3924 protected function getDefaultSchemaVars() {
3925 return array();
3926 }
3927
3928 /**
3929 * Table name callback
3930 *
3931 * @param array $matches
3932 * @return string
3933 */
3934 protected function tableNameCallback( $matches ) {
3935 return $this->tableName( $matches[1] );
3936 }
3937
3938 /**
3939 * Index name callback
3940 *
3941 * @param array $matches
3942 * @return string
3943 */
3944 protected function indexNameCallback( $matches ) {
3945 return $this->indexName( $matches[1] );
3946 }
3947
3948 /**
3949 * Check to see if a named lock is available. This is non-blocking.
3950 *
3951 * @param string $lockName Name of lock to poll
3952 * @param string $method Name of method calling us
3953 * @return bool
3954 * @since 1.20
3955 */
3956 public function lockIsFree( $lockName, $method ) {
3957 return true;
3958 }
3959
3960 /**
3961 * Acquire a named lock
3962 *
3963 * Abstracted from Filestore::lock() so child classes can implement for
3964 * their own needs.
3965 *
3966 * @param string $lockName Name of lock to aquire
3967 * @param string $method Name of method calling us
3968 * @param int $timeout
3969 * @return bool
3970 */
3971 public function lock( $lockName, $method, $timeout = 5 ) {
3972 return true;
3973 }
3974
3975 /**
3976 * Release a lock.
3977 *
3978 * @param string $lockName Name of lock to release
3979 * @param string $method Name of method calling us
3980 *
3981 * @return int Returns 1 if the lock was released, 0 if the lock was not established
3982 * by this thread (in which case the lock is not released), and NULL if the named
3983 * lock did not exist
3984 */
3985 public function unlock( $lockName, $method ) {
3986 return true;
3987 }
3988
3989 /**
3990 * Lock specific tables
3991 *
3992 * @param array $read Array of tables to lock for read access
3993 * @param array $write Array of tables to lock for write access
3994 * @param string $method Name of caller
3995 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3996 * @return bool
3997 */
3998 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3999 return true;
4000 }
4001
4002 /**
4003 * Unlock specific tables
4004 *
4005 * @param string $method The caller
4006 * @return bool
4007 */
4008 public function unlockTables( $method ) {
4009 return true;
4010 }
4011
4012 /**
4013 * Delete a table
4014 * @param string $tableName
4015 * @param string $fName
4016 * @return bool|ResultWrapper
4017 * @since 1.18
4018 */
4019 public function dropTable( $tableName, $fName = __METHOD__ ) {
4020 if ( !$this->tableExists( $tableName, $fName ) ) {
4021 return false;
4022 }
4023 $sql = "DROP TABLE " . $this->tableName( $tableName );
4024 if ( $this->cascadingDeletes() ) {
4025 $sql .= " CASCADE";
4026 }
4027
4028 return $this->query( $sql, $fName );
4029 }
4030
4031 /**
4032 * Get search engine class. All subclasses of this need to implement this
4033 * if they wish to use searching.
4034 *
4035 * @return string
4036 */
4037 public function getSearchEngine() {
4038 return 'SearchEngineDummy';
4039 }
4040
4041 /**
4042 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4043 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4044 * because "i" sorts after all numbers.
4045 *
4046 * @return string
4047 */
4048 public function getInfinity() {
4049 return 'infinity';
4050 }
4051
4052 /**
4053 * Encode an expiry time into the DBMS dependent format
4054 *
4055 * @param string $expiry timestamp for expiry, or the 'infinity' string
4056 * @return string
4057 */
4058 public function encodeExpiry( $expiry ) {
4059 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4060 ? $this->getInfinity()
4061 : $this->timestamp( $expiry );
4062 }
4063
4064 /**
4065 * Decode an expiry time into a DBMS independent format
4066 *
4067 * @param string $expiry DB timestamp field value for expiry
4068 * @param int $format TS_* constant, defaults to TS_MW
4069 * @return string
4070 */
4071 public function decodeExpiry( $expiry, $format = TS_MW ) {
4072 return ( $expiry == '' || $expiry == $this->getInfinity() )
4073 ? 'infinity'
4074 : wfTimestamp( $format, $expiry );
4075 }
4076
4077 /**
4078 * Allow or deny "big selects" for this session only. This is done by setting
4079 * the sql_big_selects session variable.
4080 *
4081 * This is a MySQL-specific feature.
4082 *
4083 * @param bool|string $value True for allow, false for deny, or "default" to
4084 * restore the initial value
4085 */
4086 public function setBigSelects( $value = true ) {
4087 // no-op
4088 }
4089
4090 /**
4091 * @since 1.19
4092 */
4093 public function __toString() {
4094 return (string)$this->mConn;
4095 }
4096
4097 /**
4098 * Run a few simple sanity checks
4099 */
4100 public function __destruct() {
4101 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
4102 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4103 }
4104 if ( count( $this->mTrxIdleCallbacks ) || count( $this->mTrxPreCommitCallbacks ) ) {
4105 $callers = array();
4106 foreach ( $this->mTrxIdleCallbacks as $callbackInfo ) {
4107 $callers[] = $callbackInfo[1];
4108 }
4109 $callers = implode( ', ', $callers );
4110 trigger_error( "DB transaction callbacks still pending (from $callers)." );
4111 }
4112 }
4113 }