4 * @defgroup Database Database
6 * This file deals with database interface functions
7 * and query specifics/optimisations.
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
29 * Interface for classes that implement or wrap DatabaseBase
36 * Database abstraction object
39 abstract class DatabaseBase
implements IDatabase
{
40 /** Number of times to re-try an operation in case of deadlock */
41 const DEADLOCK_TRIES
= 4;
43 /** Minimum time to wait before retry, in microseconds */
44 const DEADLOCK_DELAY_MIN
= 500000;
46 /** Maximum time to wait before retry */
47 const DEADLOCK_DELAY_MAX
= 1500000;
49 protected $mLastQuery = '';
50 protected $mDoneWrites = false;
51 protected $mPHPError = false;
53 protected $mServer, $mUser, $mPassword, $mDBname;
55 /** @var resource Database connection */
56 protected $mConn = null;
57 protected $mOpened = false;
59 /** @var callable[] */
60 protected $mTrxIdleCallbacks = array();
61 /** @var callable[] */
62 protected $mTrxPreCommitCallbacks = array();
64 protected $mTablePrefix;
68 protected $mErrorCount = 0;
69 protected $mLBInfo = array();
70 protected $mDefaultBigSelects = null;
71 protected $mSchemaVars = false;
73 protected $mSessionVars = array();
75 protected $preparedArgs;
77 protected $htmlErrors;
79 protected $delimiter = ';';
82 * Either 1 if a transaction is active or 0 otherwise.
83 * The other Trx fields may not be meaningfull if this is 0.
87 protected $mTrxLevel = 0;
90 * Either a short hexidecimal string if a transaction is active or ""
93 * @see DatabaseBase::mTrxLevel
95 protected $mTrxShortId = '';
98 * The UNIX time that the transaction started. Callers can assume that if
99 * snapshot isolation is used, then the data is *at least* up to date to that
100 * point (possibly more up-to-date since the first SELECT defines the snapshot).
103 * @see DatabaseBase::mTrxLevel
105 private $mTrxTimestamp = null;
108 * Remembers the function name given for starting the most recent transaction via begin().
109 * Used to provide additional context for error reporting.
112 * @see DatabaseBase::mTrxLevel
114 private $mTrxFname = null;
117 * Record if possible write queries were done in the last transaction started
120 * @see DatabaseBase::mTrxLevel
122 private $mTrxDoneWrites = false;
125 * Record if the current transaction was started implicitly due to DBO_TRX being set.
128 * @see DatabaseBase::mTrxLevel
130 private $mTrxAutomatic = false;
133 * Array of levels of atomicity within transactions
137 private $mTrxAtomicLevels;
140 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
144 private $mTrxAutomaticAtomic = false;
147 * Track the seconds spent in write queries for the current transaction
151 private $mTrxWriteDuration = 0.0;
155 * @var resource File handle for upgrade
157 protected $fileHandle = null;
161 * @var string[] Process cache of VIEWs names in the database
163 protected $allViews = null;
165 /** @var TransactionProfiler */
166 protected $trxProfiler;
169 * A string describing the current software version, and possibly
170 * other details in a user-friendly way. Will be listed on Special:Version, etc.
171 * Use getServerVersion() to get machine-friendly information.
173 * @return string Version information from the database server
175 public function getServerInfo() {
176 return $this->getServerVersion();
180 * @return string Command delimiter used by this database engine
182 public function getDelimiter() {
183 return $this->delimiter
;
187 * Boolean, controls output of large amounts of debug information.
188 * @param bool|null $debug
189 * - true to enable debugging
190 * - false to disable debugging
191 * - omitted or null to do nothing
193 * @return bool|null Previous value of the flag
195 public function debug( $debug = null ) {
196 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
200 * Turns buffering of SQL result sets on (true) or off (false). Default is
203 * Unbuffered queries are very troublesome in MySQL:
205 * - If another query is executed while the first query is being read
206 * out, the first query is killed. This means you can't call normal
207 * MediaWiki functions while you are reading an unbuffered query result
208 * from a normal wfGetDB() connection.
210 * - Unbuffered queries cause the MySQL server to use large amounts of
211 * memory and to hold broad locks which block other queries.
213 * If you want to limit client-side memory, it's almost always better to
214 * split up queries into batches using a LIMIT clause than to switch off
217 * @param null|bool $buffer
218 * @return null|bool The previous value of the flag
220 public function bufferResults( $buffer = null ) {
221 if ( is_null( $buffer ) ) {
222 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
224 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
229 * Turns on (false) or off (true) the automatic generation and sending
230 * of a "we're sorry, but there has been a database error" page on
231 * database errors. Default is on (false). When turned off, the
232 * code should use lastErrno() and lastError() to handle the
233 * situation as appropriate.
235 * Do not use this function outside of the Database classes.
237 * @param null|bool $ignoreErrors
238 * @return bool The previous value of the flag.
240 public function ignoreErrors( $ignoreErrors = null ) {
241 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
245 * Gets the current transaction level.
247 * Historically, transactions were allowed to be "nested". This is no
248 * longer supported, so this function really only returns a boolean.
250 * @return int The previous value
252 public function trxLevel() {
253 return $this->mTrxLevel
;
257 * Get the UNIX timestamp of the time that the transaction was established
259 * This can be used to reason about the staleness of SELECT data
260 * in REPEATABLE-READ transaction isolation level.
262 * @return float|null Returns null if there is not active transaction
265 public function trxTimestamp() {
266 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
270 * Get/set the number of errors logged. Only useful when errors are ignored
271 * @param int $count The count to set, or omitted to leave it unchanged.
272 * @return int The error count
274 public function errorCount( $count = null ) {
275 return wfSetVar( $this->mErrorCount
, $count );
279 * Get/set the table prefix.
280 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
281 * @return string The previous table prefix.
283 public function tablePrefix( $prefix = null ) {
284 return wfSetVar( $this->mTablePrefix
, $prefix );
288 * Get/set the db schema.
289 * @param string $schema The database schema to set, or omitted to leave it unchanged.
290 * @return string The previous db schema.
292 public function dbSchema( $schema = null ) {
293 return wfSetVar( $this->mSchema
, $schema );
297 * Set the filehandle to copy write statements to.
299 * @param resource $fh File handle
301 public function setFileHandle( $fh ) {
302 $this->fileHandle
= $fh;
306 * Get properties passed down from the server info array of the load
309 * @param string $name The entry of the info array to get, or null to get the
312 * @return array|mixed|null
314 public function getLBInfo( $name = null ) {
315 if ( is_null( $name ) ) {
316 return $this->mLBInfo
;
318 if ( array_key_exists( $name, $this->mLBInfo
) ) {
319 return $this->mLBInfo
[$name];
327 * Set the LB info array, or a member of it. If called with one parameter,
328 * the LB info array is set to that parameter. If it is called with two
329 * parameters, the member with the given name is set to the given value.
331 * @param string $name
332 * @param array $value
334 public function setLBInfo( $name, $value = null ) {
335 if ( is_null( $value ) ) {
336 $this->mLBInfo
= $name;
338 $this->mLBInfo
[$name] = $value;
343 * Set lag time in seconds for a fake slave
345 * @param mixed $lag Valid values for this parameter are determined by the
346 * subclass, but should be a PHP scalar or array that would be sensible
347 * as part of $wgLBFactoryConf.
349 public function setFakeSlaveLag( $lag ) {
353 * Make this connection a fake master
355 * @param bool $enabled
357 public function setFakeMaster( $enabled = true ) {
361 * @return TransactionProfiler
363 protected function getTransactionProfiler() {
364 return $this->trxProfiler
366 : Profiler
::instance()->getTransactionProfiler();
370 * Returns true if this database supports (and uses) cascading deletes
374 public function cascadingDeletes() {
379 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
383 public function cleanupTriggers() {
388 * Returns true if this database is strict about what can be put into an IP field.
389 * Specifically, it uses a NULL value instead of an empty string.
393 public function strictIPs() {
398 * Returns true if this database uses timestamps rather than integers
402 public function realTimestamps() {
407 * Returns true if this database does an implicit sort when doing GROUP BY
411 public function implicitGroupby() {
416 * Returns true if this database does an implicit order by when the column has an index
417 * For example: SELECT page_title FROM page LIMIT 1
421 public function implicitOrderby() {
426 * Returns true if this database can do a native search on IP columns
427 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
431 public function searchableIPs() {
436 * Returns true if this database can use functional indexes
440 public function functionalIndexes() {
445 * Return the last query that went through DatabaseBase::query()
448 public function lastQuery() {
449 return $this->mLastQuery
;
453 * Returns true if the connection may have been used for write queries.
454 * Should return true if unsure.
458 public function doneWrites() {
459 return (bool)$this->mDoneWrites
;
463 * Returns the last time the connection may have been used for write queries.
464 * Should return a timestamp if unsure.
466 * @return int|float UNIX timestamp or false
469 public function lastDoneWrites() {
470 return $this->mDoneWrites ?
: false;
474 * Returns true if there is a transaction open with possible write
475 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
479 public function writesOrCallbacksPending() {
480 return $this->mTrxLevel
&& (
481 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
486 * Get the time spend running write queries for this
488 * High times could be due to scanning, updates, locking, and such
490 * @return float|bool Returns false if not transaction is active
493 public function pendingWriteQueryDuration() {
494 return $this->mTrxLevel ?
$this->mTrxWriteDuration
: false;
498 * Is a connection to the database open?
501 public function isOpen() {
502 return $this->mOpened
;
506 * Set a flag for this connection
508 * @param int $flag DBO_* constants from Defines.php:
509 * - DBO_DEBUG: output some debug info (same as debug())
510 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
511 * - DBO_TRX: automatically start transactions
512 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
513 * and removes it in command line mode
514 * - DBO_PERSISTENT: use persistant database connection
516 public function setFlag( $flag ) {
517 global $wgDebugDBTransactions;
518 $this->mFlags |
= $flag;
519 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
520 wfDebug( "Implicit transactions are now enabled.\n" );
525 * Clear a flag for this connection
527 * @param int $flag DBO_* constants from Defines.php:
528 * - DBO_DEBUG: output some debug info (same as debug())
529 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
530 * - DBO_TRX: automatically start transactions
531 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
532 * and removes it in command line mode
533 * - DBO_PERSISTENT: use persistant database connection
535 public function clearFlag( $flag ) {
536 global $wgDebugDBTransactions;
537 $this->mFlags
&= ~
$flag;
538 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
539 wfDebug( "Implicit transactions are now disabled.\n" );
544 * Returns a boolean whether the flag $flag is set for this connection
546 * @param int $flag DBO_* constants from Defines.php:
547 * - DBO_DEBUG: output some debug info (same as debug())
548 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
549 * - DBO_TRX: automatically start transactions
550 * - DBO_PERSISTENT: use persistant database connection
553 public function getFlag( $flag ) {
554 return !!( $this->mFlags
& $flag );
558 * General read-only accessor
560 * @param string $name
563 public function getProperty( $name ) {
570 public function getWikiID() {
571 if ( $this->mTablePrefix
) {
572 return "{$this->mDBname}-{$this->mTablePrefix}";
574 return $this->mDBname
;
579 * Return a path to the DBMS-specific SQL file if it exists,
580 * otherwise default SQL file
582 * @param string $filename
585 private function getSqlFilePath( $filename ) {
587 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
588 if ( file_exists( $dbmsSpecificFilePath ) ) {
589 return $dbmsSpecificFilePath;
591 return "$IP/maintenance/$filename";
596 * Return a path to the DBMS-specific schema file,
597 * otherwise default to tables.sql
601 public function getSchemaPath() {
602 return $this->getSqlFilePath( 'tables.sql' );
606 * Return a path to the DBMS-specific update key file,
607 * otherwise default to update-keys.sql
611 public function getUpdateKeysPath() {
612 return $this->getSqlFilePath( 'update-keys.sql' );
616 * Get the type of the DBMS, as it appears in $wgDBtype.
620 abstract function getType();
623 * Open a connection to the database. Usually aborts on failure
625 * @param string $server Database server host
626 * @param string $user Database user name
627 * @param string $password Database user password
628 * @param string $dbName Database name
630 * @throws DBConnectionError
632 abstract function open( $server, $user, $password, $dbName );
635 * Fetch the next row from the given result object, in object form.
636 * Fields can be retrieved with $row->fieldname, with fields acting like
638 * If no more rows are available, false is returned.
640 * @param ResultWrapper|stdClass $res Object as returned from DatabaseBase::query(), etc.
641 * @return stdClass|bool
642 * @throws DBUnexpectedError Thrown if the database returns an error
644 abstract function fetchObject( $res );
647 * Fetch the next row from the given result object, in associative array
648 * form. Fields are retrieved with $row['fieldname'].
649 * If no more rows are available, false is returned.
651 * @param ResultWrapper $res Result object as returned from DatabaseBase::query(), etc.
653 * @throws DBUnexpectedError Thrown if the database returns an error
655 abstract function fetchRow( $res );
658 * Get the number of rows in a result object
660 * @param mixed $res A SQL result
663 abstract function numRows( $res );
666 * Get the number of fields in a result object
667 * @see http://www.php.net/mysql_num_fields
669 * @param mixed $res A SQL result
672 abstract function numFields( $res );
675 * Get a field name in a result object
676 * @see http://www.php.net/mysql_field_name
678 * @param mixed $res A SQL result
682 abstract function fieldName( $res, $n );
685 * Get the inserted value of an auto-increment row
687 * The value inserted should be fetched from nextSequenceValue()
690 * $id = $dbw->nextSequenceValue( 'page_page_id_seq' );
691 * $dbw->insert( 'page', array( 'page_id' => $id ) );
692 * $id = $dbw->insertId();
696 abstract function insertId();
699 * Change the position of the cursor in a result object
700 * @see http://www.php.net/mysql_data_seek
702 * @param mixed $res A SQL result
705 abstract function dataSeek( $res, $row );
708 * Get the last error number
709 * @see http://www.php.net/mysql_errno
713 abstract function lastErrno();
716 * Get a description of the last error
717 * @see http://www.php.net/mysql_error
721 abstract function lastError();
724 * mysql_fetch_field() wrapper
725 * Returns false if the field doesn't exist
727 * @param string $table Table name
728 * @param string $field Field name
732 abstract function fieldInfo( $table, $field );
735 * Get information about an index into an object
736 * @param string $table Table name
737 * @param string $index Index name
738 * @param string $fname Calling function name
739 * @return mixed Database-specific index description class or false if the index does not exist
741 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
744 * Get the number of rows affected by the last write query
745 * @see http://www.php.net/mysql_affected_rows
749 abstract function affectedRows();
752 * Wrapper for addslashes()
754 * @param string $s String to be slashed.
755 * @return string Slashed string.
757 abstract function strencode( $s );
760 * Returns a wikitext link to the DB's website, e.g.,
761 * return "[http://www.mysql.com/ MySQL]";
762 * Should at least contain plain text, if for some reason
763 * your database has no website.
765 * @return string Wikitext of a link to the server software's web site
767 abstract function getSoftwareLink();
770 * A string describing the current software version, like from
771 * mysql_get_server_info().
773 * @return string Version information from the database server.
775 abstract function getServerVersion();
780 * FIXME: It is possible to construct a Database object with no associated
781 * connection object, by specifying no parameters to __construct(). This
782 * feature is deprecated and should be removed.
784 * DatabaseBase subclasses should not be constructed directly in external
785 * code. DatabaseBase::factory() should be used instead.
787 * @param array $params Parameters passed from DatabaseBase::factory()
789 function __construct( array $params ) {
790 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode, $wgDebugDBTransactions;
792 $this->mTrxAtomicLevels
= new SplStack
;
794 $server = $params['host'];
795 $user = $params['user'];
796 $password = $params['password'];
797 $dbName = $params['dbname'];
798 $flags = $params['flags'];
799 $tablePrefix = $params['tablePrefix'];
800 $schema = $params['schema'];
801 $foreign = $params['foreign'];
803 $this->mFlags
= $flags;
804 if ( $this->mFlags
& DBO_DEFAULT
) {
805 if ( $wgCommandLineMode ) {
806 $this->mFlags
&= ~DBO_TRX
;
807 if ( $wgDebugDBTransactions ) {
808 wfDebug( "Implicit transaction open disabled.\n" );
811 $this->mFlags |
= DBO_TRX
;
812 if ( $wgDebugDBTransactions ) {
813 wfDebug( "Implicit transaction open enabled.\n" );
818 $this->mSessionVars
= $params['variables'];
820 /** Get the default table prefix*/
821 if ( $tablePrefix === 'get from global' ) {
822 $this->mTablePrefix
= $wgDBprefix;
824 $this->mTablePrefix
= $tablePrefix;
827 /** Get the database schema*/
828 if ( $schema === 'get from global' ) {
829 $this->mSchema
= $wgDBmwschema;
831 $this->mSchema
= $schema;
834 $this->mForeign
= $foreign;
836 if ( isset( $params['trxProfiler'] ) ) {
837 $this->trxProfiler
= $params['trxProfiler']; // override
841 $this->open( $server, $user, $password, $dbName );
846 * Called by serialize. Throw an exception when DB connection is serialized.
847 * This causes problems on some database engines because the connection is
848 * not restored on unserialize.
850 public function __sleep() {
851 throw new MWException( 'Database serialization may cause problems, since ' .
852 'the connection is not restored on wakeup.' );
856 * Given a DB type, construct the name of the appropriate child class of
857 * DatabaseBase. This is designed to replace all of the manual stuff like:
858 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
859 * as well as validate against the canonical list of DB types we have
861 * This factory function is mostly useful for when you need to connect to a
862 * database other than the MediaWiki default (such as for external auth,
863 * an extension, et cetera). Do not use this to connect to the MediaWiki
864 * database. Example uses in core:
865 * @see LoadBalancer::reallyOpenConnection()
866 * @see ForeignDBRepo::getMasterDB()
867 * @see WebInstallerDBConnect::execute()
871 * @param string $dbType A possible DB type
872 * @param array $p An array of options to pass to the constructor.
873 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
874 * @throws MWException If the database driver or extension cannot be found
875 * @return DatabaseBase|null DatabaseBase subclass or null
877 final public static function factory( $dbType, $p = array() ) {
878 $canonicalDBTypes = array(
879 'mysql' => array( 'mysqli', 'mysql' ),
880 'postgres' => array(),
887 $dbType = strtolower( $dbType );
888 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
889 $possibleDrivers = $canonicalDBTypes[$dbType];
890 if ( !empty( $p['driver'] ) ) {
891 if ( in_array( $p['driver'], $possibleDrivers ) ) {
892 $driver = $p['driver'];
894 throw new MWException( __METHOD__
.
895 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
898 foreach ( $possibleDrivers as $posDriver ) {
899 if ( extension_loaded( $posDriver ) ) {
900 $driver = $posDriver;
908 if ( $driver === false ) {
909 throw new MWException( __METHOD__
.
910 " no viable database extension found for type '$dbType'" );
913 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
914 // and everything else doesn't use a schema (e.g. null)
915 // Although postgres and oracle support schemas, we don't use them (yet)
916 // to maintain backwards compatibility
917 $defaultSchemas = array(
918 'mssql' => 'get from global',
921 $class = 'Database' . ucfirst( $driver );
922 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
923 // Resolve some defaults for b/c
924 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
925 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
926 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
927 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
928 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
929 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : array();
930 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global';
931 if ( !isset( $p['schema'] ) ) {
932 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : null;
934 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
936 return new $class( $p );
942 protected function installErrorHandler() {
943 $this->mPHPError
= false;
944 $this->htmlErrors
= ini_set( 'html_errors', '0' );
945 set_error_handler( array( $this, 'connectionErrorHandler' ) );
949 * @return bool|string
951 protected function restoreErrorHandler() {
952 restore_error_handler();
953 if ( $this->htmlErrors
!== false ) {
954 ini_set( 'html_errors', $this->htmlErrors
);
956 if ( $this->mPHPError
) {
957 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
958 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
968 * @param string $errstr
970 public function connectionErrorHandler( $errno, $errstr ) {
971 $this->mPHPError
= $errstr;
975 * Create a log context to pass to wfLogDBError or other logging functions.
977 * @param array $extras Additional data to add to context
980 protected function getLogContext( array $extras = array() ) {
983 'db_server' => $this->mServer
,
984 'db_name' => $this->mDBname
,
985 'db_user' => $this->mUser
,
992 * Closes a database connection.
993 * if it is open : commits any open transactions
995 * @throws MWException
996 * @return bool Operation success. true if already closed.
998 public function close() {
999 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
1000 throw new MWException( "Transaction idle callbacks still pending." );
1002 if ( $this->mConn
) {
1003 if ( $this->trxLevel() ) {
1004 if ( !$this->mTrxAutomatic
) {
1005 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
1006 " performing implicit commit before closing connection!" );
1009 $this->commit( __METHOD__
, 'flush' );
1012 $closed = $this->closeConnection();
1013 $this->mConn
= false;
1017 $this->mOpened
= false;
1023 * Make sure isOpen() returns true as a sanity check
1025 * @throws DBUnexpectedError
1027 protected function assertOpen() {
1028 if ( !$this->isOpen() ) {
1029 throw new DBUnexpectedError( $this, "DB connection was already closed." );
1034 * Closes underlying database connection
1036 * @return bool Whether connection was closed successfully
1038 abstract protected function closeConnection();
1041 * @param string $error Fallback error message, used if none is given by DB
1042 * @throws DBConnectionError
1044 function reportConnectionError( $error = 'Unknown error' ) {
1045 $myError = $this->lastError();
1051 throw new DBConnectionError( $this, $error );
1055 * The DBMS-dependent part of query()
1057 * @param string $sql SQL query.
1058 * @return ResultWrapper|bool Result object to feed to fetchObject,
1059 * fetchRow, ...; or false on failure
1061 abstract protected function doQuery( $sql );
1064 * Determine whether a query writes to the DB.
1065 * Should return true if unsure.
1067 * @param string $sql
1070 public function isWriteQuery( $sql ) {
1071 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
1075 * Determine whether a SQL statement is sensitive to isolation level.
1076 * A SQL statement is considered transactable if its result could vary
1077 * depending on the transaction isolation level. Operational commands
1078 * such as 'SET' and 'SHOW' are not considered to be transactable.
1080 * @param string $sql
1083 public function isTransactableQuery( $sql ) {
1084 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
1085 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
1089 * Run an SQL query and return the result. Normally throws a DBQueryError
1090 * on failure. If errors are ignored, returns false instead.
1092 * In new code, the query wrappers select(), insert(), update(), delete(),
1093 * etc. should be used where possible, since they give much better DBMS
1094 * independence and automatically quote or validate user input in a variety
1095 * of contexts. This function is generally only useful for queries which are
1096 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
1099 * However, the query wrappers themselves should call this function.
1101 * @param string $sql SQL query
1102 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
1103 * comment (you can use __METHOD__ or add some extra info)
1104 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
1105 * maybe best to catch the exception instead?
1106 * @throws MWException
1107 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
1108 * for a successful read query, or false on failure if $tempIgnore set
1110 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
1111 global $wgUser, $wgDebugDBTransactions, $wgDebugDumpSqlLength;
1113 $this->mLastQuery
= $sql;
1115 $isWriteQuery = $this->isWriteQuery( $sql );
1116 if ( $isWriteQuery ) {
1117 if ( !$this->mDoneWrites
) {
1118 wfDebug( __METHOD__
. ': Writes done: ' .
1119 DatabaseBase
::generalizeSQL( $sql ) . "\n" );
1121 # Set a flag indicating that writes have been done
1122 $this->mDoneWrites
= microtime( true );
1125 # Add a comment for easy SHOW PROCESSLIST interpretation
1126 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
1127 $userName = $wgUser->getName();
1128 if ( mb_strlen( $userName ) > 15 ) {
1129 $userName = mb_substr( $userName, 0, 15 ) . '...';
1131 $userName = str_replace( '/', '', $userName );
1136 // Add trace comment to the begin of the sql string, right after the operator.
1137 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
1138 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
1140 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
) && $this->isTransactableQuery( $sql ) ) {
1141 if ( $wgDebugDBTransactions ) {
1142 wfDebug( "Implicit transaction start.\n" );
1144 $this->begin( __METHOD__
. " ($fname)" );
1145 $this->mTrxAutomatic
= true;
1148 # Keep track of whether the transaction has write queries pending
1149 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWriteQuery ) {
1150 $this->mTrxDoneWrites
= true;
1151 $this->getTransactionProfiler()->transactionWritingIn(
1152 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
1155 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1156 # generalizeSQL will probably cut down the query to reasonable
1157 # logging size most of the time. The substr is really just a sanity check.
1159 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1160 $totalProf = 'DatabaseBase::query-master';
1162 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1163 $totalProf = 'DatabaseBase::query';
1165 # Include query transaction state
1166 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
1168 $profiler = Profiler
::instance();
1169 if ( !$profiler instanceof ProfilerStub
) {
1170 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
1171 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
1174 if ( $this->debug() ) {
1178 $sqlx = $wgDebugDumpSqlLength ?
substr( $commentedSql, 0, $wgDebugDumpSqlLength )
1180 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1182 $master = $isMaster ?
'master' : 'slave';
1183 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1186 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
1188 # Avoid fatals if close() was called
1189 $this->assertOpen();
1191 # Do the query and handle errors
1192 $startTime = microtime( true );
1193 $ret = $this->doQuery( $commentedSql );
1194 $queryRuntime = microtime( true ) - $startTime;
1195 # Log the query time and feed it into the DB trx profiler
1196 $this->getTransactionProfiler()->recordQueryCompletion(
1197 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1199 MWDebug
::queryTime( $queryId );
1201 # Try reconnecting if the connection was lost
1202 if ( false === $ret && $this->wasErrorReissuable() ) {
1203 # Transaction is gone, like it or not
1204 $hadTrx = $this->mTrxLevel
; // possible lost transaction
1205 $this->mTrxLevel
= 0;
1206 $this->mTrxIdleCallbacks
= array(); // bug 65263
1207 $this->mTrxPreCommitCallbacks
= array(); // bug 65263
1208 wfDebug( "Connection lost, reconnecting...\n" );
1209 # Stash the last error values since ping() might clear them
1210 $lastError = $this->lastError();
1211 $lastErrno = $this->lastErrno();
1212 if ( $this->ping() ) {
1213 wfDebug( "Reconnected\n" );
1214 $server = $this->getServer();
1215 $msg = __METHOD__
. ": lost connection to $server; reconnected";
1216 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1219 # Leave $ret as false and let an error be reported.
1220 # Callers may catch the exception and continue to use the DB.
1221 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1223 # Should be safe to silently retry (no trx and thus no callbacks)
1224 $startTime = microtime( true );
1225 $ret = $this->doQuery( $commentedSql );
1226 $queryRuntime = microtime( true ) - $startTime;
1227 # Log the query time and feed it into the DB trx profiler
1228 $this->getTransactionProfiler()->recordQueryCompletion(
1229 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1232 wfDebug( "Failed\n" );
1236 if ( false === $ret ) {
1237 $this->reportQueryError(
1238 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1241 $res = $this->resultObject( $ret );
1243 // Destroy profile sections in the opposite order to their creation
1244 $queryProfSection = false;
1245 $totalProfSection = false;
1247 if ( $isWriteQuery && $this->mTrxLevel
) {
1248 $this->mTrxWriteDuration +
= $queryRuntime;
1255 * Report a query error. Log the error, and if neither the object ignore
1256 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1258 * @param string $error
1260 * @param string $sql
1261 * @param string $fname
1262 * @param bool $tempIgnore
1263 * @throws DBQueryError
1265 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1266 ++
$this->mErrorCount
;
1268 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1269 wfDebug( "SQL ERROR (ignored): $error\n" );
1271 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1273 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1274 $this->getLogContext( array(
1275 'method' => __METHOD__
,
1278 'sql1line' => $sql1line,
1282 wfDebug( "SQL ERROR: " . $error . "\n" );
1283 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1288 * Intended to be compatible with the PEAR::DB wrapper functions.
1289 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1291 * ? = scalar value, quoted as necessary
1292 * ! = raw SQL bit (a function for instance)
1293 * & = filename; reads the file and inserts as a blob
1294 * (we don't use this though...)
1296 * @param string $sql
1297 * @param string $func
1301 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1302 /* MySQL doesn't support prepared statements (yet), so just
1303 * pack up the query for reference. We'll manually replace
1306 return array( 'query' => $sql, 'func' => $func );
1310 * Free a prepared query, generated by prepare().
1311 * @param string $prepared
1313 protected function freePrepared( $prepared ) {
1314 /* No-op by default */
1318 * Execute a prepared query with the various arguments
1319 * @param string $prepared The prepared sql
1320 * @param mixed $args Either an array here, or put scalars as varargs
1322 * @return ResultWrapper
1324 public function execute( $prepared, $args = null ) {
1325 if ( !is_array( $args ) ) {
1327 $args = func_get_args();
1328 array_shift( $args );
1331 $sql = $this->fillPrepared( $prepared['query'], $args );
1333 return $this->query( $sql, $prepared['func'] );
1337 * For faking prepared SQL statements on DBs that don't support it directly.
1339 * @param string $preparedQuery A 'preparable' SQL statement
1340 * @param array $args Array of Arguments to fill it with
1341 * @return string Executable SQL
1343 public function fillPrepared( $preparedQuery, $args ) {
1345 $this->preparedArgs
=& $args;
1347 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1348 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1352 * preg_callback func for fillPrepared()
1353 * The arguments should be in $this->preparedArgs and must not be touched
1354 * while we're doing this.
1356 * @param array $matches
1357 * @throws DBUnexpectedError
1360 protected function fillPreparedArg( $matches ) {
1361 switch ( $matches[1] ) {
1370 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1372 switch ( $matches[1] ) {
1374 return $this->addQuotes( $arg );
1378 # return $this->addQuotes( file_get_contents( $arg ) );
1379 throw new DBUnexpectedError(
1381 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1384 throw new DBUnexpectedError(
1386 'Received invalid match. This should never happen!'
1392 * Free a result object returned by query() or select(). It's usually not
1393 * necessary to call this, just use unset() or let the variable holding
1394 * the result object go out of scope.
1396 * @param mixed $res A SQL result
1398 public function freeResult( $res ) {
1402 * A SELECT wrapper which returns a single field from a single result row.
1404 * Usually throws a DBQueryError on failure. If errors are explicitly
1405 * ignored, returns false on failure.
1407 * If no result rows are returned from the query, false is returned.
1409 * @param string|array $table Table name. See DatabaseBase::select() for details.
1410 * @param string $var The field name to select. This must be a valid SQL
1411 * fragment: do not use unvalidated user input.
1412 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1413 * @param string $fname The function name of the caller.
1414 * @param string|array $options The query options. See DatabaseBase::select() for details.
1416 * @return bool|mixed The value from the field, or false on failure.
1418 public function selectField(
1419 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1421 if ( $var === '*' ) { // sanity
1422 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1425 if ( !is_array( $options ) ) {
1426 $options = array( $options );
1429 $options['LIMIT'] = 1;
1431 $res = $this->select( $table, $var, $cond, $fname, $options );
1432 if ( $res === false ||
!$this->numRows( $res ) ) {
1436 $row = $this->fetchRow( $res );
1438 if ( $row !== false ) {
1439 return reset( $row );
1446 * A SELECT wrapper which returns a list of single field values from result rows.
1448 * Usually throws a DBQueryError on failure. If errors are explicitly
1449 * ignored, returns false on failure.
1451 * If no result rows are returned from the query, false is returned.
1453 * @param string|array $table Table name. See DatabaseBase::select() for details.
1454 * @param string $var The field name to select. This must be a valid SQL
1455 * fragment: do not use unvalidated user input.
1456 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1457 * @param string $fname The function name of the caller.
1458 * @param string|array $options The query options. See DatabaseBase::select() for details.
1460 * @return bool|array The values from the field, or false on failure
1463 public function selectFieldValues(
1464 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1466 if ( $var === '*' ) { // sanity
1467 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1470 if ( !is_array( $options ) ) {
1471 $options = array( $options );
1474 $res = $this->select( $table, $var, $cond, $fname, $options );
1475 if ( $res === false ) {
1480 foreach ( $res as $row ) {
1481 $values[] = $row->$var;
1488 * Returns an optional USE INDEX clause to go after the table, and a
1489 * string to go at the end of the query.
1491 * @param array $options Associative array of options to be turned into
1492 * an SQL query, valid keys are listed in the function.
1494 * @see DatabaseBase::select()
1496 public function makeSelectOptions( $options ) {
1497 $preLimitTail = $postLimitTail = '';
1500 $noKeyOptions = array();
1502 foreach ( $options as $key => $option ) {
1503 if ( is_numeric( $key ) ) {
1504 $noKeyOptions[$option] = true;
1508 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1510 $preLimitTail .= $this->makeOrderBy( $options );
1512 // if (isset($options['LIMIT'])) {
1513 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1514 // isset($options['OFFSET']) ? $options['OFFSET']
1518 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1519 $postLimitTail .= ' FOR UPDATE';
1522 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1523 $postLimitTail .= ' LOCK IN SHARE MODE';
1526 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1527 $startOpts .= 'DISTINCT';
1530 # Various MySQL extensions
1531 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1532 $startOpts .= ' /*! STRAIGHT_JOIN */';
1535 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1536 $startOpts .= ' HIGH_PRIORITY';
1539 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1540 $startOpts .= ' SQL_BIG_RESULT';
1543 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1544 $startOpts .= ' SQL_BUFFER_RESULT';
1547 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1548 $startOpts .= ' SQL_SMALL_RESULT';
1551 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1552 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1555 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1556 $startOpts .= ' SQL_CACHE';
1559 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1560 $startOpts .= ' SQL_NO_CACHE';
1563 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1564 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1569 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1573 * Returns an optional GROUP BY with an optional HAVING
1575 * @param array $options Associative array of options
1577 * @see DatabaseBase::select()
1580 public function makeGroupByWithHaving( $options ) {
1582 if ( isset( $options['GROUP BY'] ) ) {
1583 $gb = is_array( $options['GROUP BY'] )
1584 ?
implode( ',', $options['GROUP BY'] )
1585 : $options['GROUP BY'];
1586 $sql .= ' GROUP BY ' . $gb;
1588 if ( isset( $options['HAVING'] ) ) {
1589 $having = is_array( $options['HAVING'] )
1590 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1591 : $options['HAVING'];
1592 $sql .= ' HAVING ' . $having;
1599 * Returns an optional ORDER BY
1601 * @param array $options Associative array of options
1603 * @see DatabaseBase::select()
1606 public function makeOrderBy( $options ) {
1607 if ( isset( $options['ORDER BY'] ) ) {
1608 $ob = is_array( $options['ORDER BY'] )
1609 ?
implode( ',', $options['ORDER BY'] )
1610 : $options['ORDER BY'];
1612 return ' ORDER BY ' . $ob;
1619 * Execute a SELECT query constructed using the various parameters provided.
1620 * See below for full details of the parameters.
1622 * @param string|array $table Table name
1623 * @param string|array $vars Field names
1624 * @param string|array $conds Conditions
1625 * @param string $fname Caller function name
1626 * @param array $options Query options
1627 * @param array $join_conds Join conditions
1630 * @param string|array $table
1632 * May be either an array of table names, or a single string holding a table
1633 * name. If an array is given, table aliases can be specified, for example:
1635 * array( 'a' => 'user' )
1637 * This includes the user table in the query, with the alias "a" available
1638 * for use in field names (e.g. a.user_name).
1640 * All of the table names given here are automatically run through
1641 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1642 * added, and various other table name mappings to be performed.
1645 * @param string|array $vars
1647 * May be either a field name or an array of field names. The field names
1648 * can be complete fragments of SQL, for direct inclusion into the SELECT
1649 * query. If an array is given, field aliases can be specified, for example:
1651 * array( 'maxrev' => 'MAX(rev_id)' )
1653 * This includes an expression with the alias "maxrev" in the query.
1655 * If an expression is given, care must be taken to ensure that it is
1659 * @param string|array $conds
1661 * May be either a string containing a single condition, or an array of
1662 * conditions. If an array is given, the conditions constructed from each
1663 * element are combined with AND.
1665 * Array elements may take one of two forms:
1667 * - Elements with a numeric key are interpreted as raw SQL fragments.
1668 * - Elements with a string key are interpreted as equality conditions,
1669 * where the key is the field name.
1670 * - If the value of such an array element is a scalar (such as a
1671 * string), it will be treated as data and thus quoted appropriately.
1672 * If it is null, an IS NULL clause will be added.
1673 * - If the value is an array, an IN (...) clause will be constructed
1674 * from its non-null elements, and an IS NULL clause will be added
1675 * if null is present, such that the field may match any of the
1676 * elements in the array. The non-null elements will be quoted.
1678 * Note that expressions are often DBMS-dependent in their syntax.
1679 * DBMS-independent wrappers are provided for constructing several types of
1680 * expression commonly used in condition queries. See:
1681 * - DatabaseBase::buildLike()
1682 * - DatabaseBase::conditional()
1685 * @param string|array $options
1687 * Optional: Array of query options. Boolean options are specified by
1688 * including them in the array as a string value with a numeric key, for
1691 * array( 'FOR UPDATE' )
1693 * The supported options are:
1695 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1696 * with LIMIT can theoretically be used for paging through a result set,
1697 * but this is discouraged in MediaWiki for performance reasons.
1699 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1700 * and then the first rows are taken until the limit is reached. LIMIT
1701 * is applied to a result set after OFFSET.
1703 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1704 * changed until the next COMMIT.
1706 * - DISTINCT: Boolean: return only unique result rows.
1708 * - GROUP BY: May be either an SQL fragment string naming a field or
1709 * expression to group by, or an array of such SQL fragments.
1711 * - HAVING: May be either an string containing a HAVING clause or an array of
1712 * conditions building the HAVING clause. If an array is given, the conditions
1713 * constructed from each element are combined with AND.
1715 * - ORDER BY: May be either an SQL fragment giving a field name or
1716 * expression to order by, or an array of such SQL fragments.
1718 * - USE INDEX: This may be either a string giving the index name to use
1719 * for the query, or an array. If it is an associative array, each key
1720 * gives the table name (or alias), each value gives the index name to
1721 * use for that table. All strings are SQL fragments and so should be
1722 * validated by the caller.
1724 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1725 * instead of SELECT.
1727 * And also the following boolean MySQL extensions, see the MySQL manual
1728 * for documentation:
1730 * - LOCK IN SHARE MODE
1734 * - SQL_BUFFER_RESULT
1735 * - SQL_SMALL_RESULT
1736 * - SQL_CALC_FOUND_ROWS
1741 * @param string|array $join_conds
1743 * Optional associative array of table-specific join conditions. In the
1744 * most common case, this is unnecessary, since the join condition can be
1745 * in $conds. However, it is useful for doing a LEFT JOIN.
1747 * The key of the array contains the table name or alias. The value is an
1748 * array with two elements, numbered 0 and 1. The first gives the type of
1749 * join, the second is an SQL fragment giving the join condition for that
1750 * table. For example:
1752 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1754 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1755 * with no rows in it will be returned. If there was a query error, a
1756 * DBQueryError exception will be thrown, except if the "ignore errors"
1757 * option was set, in which case false will be returned.
1759 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1760 $options = array(), $join_conds = array() ) {
1761 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1763 return $this->query( $sql, $fname );
1767 * The equivalent of DatabaseBase::select() except that the constructed SQL
1768 * is returned, instead of being immediately executed. This can be useful for
1769 * doing UNION queries, where the SQL text of each query is needed. In general,
1770 * however, callers outside of Database classes should just use select().
1772 * @param string|array $table Table name
1773 * @param string|array $vars Field names
1774 * @param string|array $conds Conditions
1775 * @param string $fname Caller function name
1776 * @param string|array $options Query options
1777 * @param string|array $join_conds Join conditions
1779 * @return string SQL query string.
1780 * @see DatabaseBase::select()
1782 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1783 $options = array(), $join_conds = array()
1785 if ( is_array( $vars ) ) {
1786 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1789 $options = (array)$options;
1790 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1791 ?
$options['USE INDEX']
1794 if ( is_array( $table ) ) {
1796 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1797 } elseif ( $table != '' ) {
1798 if ( $table[0] == ' ' ) {
1799 $from = ' FROM ' . $table;
1802 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1808 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1809 $this->makeSelectOptions( $options );
1811 if ( !empty( $conds ) ) {
1812 if ( is_array( $conds ) ) {
1813 $conds = $this->makeList( $conds, LIST_AND
);
1815 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1817 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1820 if ( isset( $options['LIMIT'] ) ) {
1821 $sql = $this->limitResult( $sql, $options['LIMIT'],
1822 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1824 $sql = "$sql $postLimitTail";
1826 if ( isset( $options['EXPLAIN'] ) ) {
1827 $sql = 'EXPLAIN ' . $sql;
1834 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1835 * that a single row object is returned. If the query returns no rows,
1836 * false is returned.
1838 * @param string|array $table Table name
1839 * @param string|array $vars Field names
1840 * @param array $conds Conditions
1841 * @param string $fname Caller function name
1842 * @param string|array $options Query options
1843 * @param array|string $join_conds Join conditions
1845 * @return stdClass|bool
1847 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1848 $options = array(), $join_conds = array()
1850 $options = (array)$options;
1851 $options['LIMIT'] = 1;
1852 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1854 if ( $res === false ) {
1858 if ( !$this->numRows( $res ) ) {
1862 $obj = $this->fetchObject( $res );
1868 * Estimate the number of rows in dataset
1870 * MySQL allows you to estimate the number of rows that would be returned
1871 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1872 * index cardinality statistics, and is notoriously inaccurate, especially
1873 * when large numbers of rows have recently been added or deleted.
1875 * For DBMSs that don't support fast result size estimation, this function
1876 * will actually perform the SELECT COUNT(*).
1878 * Takes the same arguments as DatabaseBase::select().
1880 * @param string $table Table name
1881 * @param string $vars Unused
1882 * @param array|string $conds Filters on the table
1883 * @param string $fname Function name for profiling
1884 * @param array $options Options for select
1885 * @return int Row count
1887 public function estimateRowCount(
1888 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1891 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1894 $row = $this->fetchRow( $res );
1895 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1902 * Get the number of rows in dataset
1904 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
1906 * Takes the same arguments as DatabaseBase::select().
1908 * @param string $table Table name
1909 * @param string $vars Unused
1910 * @param array|string $conds Filters on the table
1911 * @param string $fname Function name for profiling
1912 * @param array $options Options for select
1913 * @return int Row count
1916 public function selectRowCount(
1917 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1920 $sql = $this->selectSQLText( $table, '1', $conds, $fname, $options );
1921 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count" );
1924 $row = $this->fetchRow( $res );
1925 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1932 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1933 * It's only slightly flawed. Don't use for anything important.
1935 * @param string $sql A SQL Query
1939 static function generalizeSQL( $sql ) {
1940 # This does the same as the regexp below would do, but in such a way
1941 # as to avoid crashing php on some large strings.
1942 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1944 $sql = str_replace( "\\\\", '', $sql );
1945 $sql = str_replace( "\\'", '', $sql );
1946 $sql = str_replace( "\\\"", '', $sql );
1947 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1948 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1950 # All newlines, tabs, etc replaced by single space
1951 $sql = preg_replace( '/\s+/', ' ', $sql );
1954 # except the ones surrounded by characters, e.g. l10n
1955 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1956 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1962 * Determines whether a field exists in a table
1964 * @param string $table Table name
1965 * @param string $field Filed to check on that table
1966 * @param string $fname Calling function name (optional)
1967 * @return bool Whether $table has filed $field
1969 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1970 $info = $this->fieldInfo( $table, $field );
1976 * Determines whether an index exists
1977 * Usually throws a DBQueryError on failure
1978 * If errors are explicitly ignored, returns NULL on failure
1980 * @param string $table
1981 * @param string $index
1982 * @param string $fname
1985 public function indexExists( $table, $index, $fname = __METHOD__
) {
1986 if ( !$this->tableExists( $table ) ) {
1990 $info = $this->indexInfo( $table, $index, $fname );
1991 if ( is_null( $info ) ) {
1994 return $info !== false;
1999 * Query whether a given table exists
2001 * @param string $table
2002 * @param string $fname
2005 public function tableExists( $table, $fname = __METHOD__
) {
2006 $table = $this->tableName( $table );
2007 $old = $this->ignoreErrors( true );
2008 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
2009 $this->ignoreErrors( $old );
2015 * Determines if a given index is unique
2017 * @param string $table
2018 * @param string $index
2022 public function indexUnique( $table, $index ) {
2023 $indexInfo = $this->indexInfo( $table, $index );
2025 if ( !$indexInfo ) {
2029 return !$indexInfo[0]->Non_unique
;
2033 * Helper for DatabaseBase::insert().
2035 * @param array $options
2038 protected function makeInsertOptions( $options ) {
2039 return implode( ' ', $options );
2043 * INSERT wrapper, inserts an array into a table.
2047 * - A single associative array. The array keys are the field names, and
2048 * the values are the values to insert. The values are treated as data
2049 * and will be quoted appropriately. If NULL is inserted, this will be
2050 * converted to a database NULL.
2051 * - An array with numeric keys, holding a list of associative arrays.
2052 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2053 * each subarray must be identical to each other, and in the same order.
2055 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2058 * $options is an array of options, with boolean options encoded as values
2059 * with numeric keys, in the same style as $options in
2060 * DatabaseBase::select(). Supported options are:
2062 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
2063 * any rows which cause duplicate key errors are not inserted. It's
2064 * possible to determine how many rows were successfully inserted using
2065 * DatabaseBase::affectedRows().
2067 * @param string $table Table name. This will be passed through
2068 * DatabaseBase::tableName().
2069 * @param array $a Array of rows to insert
2070 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2071 * @param array $options Array of options
2075 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
2076 # No rows to insert, easy just return now
2077 if ( !count( $a ) ) {
2081 $table = $this->tableName( $table );
2083 if ( !is_array( $options ) ) {
2084 $options = array( $options );
2088 if ( isset( $options['fileHandle'] ) ) {
2089 $fh = $options['fileHandle'];
2091 $options = $this->makeInsertOptions( $options );
2093 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
2095 $keys = array_keys( $a[0] );
2098 $keys = array_keys( $a );
2101 $sql = 'INSERT ' . $options .
2102 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
2106 foreach ( $a as $row ) {
2112 $sql .= '(' . $this->makeList( $row ) . ')';
2115 $sql .= '(' . $this->makeList( $a ) . ')';
2118 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
2120 } elseif ( $fh !== null ) {
2124 return (bool)$this->query( $sql, $fname );
2128 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
2130 * @param array $options
2133 protected function makeUpdateOptionsArray( $options ) {
2134 if ( !is_array( $options ) ) {
2135 $options = array( $options );
2140 if ( in_array( 'LOW_PRIORITY', $options ) ) {
2141 $opts[] = $this->lowPriorityOption();
2144 if ( in_array( 'IGNORE', $options ) ) {
2152 * Make UPDATE options for the DatabaseBase::update function
2154 * @param array $options The options passed to DatabaseBase::update
2157 protected function makeUpdateOptions( $options ) {
2158 $opts = $this->makeUpdateOptionsArray( $options );
2160 return implode( ' ', $opts );
2164 * UPDATE wrapper. Takes a condition array and a SET array.
2166 * @param string $table Name of the table to UPDATE. This will be passed through
2167 * DatabaseBase::tableName().
2168 * @param array $values An array of values to SET. For each array element,
2169 * the key gives the field name, and the value gives the data to set
2170 * that field to. The data will be quoted by DatabaseBase::addQuotes().
2171 * @param array $conds An array of conditions (WHERE). See
2172 * DatabaseBase::select() for the details of the format of condition
2173 * arrays. Use '*' to update all rows.
2174 * @param string $fname The function name of the caller (from __METHOD__),
2175 * for logging and profiling.
2176 * @param array $options An array of UPDATE options, can be:
2177 * - IGNORE: Ignore unique key conflicts
2178 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
2181 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
2182 $table = $this->tableName( $table );
2183 $opts = $this->makeUpdateOptions( $options );
2184 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
2186 if ( $conds !== array() && $conds !== '*' ) {
2187 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
2190 return $this->query( $sql, $fname );
2194 * Makes an encoded list of strings from an array
2196 * @param array $a Containing the data
2197 * @param int $mode Constant
2198 * - LIST_COMMA: Comma separated, no field names
2199 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2200 * documentation for $conds in DatabaseBase::select().
2201 * - LIST_OR: ORed WHERE clause (without the WHERE)
2202 * - LIST_SET: Comma separated with field names, like a SET clause
2203 * - LIST_NAMES: Comma separated field names
2204 * @throws MWException|DBUnexpectedError
2207 public function makeList( $a, $mode = LIST_COMMA
) {
2208 if ( !is_array( $a ) ) {
2209 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2215 foreach ( $a as $field => $value ) {
2217 if ( $mode == LIST_AND
) {
2219 } elseif ( $mode == LIST_OR
) {
2228 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
2229 $list .= "($value)";
2230 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
2232 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
2233 // Remove null from array to be handled separately if found
2234 $includeNull = false;
2235 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2236 $includeNull = true;
2237 unset( $value[$nullKey] );
2239 if ( count( $value ) == 0 && !$includeNull ) {
2240 throw new MWException( __METHOD__
. ": empty input for field $field" );
2241 } elseif ( count( $value ) == 0 ) {
2242 // only check if $field is null
2243 $list .= "$field IS NULL";
2245 // IN clause contains at least one valid element
2246 if ( $includeNull ) {
2247 // Group subconditions to ensure correct precedence
2250 if ( count( $value ) == 1 ) {
2251 // Special-case single values, as IN isn't terribly efficient
2252 // Don't necessarily assume the single key is 0; we don't
2253 // enforce linear numeric ordering on other arrays here.
2254 $value = array_values( $value );
2255 $list .= $field . " = " . $this->addQuotes( $value[0] );
2257 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2259 // if null present in array, append IS NULL
2260 if ( $includeNull ) {
2261 $list .= " OR $field IS NULL)";
2264 } elseif ( $value === null ) {
2265 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
2266 $list .= "$field IS ";
2267 } elseif ( $mode == LIST_SET
) {
2268 $list .= "$field = ";
2272 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
2273 $list .= "$field = ";
2275 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
2283 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2284 * The keys on each level may be either integers or strings.
2286 * @param array $data Organized as 2-d
2287 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2288 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2289 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2290 * @return string|bool SQL fragment, or false if no items in array
2292 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2295 foreach ( $data as $base => $sub ) {
2296 if ( count( $sub ) ) {
2297 $conds[] = $this->makeList(
2298 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2304 return $this->makeList( $conds, LIST_OR
);
2306 // Nothing to search for...
2312 * Return aggregated value alias
2314 * @param array $valuedata
2315 * @param string $valuename
2319 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2324 * @param string $field
2327 public function bitNot( $field ) {
2332 * @param string $fieldLeft
2333 * @param string $fieldRight
2336 public function bitAnd( $fieldLeft, $fieldRight ) {
2337 return "($fieldLeft & $fieldRight)";
2341 * @param string $fieldLeft
2342 * @param string $fieldRight
2345 public function bitOr( $fieldLeft, $fieldRight ) {
2346 return "($fieldLeft | $fieldRight)";
2350 * Build a concatenation list to feed into a SQL query
2351 * @param array $stringList List of raw SQL expressions; caller is
2352 * responsible for any quoting
2355 public function buildConcat( $stringList ) {
2356 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2360 * Build a GROUP_CONCAT or equivalent statement for a query.
2362 * This is useful for combining a field for several rows into a single string.
2363 * NULL values will not appear in the output, duplicated values will appear,
2364 * and the resulting delimiter-separated values have no defined sort order.
2365 * Code using the results may need to use the PHP unique() or sort() methods.
2367 * @param string $delim Glue to bind the results together
2368 * @param string|array $table Table name
2369 * @param string $field Field name
2370 * @param string|array $conds Conditions
2371 * @param string|array $join_conds Join conditions
2372 * @return string SQL text
2375 public function buildGroupConcatField(
2376 $delim, $table, $field, $conds = '', $join_conds = array()
2378 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2380 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2384 * Change the current database
2386 * @todo Explain what exactly will fail if this is not overridden.
2390 * @return bool Success or failure
2392 public function selectDB( $db ) {
2393 # Stub. Shouldn't cause serious problems if it's not overridden, but
2394 # if your database engine supports a concept similar to MySQL's
2395 # databases you may as well.
2396 $this->mDBname
= $db;
2402 * Get the current DB name
2405 public function getDBname() {
2406 return $this->mDBname
;
2410 * Get the server hostname or IP address
2413 public function getServer() {
2414 return $this->mServer
;
2418 * Format a table name ready for use in constructing an SQL query
2420 * This does two important things: it quotes the table names to clean them up,
2421 * and it adds a table prefix if only given a table name with no quotes.
2423 * All functions of this object which require a table name call this function
2424 * themselves. Pass the canonical name to such functions. This is only needed
2425 * when calling query() directly.
2427 * @param string $name Database table name
2428 * @param string $format One of:
2429 * quoted - Automatically pass the table name through addIdentifierQuotes()
2430 * so that it can be used in a query.
2431 * raw - Do not add identifier quotes to the table name
2432 * @return string Full database name
2434 public function tableName( $name, $format = 'quoted' ) {
2435 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2436 # Skip the entire process when we have a string quoted on both ends.
2437 # Note that we check the end so that we will still quote any use of
2438 # use of `database`.table. But won't break things if someone wants
2439 # to query a database table with a dot in the name.
2440 if ( $this->isQuotedIdentifier( $name ) ) {
2444 # Lets test for any bits of text that should never show up in a table
2445 # name. Basically anything like JOIN or ON which are actually part of
2446 # SQL queries, but may end up inside of the table value to combine
2447 # sql. Such as how the API is doing.
2448 # Note that we use a whitespace test rather than a \b test to avoid
2449 # any remote case where a word like on may be inside of a table name
2450 # surrounded by symbols which may be considered word breaks.
2451 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2455 # Split database and table into proper variables.
2456 # We reverse the explode so that database.table and table both output
2457 # the correct table.
2458 $dbDetails = explode( '.', $name, 3 );
2459 if ( count( $dbDetails ) == 3 ) {
2460 list( $database, $schema, $table ) = $dbDetails;
2461 # We don't want any prefix added in this case
2463 } elseif ( count( $dbDetails ) == 2 ) {
2464 list( $database, $table ) = $dbDetails;
2465 # We don't want any prefix added in this case
2466 # In dbs that support it, $database may actually be the schema
2467 # but that doesn't affect any of the functionality here
2471 list( $table ) = $dbDetails;
2472 if ( $wgSharedDB !== null # We have a shared database
2473 && $this->mForeign
== false # We're not working on a foreign database
2474 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2475 && in_array( $table, $wgSharedTables ) # A shared table is selected
2477 $database = $wgSharedDB;
2478 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
2479 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
2482 $schema = $this->mSchema
; # Default schema
2483 $prefix = $this->mTablePrefix
; # Default prefix
2487 # Quote $table and apply the prefix if not quoted.
2488 # $tableName might be empty if this is called from Database::replaceVars()
2489 $tableName = "{$prefix}{$table}";
2490 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2491 $tableName = $this->addIdentifierQuotes( $tableName );
2494 # Quote $schema and merge it with the table name if needed
2495 if ( strlen( $schema ) ) {
2496 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2497 $schema = $this->addIdentifierQuotes( $schema );
2499 $tableName = $schema . '.' . $tableName;
2502 # Quote $database and merge it with the table name if needed
2503 if ( $database !== null ) {
2504 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2505 $database = $this->addIdentifierQuotes( $database );
2507 $tableName = $database . '.' . $tableName;
2514 * Fetch a number of table names into an array
2515 * This is handy when you need to construct SQL for joins
2518 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2519 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2520 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2524 public function tableNames() {
2525 $inArray = func_get_args();
2528 foreach ( $inArray as $name ) {
2529 $retVal[$name] = $this->tableName( $name );
2536 * Fetch a number of table names into an zero-indexed numerical array
2537 * This is handy when you need to construct SQL for joins
2540 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2541 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2542 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2546 public function tableNamesN() {
2547 $inArray = func_get_args();
2550 foreach ( $inArray as $name ) {
2551 $retVal[] = $this->tableName( $name );
2558 * Get an aliased table name
2559 * e.g. tableName AS newTableName
2561 * @param string $name Table name, see tableName()
2562 * @param string|bool $alias Alias (optional)
2563 * @return string SQL name for aliased table. Will not alias a table to its own name
2565 public function tableNameWithAlias( $name, $alias = false ) {
2566 if ( !$alias ||
$alias == $name ) {
2567 return $this->tableName( $name );
2569 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2574 * Gets an array of aliased table names
2576 * @param array $tables Array( [alias] => table )
2577 * @return string[] See tableNameWithAlias()
2579 public function tableNamesWithAlias( $tables ) {
2581 foreach ( $tables as $alias => $table ) {
2582 if ( is_numeric( $alias ) ) {
2585 $retval[] = $this->tableNameWithAlias( $table, $alias );
2592 * Get an aliased field name
2593 * e.g. fieldName AS newFieldName
2595 * @param string $name Field name
2596 * @param string|bool $alias Alias (optional)
2597 * @return string SQL name for aliased field. Will not alias a field to its own name
2599 public function fieldNameWithAlias( $name, $alias = false ) {
2600 if ( !$alias ||
(string)$alias === (string)$name ) {
2603 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2608 * Gets an array of aliased field names
2610 * @param array $fields Array( [alias] => field )
2611 * @return string[] See fieldNameWithAlias()
2613 public function fieldNamesWithAlias( $fields ) {
2615 foreach ( $fields as $alias => $field ) {
2616 if ( is_numeric( $alias ) ) {
2619 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2626 * Get the aliased table name clause for a FROM clause
2627 * which might have a JOIN and/or USE INDEX clause
2629 * @param array $tables ( [alias] => table )
2630 * @param array $use_index Same as for select()
2631 * @param array $join_conds Same as for select()
2634 protected function tableNamesWithUseIndexOrJOIN(
2635 $tables, $use_index = array(), $join_conds = array()
2639 $use_index = (array)$use_index;
2640 $join_conds = (array)$join_conds;
2642 foreach ( $tables as $alias => $table ) {
2643 if ( !is_string( $alias ) ) {
2644 // No alias? Set it equal to the table name
2647 // Is there a JOIN clause for this table?
2648 if ( isset( $join_conds[$alias] ) ) {
2649 list( $joinType, $conds ) = $join_conds[$alias];
2650 $tableClause = $joinType;
2651 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2652 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2653 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2655 $tableClause .= ' ' . $use;
2658 $on = $this->makeList( (array)$conds, LIST_AND
);
2660 $tableClause .= ' ON (' . $on . ')';
2663 $retJOIN[] = $tableClause;
2664 } elseif ( isset( $use_index[$alias] ) ) {
2665 // Is there an INDEX clause for this table?
2666 $tableClause = $this->tableNameWithAlias( $table, $alias );
2667 $tableClause .= ' ' . $this->useIndexClause(
2668 implode( ',', (array)$use_index[$alias] )
2671 $ret[] = $tableClause;
2673 $tableClause = $this->tableNameWithAlias( $table, $alias );
2675 $ret[] = $tableClause;
2679 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2680 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2681 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2683 // Compile our final table clause
2684 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2688 * Get the name of an index in a given table.
2690 * @protected Don't use outside of DatabaseBase and childs
2691 * @param string $index
2694 public function indexName( $index ) {
2695 // @FIXME: Make this protected once we move away from PHP 5.3
2696 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
2698 // Backwards-compatibility hack
2700 'ar_usertext_timestamp' => 'usertext_timestamp',
2701 'un_user_id' => 'user_id',
2702 'un_user_ip' => 'user_ip',
2705 if ( isset( $renamed[$index] ) ) {
2706 return $renamed[$index];
2713 * Adds quotes and backslashes.
2715 * @param string|Blob $s
2718 public function addQuotes( $s ) {
2719 if ( $s instanceof Blob
) {
2722 if ( $s === null ) {
2725 # This will also quote numeric values. This should be harmless,
2726 # and protects against weird problems that occur when they really
2727 # _are_ strings such as article titles and string->number->string
2728 # conversion is not 1:1.
2729 return "'" . $this->strencode( $s ) . "'";
2734 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2735 * MySQL uses `backticks` while basically everything else uses double quotes.
2736 * Since MySQL is the odd one out here the double quotes are our generic
2737 * and we implement backticks in DatabaseMysql.
2742 public function addIdentifierQuotes( $s ) {
2743 return '"' . str_replace( '"', '""', $s ) . '"';
2747 * Returns if the given identifier looks quoted or not according to
2748 * the database convention for quoting identifiers .
2750 * @param string $name
2753 public function isQuotedIdentifier( $name ) {
2754 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2761 protected function escapeLikeInternal( $s ) {
2762 return addcslashes( $s, '\%_' );
2766 * LIKE statement wrapper, receives a variable-length argument list with
2767 * parts of pattern to match containing either string literals that will be
2768 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2769 * the function could be provided with an array of aforementioned
2772 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2773 * a LIKE clause that searches for subpages of 'My page title'.
2775 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2776 * $query .= $dbr->buildLike( $pattern );
2779 * @return string Fully built LIKE statement
2781 public function buildLike() {
2782 $params = func_get_args();
2784 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2785 $params = $params[0];
2790 foreach ( $params as $value ) {
2791 if ( $value instanceof LikeMatch
) {
2792 $s .= $value->toString();
2794 $s .= $this->escapeLikeInternal( $value );
2798 return " LIKE {$this->addQuotes( $s )} ";
2802 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2806 public function anyChar() {
2807 return new LikeMatch( '_' );
2811 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2815 public function anyString() {
2816 return new LikeMatch( '%' );
2820 * Returns an appropriately quoted sequence value for inserting a new row.
2821 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2822 * subclass will return an integer, and save the value for insertId()
2824 * Any implementation of this function should *not* involve reusing
2825 * sequence numbers created for rolled-back transactions.
2826 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2827 * @param string $seqName
2830 public function nextSequenceValue( $seqName ) {
2835 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2836 * is only needed because a) MySQL must be as efficient as possible due to
2837 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2838 * which index to pick. Anyway, other databases might have different
2839 * indexes on a given table. So don't bother overriding this unless you're
2841 * @param string $index
2844 public function useIndexClause( $index ) {
2849 * REPLACE query wrapper.
2851 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2852 * except that when there is a duplicate key error, the old row is deleted
2853 * and the new row is inserted in its place.
2855 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2856 * perform the delete, we need to know what the unique indexes are so that
2857 * we know how to find the conflicting rows.
2859 * It may be more efficient to leave off unique indexes which are unlikely
2860 * to collide. However if you do this, you run the risk of encountering
2861 * errors which wouldn't have occurred in MySQL.
2863 * @param string $table The table to replace the row(s) in.
2864 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2865 * a field name or an array of field names
2866 * @param array $rows Can be either a single row to insert, or multiple rows,
2867 * in the same format as for DatabaseBase::insert()
2868 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2870 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2871 $quotedTable = $this->tableName( $table );
2873 if ( count( $rows ) == 0 ) {
2878 if ( !is_array( reset( $rows ) ) ) {
2879 $rows = array( $rows );
2882 foreach ( $rows as $row ) {
2883 # Delete rows which collide
2884 if ( $uniqueIndexes ) {
2885 $sql = "DELETE FROM $quotedTable WHERE ";
2887 foreach ( $uniqueIndexes as $index ) {
2894 if ( is_array( $index ) ) {
2896 foreach ( $index as $col ) {
2902 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2905 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2909 $this->query( $sql, $fname );
2912 # Now insert the row
2913 $this->insert( $table, $row, $fname );
2918 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2921 * @param string $table Table name
2922 * @param array|string $rows Row(s) to insert
2923 * @param string $fname Caller function name
2925 * @return ResultWrapper
2927 protected function nativeReplace( $table, $rows, $fname ) {
2928 $table = $this->tableName( $table );
2931 if ( !is_array( reset( $rows ) ) ) {
2932 $rows = array( $rows );
2935 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2938 foreach ( $rows as $row ) {
2945 $sql .= '(' . $this->makeList( $row ) . ')';
2948 return $this->query( $sql, $fname );
2952 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2954 * This updates any conflicting rows (according to the unique indexes) using
2955 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2957 * $rows may be either:
2958 * - A single associative array. The array keys are the field names, and
2959 * the values are the values to insert. The values are treated as data
2960 * and will be quoted appropriately. If NULL is inserted, this will be
2961 * converted to a database NULL.
2962 * - An array with numeric keys, holding a list of associative arrays.
2963 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2964 * each subarray must be identical to each other, and in the same order.
2966 * It may be more efficient to leave off unique indexes which are unlikely
2967 * to collide. However if you do this, you run the risk of encountering
2968 * errors which wouldn't have occurred in MySQL.
2970 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2975 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2976 * @param array $rows A single row or list of rows to insert
2977 * @param array $uniqueIndexes List of single field names or field name tuples
2978 * @param array $set An array of values to SET. For each array element, the
2979 * key gives the field name, and the value gives the data to set that
2980 * field to. The data will be quoted by DatabaseBase::addQuotes().
2981 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2985 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2988 if ( !count( $rows ) ) {
2989 return true; // nothing to do
2992 if ( !is_array( reset( $rows ) ) ) {
2993 $rows = array( $rows );
2996 if ( count( $uniqueIndexes ) ) {
2997 $clauses = array(); // list WHERE clauses that each identify a single row
2998 foreach ( $rows as $row ) {
2999 foreach ( $uniqueIndexes as $index ) {
3000 $index = is_array( $index ) ?
$index : array( $index ); // columns
3001 $rowKey = array(); // unique key to this row
3002 foreach ( $index as $column ) {
3003 $rowKey[$column] = $row[$column];
3005 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
3008 $where = array( $this->makeList( $clauses, LIST_OR
) );
3013 $useTrx = !$this->mTrxLevel
;
3015 $this->begin( $fname );
3018 # Update any existing conflicting row(s)
3019 if ( $where !== false ) {
3020 $ok = $this->update( $table, $set, $where, $fname );
3024 # Now insert any non-conflicting row(s)
3025 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
3026 } catch ( Exception
$e ) {
3028 $this->rollback( $fname );
3033 $this->commit( $fname );
3040 * DELETE where the condition is a join.
3042 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
3043 * we use sub-selects
3045 * For safety, an empty $conds will not delete everything. If you want to
3046 * delete all rows where the join condition matches, set $conds='*'.
3048 * DO NOT put the join condition in $conds.
3050 * @param string $delTable The table to delete from.
3051 * @param string $joinTable The other table.
3052 * @param string $delVar The variable to join on, in the first table.
3053 * @param string $joinVar The variable to join on, in the second table.
3054 * @param array $conds Condition array of field names mapped to variables,
3055 * ANDed together in the WHERE clause
3056 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
3057 * @throws DBUnexpectedError
3059 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
3063 throw new DBUnexpectedError( $this,
3064 'DatabaseBase::deleteJoin() called with empty $conds' );
3067 $delTable = $this->tableName( $delTable );
3068 $joinTable = $this->tableName( $joinTable );
3069 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
3070 if ( $conds != '*' ) {
3071 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
3075 $this->query( $sql, $fname );
3079 * Returns the size of a text field, or -1 for "unlimited"
3081 * @param string $table
3082 * @param string $field
3085 public function textFieldSize( $table, $field ) {
3086 $table = $this->tableName( $table );
3087 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
3088 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
3089 $row = $this->fetchObject( $res );
3093 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
3103 * A string to insert into queries to show that they're low-priority, like
3104 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
3105 * string and nothing bad should happen.
3107 * @return string Returns the text of the low priority option if it is
3108 * supported, or a blank string otherwise
3110 public function lowPriorityOption() {
3115 * DELETE query wrapper.
3117 * @param array $table Table name
3118 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
3119 * for the format. Use $conds == "*" to delete all rows
3120 * @param string $fname Name of the calling function
3121 * @throws DBUnexpectedError
3122 * @return bool|ResultWrapper
3124 public function delete( $table, $conds, $fname = __METHOD__
) {
3126 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
3129 $table = $this->tableName( $table );
3130 $sql = "DELETE FROM $table";
3132 if ( $conds != '*' ) {
3133 if ( is_array( $conds ) ) {
3134 $conds = $this->makeList( $conds, LIST_AND
);
3136 $sql .= ' WHERE ' . $conds;
3139 return $this->query( $sql, $fname );
3143 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
3144 * into another table.
3146 * @param string $destTable The table name to insert into
3147 * @param string|array $srcTable May be either a table name, or an array of table names
3148 * to include in a join.
3150 * @param array $varMap Must be an associative array of the form
3151 * array( 'dest1' => 'source1', ...). Source items may be literals
3152 * rather than field names, but strings should be quoted with
3153 * DatabaseBase::addQuotes()
3155 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
3156 * the details of the format of condition arrays. May be "*" to copy the
3159 * @param string $fname The function name of the caller, from __METHOD__
3161 * @param array $insertOptions Options for the INSERT part of the query, see
3162 * DatabaseBase::insert() for details.
3163 * @param array $selectOptions Options for the SELECT part of the query, see
3164 * DatabaseBase::select() for details.
3166 * @return ResultWrapper
3168 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
3169 $fname = __METHOD__
,
3170 $insertOptions = array(), $selectOptions = array()
3172 $destTable = $this->tableName( $destTable );
3174 if ( !is_array( $insertOptions ) ) {
3175 $insertOptions = array( $insertOptions );
3178 $insertOptions = $this->makeInsertOptions( $insertOptions );
3180 if ( !is_array( $selectOptions ) ) {
3181 $selectOptions = array( $selectOptions );
3184 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
3186 if ( is_array( $srcTable ) ) {
3187 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
3189 $srcTable = $this->tableName( $srcTable );
3192 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
3193 " SELECT $startOpts " . implode( ',', $varMap ) .
3194 " FROM $srcTable $useIndex ";
3196 if ( $conds != '*' ) {
3197 if ( is_array( $conds ) ) {
3198 $conds = $this->makeList( $conds, LIST_AND
);
3200 $sql .= " WHERE $conds";
3203 $sql .= " $tailOpts";
3205 return $this->query( $sql, $fname );
3209 * Construct a LIMIT query with optional offset. This is used for query
3210 * pages. The SQL should be adjusted so that only the first $limit rows
3211 * are returned. If $offset is provided as well, then the first $offset
3212 * rows should be discarded, and the next $limit rows should be returned.
3213 * If the result of the query is not ordered, then the rows to be returned
3214 * are theoretically arbitrary.
3216 * $sql is expected to be a SELECT, if that makes a difference.
3218 * The version provided by default works in MySQL and SQLite. It will very
3219 * likely need to be overridden for most other DBMSes.
3221 * @param string $sql SQL query we will append the limit too
3222 * @param int $limit The SQL limit
3223 * @param int|bool $offset The SQL offset (default false)
3224 * @throws DBUnexpectedError
3227 public function limitResult( $sql, $limit, $offset = false ) {
3228 if ( !is_numeric( $limit ) ) {
3229 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3232 return "$sql LIMIT "
3233 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3238 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3239 * within the UNION construct.
3242 public function unionSupportsOrderAndLimit() {
3243 return true; // True for almost every DB supported
3247 * Construct a UNION query
3248 * This is used for providing overload point for other DB abstractions
3249 * not compatible with the MySQL syntax.
3250 * @param array $sqls SQL statements to combine
3251 * @param bool $all Use UNION ALL
3252 * @return string SQL fragment
3254 public function unionQueries( $sqls, $all ) {
3255 $glue = $all ?
') UNION ALL (' : ') UNION (';
3257 return '(' . implode( $glue, $sqls ) . ')';
3261 * Returns an SQL expression for a simple conditional. This doesn't need
3262 * to be overridden unless CASE isn't supported in your DBMS.
3264 * @param string|array $cond SQL expression which will result in a boolean value
3265 * @param string $trueVal SQL expression to return if true
3266 * @param string $falseVal SQL expression to return if false
3267 * @return string SQL fragment
3269 public function conditional( $cond, $trueVal, $falseVal ) {
3270 if ( is_array( $cond ) ) {
3271 $cond = $this->makeList( $cond, LIST_AND
);
3274 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3278 * Returns a comand for str_replace function in SQL query.
3279 * Uses REPLACE() in MySQL
3281 * @param string $orig Column to modify
3282 * @param string $old Column to seek
3283 * @param string $new Column to replace with
3287 public function strreplace( $orig, $old, $new ) {
3288 return "REPLACE({$orig}, {$old}, {$new})";
3292 * Determines how long the server has been up
3297 public function getServerUptime() {
3302 * Determines if the last failure was due to a deadlock
3307 public function wasDeadlock() {
3312 * Determines if the last failure was due to a lock timeout
3317 public function wasLockTimeout() {
3322 * Determines if the last query error was something that should be dealt
3323 * with by pinging the connection and reissuing the query.
3328 public function wasErrorReissuable() {
3333 * Determines if the last failure was due to the database being read-only.
3338 public function wasReadOnlyError() {
3343 * Perform a deadlock-prone transaction.
3345 * This function invokes a callback function to perform a set of write
3346 * queries. If a deadlock occurs during the processing, the transaction
3347 * will be rolled back and the callback function will be called again.
3350 * $dbw->deadlockLoop( callback, ... );
3352 * Extra arguments are passed through to the specified callback function.
3354 * Returns whatever the callback function returned on its successful,
3355 * iteration, or false on error, for example if the retry limit was
3360 public function deadlockLoop() {
3361 $args = func_get_args();
3362 $function = array_shift( $args );
3363 $tries = self
::DEADLOCK_TRIES
;
3364 if ( is_array( $function ) ) {
3365 $fname = $function[0];
3370 $this->begin( __METHOD__
);
3375 $retVal = call_user_func_array( $function, $args );
3377 } catch ( DBQueryError
$e ) {
3378 $error = $this->lastError();
3379 $errno = $this->lastErrno();
3380 $sql = $this->lastQuery();
3381 if ( $this->wasDeadlock() ) {
3382 // Retry after a randomized delay
3383 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3385 // Throw the error back up
3389 } while ( --$tries > 0 );
3391 if ( $tries <= 0 ) {
3392 // Too many deadlocks; give up
3393 $this->rollback( __METHOD__
);
3396 $this->commit( __METHOD__
);
3403 * Wait for the slave to catch up to a given master position.
3405 * @param DBMasterPos $pos
3406 * @param int $timeout The maximum number of seconds to wait for
3408 * @return int Zero if the slave was past that position already,
3409 * greater than zero if we waited for some period of time, less than
3410 * zero if we timed out.
3412 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3413 # Real waits are implemented in the subclass.
3418 * Get the replication position of this slave
3420 * @return DBMasterPos|bool False if this is not a slave.
3422 public function getSlavePos() {
3428 * Get the position of this master
3430 * @return DBMasterPos|bool False if this is not a master
3432 public function getMasterPos() {
3438 * Run an anonymous function as soon as there is no transaction pending.
3439 * If there is a transaction and it is rolled back, then the callback is cancelled.
3440 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3441 * Callbacks must commit any transactions that they begin.
3443 * This is useful for updates to different systems or when separate transactions are needed.
3444 * For example, one might want to enqueue jobs into a system outside the database, but only
3445 * after the database is updated so that the jobs will see the data when they actually run.
3446 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3448 * @param callable $callback
3451 final public function onTransactionIdle( $callback ) {
3452 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
3453 if ( !$this->mTrxLevel
) {
3454 $this->runOnTransactionIdleCallbacks();
3459 * Run an anonymous function before the current transaction commits or now if there is none.
3460 * If there is a transaction and it is rolled back, then the callback is cancelled.
3461 * Callbacks must not start nor commit any transactions.
3463 * This is useful for updates that easily cause deadlocks if locks are held too long
3464 * but where atomicity is strongly desired for these updates and some related updates.
3466 * @param callable $callback
3469 final public function onTransactionPreCommitOrIdle( $callback ) {
3470 if ( $this->mTrxLevel
) {
3471 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
3473 $this->onTransactionIdle( $callback ); // this will trigger immediately
3478 * Actually any "on transaction idle" callbacks.
3482 protected function runOnTransactionIdleCallbacks() {
3483 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
3485 $e = $ePrior = null; // last exception
3486 do { // callbacks may add callbacks :)
3487 $callbacks = $this->mTrxIdleCallbacks
;
3488 $this->mTrxIdleCallbacks
= array(); // recursion guard
3489 foreach ( $callbacks as $callback ) {
3491 list( $phpCallback ) = $callback;
3492 $this->clearFlag( DBO_TRX
); // make each query its own transaction
3493 call_user_func( $phpCallback );
3494 $this->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
3495 } catch ( Exception
$e ) {
3497 MWExceptionHandler
::logException( $ePrior );
3502 } while ( count( $this->mTrxIdleCallbacks
) );
3504 if ( $e instanceof Exception
) {
3505 throw $e; // re-throw any last exception
3510 * Actually any "on transaction pre-commit" callbacks.
3514 protected function runOnTransactionPreCommitCallbacks() {
3515 $e = $ePrior = null; // last exception
3516 do { // callbacks may add callbacks :)
3517 $callbacks = $this->mTrxPreCommitCallbacks
;
3518 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
3519 foreach ( $callbacks as $callback ) {
3521 list( $phpCallback ) = $callback;
3522 call_user_func( $phpCallback );
3523 } catch ( Exception
$e ) {
3525 MWExceptionHandler
::logException( $ePrior );
3530 } while ( count( $this->mTrxPreCommitCallbacks
) );
3532 if ( $e instanceof Exception
) {
3533 throw $e; // re-throw any last exception
3538 * Begin an atomic section of statements
3540 * If a transaction has been started already, just keep track of the given
3541 * section name to make sure the transaction is not committed pre-maturely.
3542 * This function can be used in layers (with sub-sections), so use a stack
3543 * to keep track of the different atomic sections. If there is no transaction,
3544 * start one implicitly.
3546 * The goal of this function is to create an atomic section of SQL queries
3547 * without having to start a new transaction if it already exists.
3549 * Atomic sections are more strict than transactions. With transactions,
3550 * attempting to begin a new transaction when one is already running results
3551 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3552 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3553 * and any database transactions cannot be began or committed until all atomic
3554 * levels are closed. There is no such thing as implicitly opening or closing
3555 * an atomic section.
3558 * @param string $fname
3561 final public function startAtomic( $fname = __METHOD__
) {
3562 if ( !$this->mTrxLevel
) {
3563 $this->begin( $fname );
3564 $this->mTrxAutomatic
= true;
3565 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3566 // in all changes being in one transaction to keep requests transactional.
3567 if ( !$this->getFlag( DBO_TRX
) ) {
3568 $this->mTrxAutomaticAtomic
= true;
3572 $this->mTrxAtomicLevels
->push( $fname );
3576 * Ends an atomic section of SQL statements
3578 * Ends the next section of atomic SQL statements and commits the transaction
3582 * @see DatabaseBase::startAtomic
3583 * @param string $fname
3586 final public function endAtomic( $fname = __METHOD__
) {
3587 if ( !$this->mTrxLevel
) {
3588 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3590 if ( $this->mTrxAtomicLevels
->isEmpty() ||
3591 $this->mTrxAtomicLevels
->pop() !== $fname
3593 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3596 if ( $this->mTrxAtomicLevels
->isEmpty() && $this->mTrxAutomaticAtomic
) {
3597 $this->commit( $fname, 'flush' );
3602 * Begin a transaction. If a transaction is already in progress,
3603 * that transaction will be committed before the new transaction is started.
3605 * Note that when the DBO_TRX flag is set (which is usually the case for web
3606 * requests, but not for maintenance scripts), any previous database query
3607 * will have started a transaction automatically.
3609 * Nesting of transactions is not supported. Attempts to nest transactions
3610 * will cause a warning, unless the current transaction was started
3611 * automatically because of the DBO_TRX flag.
3613 * @param string $fname
3616 final public function begin( $fname = __METHOD__
) {
3617 global $wgDebugDBTransactions;
3619 if ( $this->mTrxLevel
) { // implicit commit
3620 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3621 // If the current transaction was an automatic atomic one, then we definitely have
3622 // a problem. Same if there is any unclosed atomic level.
3623 throw new DBUnexpectedError( $this,
3624 "Attempted to start explicit transaction when atomic levels are still open."
3626 } elseif ( !$this->mTrxAutomatic
) {
3627 // We want to warn about inadvertently nested begin/commit pairs, but not about
3628 // auto-committing implicit transactions that were started by query() via DBO_TRX
3629 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3630 " performing implicit commit!";
3633 $this->getLogContext( array(
3634 'method' => __METHOD__
,
3639 // if the transaction was automatic and has done write operations,
3640 // log it if $wgDebugDBTransactions is enabled.
3641 if ( $this->mTrxDoneWrites
&& $wgDebugDBTransactions ) {
3642 wfDebug( "$fname: Automatic transaction with writes in progress" .
3643 " (from {$this->mTrxFname}), performing implicit commit!\n"
3648 $this->runOnTransactionPreCommitCallbacks();
3649 $writeTime = $this->pendingWriteQueryDuration();
3650 $this->doCommit( $fname );
3651 if ( $this->mTrxDoneWrites
) {
3652 $this->mDoneWrites
= microtime( true );
3653 $this->getTransactionProfiler()->transactionWritingOut(
3654 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
3656 $this->runOnTransactionIdleCallbacks();
3659 # Avoid fatals if close() was called
3660 $this->assertOpen();
3662 $this->doBegin( $fname );
3663 $this->mTrxTimestamp
= microtime( true );
3664 $this->mTrxFname
= $fname;
3665 $this->mTrxDoneWrites
= false;
3666 $this->mTrxAutomatic
= false;
3667 $this->mTrxAutomaticAtomic
= false;
3668 $this->mTrxAtomicLevels
= new SplStack
;
3669 $this->mTrxIdleCallbacks
= array();
3670 $this->mTrxPreCommitCallbacks
= array();
3671 $this->mTrxShortId
= wfRandomString( 12 );
3672 $this->mTrxWriteDuration
= 0.0;
3676 * Issues the BEGIN command to the database server.
3678 * @see DatabaseBase::begin()
3679 * @param string $fname
3681 protected function doBegin( $fname ) {
3682 $this->query( 'BEGIN', $fname );
3683 $this->mTrxLevel
= 1;
3687 * Commits a transaction previously started using begin().
3688 * If no transaction is in progress, a warning is issued.
3690 * Nesting of transactions is not supported.
3692 * @param string $fname
3693 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3694 * explicitly committing implicit transactions, or calling commit when no
3695 * transaction is in progress. This will silently break any ongoing
3696 * explicit transaction. Only set the flush flag if you are sure that it
3697 * is safe to ignore these warnings in your context.
3698 * @throws DBUnexpectedError
3700 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3701 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3702 // There are still atomic sections open. This cannot be ignored
3703 throw new DBUnexpectedError(
3705 "Attempted to commit transaction while atomic sections are still open"
3709 if ( $flush === 'flush' ) {
3710 if ( !$this->mTrxLevel
) {
3711 return; // nothing to do
3712 } elseif ( !$this->mTrxAutomatic
) {
3713 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3716 if ( !$this->mTrxLevel
) {
3717 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3718 return; // nothing to do
3719 } elseif ( $this->mTrxAutomatic
) {
3720 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3724 # Avoid fatals if close() was called
3725 $this->assertOpen();
3727 $this->runOnTransactionPreCommitCallbacks();
3728 $writeTime = $this->pendingWriteQueryDuration();
3729 $this->doCommit( $fname );
3730 if ( $this->mTrxDoneWrites
) {
3731 $this->mDoneWrites
= microtime( true );
3732 $this->getTransactionProfiler()->transactionWritingOut(
3733 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
3735 $this->runOnTransactionIdleCallbacks();
3739 * Issues the COMMIT command to the database server.
3741 * @see DatabaseBase::commit()
3742 * @param string $fname
3744 protected function doCommit( $fname ) {
3745 if ( $this->mTrxLevel
) {
3746 $this->query( 'COMMIT', $fname );
3747 $this->mTrxLevel
= 0;
3752 * Rollback a transaction previously started using begin().
3753 * If no transaction is in progress, a warning is issued.
3755 * No-op on non-transactional databases.
3757 * @param string $fname
3758 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3759 * calling rollback when no transaction is in progress. This will silently
3760 * break any ongoing explicit transaction. Only set the flush flag if you
3761 * are sure that it is safe to ignore these warnings in your context.
3762 * @throws DBUnexpectedError
3763 * @since 1.23 Added $flush parameter
3765 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3766 if ( $flush !== 'flush' ) {
3767 if ( !$this->mTrxLevel
) {
3768 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3769 return; // nothing to do
3770 } elseif ( $this->mTrxAutomatic
) {
3771 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3774 if ( !$this->mTrxLevel
) {
3775 return; // nothing to do
3776 } elseif ( !$this->mTrxAutomatic
) {
3777 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3781 # Avoid fatals if close() was called
3782 $this->assertOpen();
3784 $this->doRollback( $fname );
3785 $this->mTrxIdleCallbacks
= array(); // cancel
3786 $this->mTrxPreCommitCallbacks
= array(); // cancel
3787 $this->mTrxAtomicLevels
= new SplStack
;
3788 if ( $this->mTrxDoneWrites
) {
3789 $this->getTransactionProfiler()->transactionWritingOut(
3790 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3795 * Issues the ROLLBACK command to the database server.
3797 * @see DatabaseBase::rollback()
3798 * @param string $fname
3800 protected function doRollback( $fname ) {
3801 if ( $this->mTrxLevel
) {
3802 $this->query( 'ROLLBACK', $fname, true );
3803 $this->mTrxLevel
= 0;
3808 * Creates a new table with structure copied from existing table
3809 * Note that unlike most database abstraction functions, this function does not
3810 * automatically append database prefix, because it works at a lower
3811 * abstraction level.
3812 * The table names passed to this function shall not be quoted (this
3813 * function calls addIdentifierQuotes when needed).
3815 * @param string $oldName Name of table whose structure should be copied
3816 * @param string $newName Name of table to be created
3817 * @param bool $temporary Whether the new table should be temporary
3818 * @param string $fname Calling function name
3819 * @throws MWException
3820 * @return bool True if operation was successful
3822 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3825 throw new MWException(
3826 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3830 * List all tables on the database
3832 * @param string $prefix Only show tables with this prefix, e.g. mw_
3833 * @param string $fname Calling function name
3834 * @throws MWException
3837 function listTables( $prefix = null, $fname = __METHOD__
) {
3838 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3842 * Reset the views process cache set by listViews()
3845 final public function clearViewsCache() {
3846 $this->allViews
= null;
3850 * Lists all the VIEWs in the database
3852 * For caching purposes the list of all views should be stored in
3853 * $this->allViews. The process cache can be cleared with clearViewsCache()
3855 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3856 * @param string $fname Name of calling function
3857 * @throws MWException
3861 public function listViews( $prefix = null, $fname = __METHOD__
) {
3862 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3866 * Differentiates between a TABLE and a VIEW
3868 * @param string $name Name of the database-structure to test.
3869 * @throws MWException
3873 public function isView( $name ) {
3874 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3878 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3879 * to the format used for inserting into timestamp fields in this DBMS.
3881 * The result is unquoted, and needs to be passed through addQuotes()
3882 * before it can be included in raw SQL.
3884 * @param string|int $ts
3888 public function timestamp( $ts = 0 ) {
3889 return wfTimestamp( TS_MW
, $ts );
3893 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3894 * to the format used for inserting into timestamp fields in this DBMS. If
3895 * NULL is input, it is passed through, allowing NULL values to be inserted
3896 * into timestamp fields.
3898 * The result is unquoted, and needs to be passed through addQuotes()
3899 * before it can be included in raw SQL.
3901 * @param string|int $ts
3905 public function timestampOrNull( $ts = null ) {
3906 if ( is_null( $ts ) ) {
3909 return $this->timestamp( $ts );
3914 * Take the result from a query, and wrap it in a ResultWrapper if
3915 * necessary. Boolean values are passed through as is, to indicate success
3916 * of write queries or failure.
3918 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3919 * resource, and it was necessary to call this function to convert it to
3920 * a wrapper. Nowadays, raw database objects are never exposed to external
3921 * callers, so this is unnecessary in external code. For compatibility with
3922 * old code, ResultWrapper objects are passed through unaltered.
3924 * @param bool|ResultWrapper|resource $result
3925 * @return bool|ResultWrapper
3927 public function resultObject( $result ) {
3928 if ( empty( $result ) ) {
3930 } elseif ( $result instanceof ResultWrapper
) {
3932 } elseif ( $result === true ) {
3933 // Successful write query
3936 return new ResultWrapper( $this, $result );
3941 * Ping the server and try to reconnect if it there is no connection
3943 * @return bool Success or failure
3945 public function ping() {
3946 # Stub. Not essential to override.
3951 * Get slave lag. Currently supported only by MySQL.
3953 * Note that this function will generate a fatal error on many
3954 * installations. Most callers should use LoadBalancer::safeGetLag()
3957 * @return int Database replication lag in seconds
3959 public function getLag() {
3964 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3968 function maxListLen() {
3973 * Some DBMSs have a special format for inserting into blob fields, they
3974 * don't allow simple quoted strings to be inserted. To insert into such
3975 * a field, pass the data through this function before passing it to
3976 * DatabaseBase::insert().
3981 public function encodeBlob( $b ) {
3986 * Some DBMSs return a special placeholder object representing blob fields
3987 * in result objects. Pass the object through this function to return the
3990 * @param string|Blob $b
3993 public function decodeBlob( $b ) {
3994 if ( $b instanceof Blob
) {
4001 * Override database's default behavior. $options include:
4002 * 'connTimeout' : Set the connection timeout value in seconds.
4003 * May be useful for very long batch queries such as
4004 * full-wiki dumps, where a single query reads out over
4007 * @param array $options
4010 public function setSessionOptions( array $options ) {
4014 * Read and execute SQL commands from a file.
4016 * Returns true on success, error string or exception on failure (depending
4017 * on object's error ignore settings).
4019 * @param string $filename File name to open
4020 * @param bool|callable $lineCallback Optional function called before reading each line
4021 * @param bool|callable $resultCallback Optional function called for each MySQL result
4022 * @param bool|string $fname Calling function name or false if name should be
4023 * generated dynamically using $filename
4024 * @param bool|callable $inputCallback Optional function called for each
4025 * complete line sent
4026 * @throws Exception|MWException
4027 * @return bool|string
4029 public function sourceFile(
4030 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
4032 MediaWiki\
suppressWarnings();
4033 $fp = fopen( $filename, 'r' );
4034 MediaWiki\restoreWarnings
();
4036 if ( false === $fp ) {
4037 throw new MWException( "Could not open \"{$filename}\".\n" );
4041 $fname = __METHOD__
. "( $filename )";
4045 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
4046 } catch ( Exception
$e ) {
4057 * Get the full path of a patch file. Originally based on archive()
4058 * from updaters.inc. Keep in mind this always returns a patch, as
4059 * it fails back to MySQL if no DB-specific patch can be found
4061 * @param string $patch The name of the patch, like patch-something.sql
4062 * @return string Full path to patch file
4064 public function patchPath( $patch ) {
4067 $dbType = $this->getType();
4068 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
4069 return "$IP/maintenance/$dbType/archives/$patch";
4071 return "$IP/maintenance/archives/$patch";
4076 * Set variables to be used in sourceFile/sourceStream, in preference to the
4077 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
4078 * all. If it's set to false, $GLOBALS will be used.
4080 * @param bool|array $vars Mapping variable name to value.
4082 public function setSchemaVars( $vars ) {
4083 $this->mSchemaVars
= $vars;
4087 * Read and execute commands from an open file handle.
4089 * Returns true on success, error string or exception on failure (depending
4090 * on object's error ignore settings).
4092 * @param resource $fp File handle
4093 * @param bool|callable $lineCallback Optional function called before reading each query
4094 * @param bool|callable $resultCallback Optional function called for each MySQL result
4095 * @param string $fname Calling function name
4096 * @param bool|callable $inputCallback Optional function called for each complete query sent
4097 * @return bool|string
4099 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
4100 $fname = __METHOD__
, $inputCallback = false
4104 while ( !feof( $fp ) ) {
4105 if ( $lineCallback ) {
4106 call_user_func( $lineCallback );
4109 $line = trim( fgets( $fp ) );
4111 if ( $line == '' ) {
4115 if ( '-' == $line[0] && '-' == $line[1] ) {
4123 $done = $this->streamStatementEnd( $cmd, $line );
4127 if ( $done ||
feof( $fp ) ) {
4128 $cmd = $this->replaceVars( $cmd );
4130 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
4131 $res = $this->query( $cmd, $fname );
4133 if ( $resultCallback ) {
4134 call_user_func( $resultCallback, $res, $this );
4137 if ( false === $res ) {
4138 $err = $this->lastError();
4140 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4151 * Called by sourceStream() to check if we've reached a statement end
4153 * @param string $sql SQL assembled so far
4154 * @param string $newLine New line about to be added to $sql
4155 * @return bool Whether $newLine contains end of the statement
4157 public function streamStatementEnd( &$sql, &$newLine ) {
4158 if ( $this->delimiter
) {
4160 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4161 if ( $newLine != $prev ) {
4170 * Database independent variable replacement. Replaces a set of variables
4171 * in an SQL statement with their contents as given by $this->getSchemaVars().
4173 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4175 * - '{$var}' should be used for text and is passed through the database's
4177 * - `{$var}` should be used for identifiers (e.g. table and database names).
4178 * It is passed through the database's addIdentifierQuotes method which
4179 * can be overridden if the database uses something other than backticks.
4180 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4181 * database's tableName method.
4182 * - / *i* / passes the name that follows through the database's indexName method.
4183 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4184 * its use should be avoided. In 1.24 and older, string encoding was applied.
4186 * @param string $ins SQL statement to replace variables in
4187 * @return string The new SQL statement with variables replaced
4189 protected function replaceVars( $ins ) {
4191 $vars = $this->getSchemaVars();
4192 return preg_replace_callback(
4194 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4195 \'\{\$ (\w+) }\' | # 3. addQuotes
4196 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4197 /\*\$ (\w+) \*/ # 5. leave unencoded
4199 function ( $m ) use ( $that, $vars ) {
4200 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4201 // check for both nonexistent keys *and* the empty string.
4202 if ( isset( $m[1] ) && $m[1] !== '' ) {
4203 if ( $m[1] === 'i' ) {
4204 return $that->indexName( $m[2] );
4206 return $that->tableName( $m[2] );
4208 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4209 return $that->addQuotes( $vars[$m[3]] );
4210 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4211 return $that->addIdentifierQuotes( $vars[$m[4]] );
4212 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4213 return $vars[$m[5]];
4223 * Get schema variables. If none have been set via setSchemaVars(), then
4224 * use some defaults from the current object.
4228 protected function getSchemaVars() {
4229 if ( $this->mSchemaVars
) {
4230 return $this->mSchemaVars
;
4232 return $this->getDefaultSchemaVars();
4237 * Get schema variables to use if none have been set via setSchemaVars().
4239 * Override this in derived classes to provide variables for tables.sql
4240 * and SQL patch files.
4244 protected function getDefaultSchemaVars() {
4249 * Check to see if a named lock is available (non-blocking)
4251 * @param string $lockName Name of lock to poll
4252 * @param string $method Name of method calling us
4256 public function lockIsFree( $lockName, $method ) {
4261 * Acquire a named lock
4263 * Named locks are not related to transactions
4265 * @param string $lockName Name of lock to aquire
4266 * @param string $method Name of method calling us
4267 * @param int $timeout
4270 public function lock( $lockName, $method, $timeout = 5 ) {
4277 * Named locks are not related to transactions
4279 * @param string $lockName Name of lock to release
4280 * @param string $method Name of method calling us
4282 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4283 * by this thread (in which case the lock is not released), and NULL if the named
4284 * lock did not exist
4286 public function unlock( $lockName, $method ) {
4291 * Check to see if a named lock used by lock() use blocking queues
4296 public function namedLocksEnqueue() {
4301 * Lock specific tables
4303 * @param array $read Array of tables to lock for read access
4304 * @param array $write Array of tables to lock for write access
4305 * @param string $method Name of caller
4306 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4309 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4314 * Unlock specific tables
4316 * @param string $method The caller
4319 public function unlockTables( $method ) {
4325 * @param string $tableName
4326 * @param string $fName
4327 * @return bool|ResultWrapper
4330 public function dropTable( $tableName, $fName = __METHOD__
) {
4331 if ( !$this->tableExists( $tableName, $fName ) ) {
4334 $sql = "DROP TABLE " . $this->tableName( $tableName );
4335 if ( $this->cascadingDeletes() ) {
4339 return $this->query( $sql, $fName );
4343 * Get search engine class. All subclasses of this need to implement this
4344 * if they wish to use searching.
4348 public function getSearchEngine() {
4349 return 'SearchEngineDummy';
4353 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4354 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4355 * because "i" sorts after all numbers.
4359 public function getInfinity() {
4364 * Encode an expiry time into the DBMS dependent format
4366 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4369 public function encodeExpiry( $expiry ) {
4370 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4371 ?
$this->getInfinity()
4372 : $this->timestamp( $expiry );
4376 * Decode an expiry time into a DBMS independent format
4378 * @param string $expiry DB timestamp field value for expiry
4379 * @param int $format TS_* constant, defaults to TS_MW
4382 public function decodeExpiry( $expiry, $format = TS_MW
) {
4383 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4385 : wfTimestamp( $format, $expiry );
4389 * Allow or deny "big selects" for this session only. This is done by setting
4390 * the sql_big_selects session variable.
4392 * This is a MySQL-specific feature.
4394 * @param bool|string $value True for allow, false for deny, or "default" to
4395 * restore the initial value
4397 public function setBigSelects( $value = true ) {
4405 public function __toString() {
4406 return (string)$this->mConn
;
4410 * Run a few simple sanity checks
4412 public function __destruct() {
4413 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
4414 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4416 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
4418 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
4419 $callers[] = $callbackInfo[1];
4421 $callers = implode( ', ', $callers );
4422 trigger_error( "DB transaction callbacks still pending (from $callers)." );