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 * Database abstraction object
32 abstract class DatabaseBase
implements IDatabase
{
33 /** Number of times to re-try an operation in case of deadlock */
34 const DEADLOCK_TRIES
= 4;
36 /** Minimum time to wait before retry, in microseconds */
37 const DEADLOCK_DELAY_MIN
= 500000;
39 /** Maximum time to wait before retry */
40 const DEADLOCK_DELAY_MAX
= 1500000;
42 protected $mLastQuery = '';
43 protected $mDoneWrites = false;
44 protected $mPHPError = false;
46 protected $mServer, $mUser, $mPassword, $mDBname;
48 /** @var resource Database connection */
49 protected $mConn = null;
50 protected $mOpened = false;
52 /** @var callable[] */
53 protected $mTrxIdleCallbacks = array();
54 /** @var callable[] */
55 protected $mTrxPreCommitCallbacks = array();
57 protected $mTablePrefix;
61 protected $mErrorCount = 0;
62 protected $mLBInfo = array();
63 protected $mDefaultBigSelects = null;
64 protected $mSchemaVars = false;
66 protected $mSessionVars = array();
68 protected $preparedArgs;
70 protected $htmlErrors;
72 protected $delimiter = ';';
75 * Either 1 if a transaction is active or 0 otherwise.
76 * The other Trx fields may not be meaningfull if this is 0.
80 protected $mTrxLevel = 0;
83 * Either a short hexidecimal string if a transaction is active or ""
86 * @see DatabaseBase::mTrxLevel
88 protected $mTrxShortId = '';
91 * The UNIX time that the transaction started. Callers can assume that if
92 * snapshot isolation is used, then the data is *at least* up to date to that
93 * point (possibly more up-to-date since the first SELECT defines the snapshot).
96 * @see DatabaseBase::mTrxLevel
98 private $mTrxTimestamp = null;
101 * Remembers the function name given for starting the most recent transaction via begin().
102 * Used to provide additional context for error reporting.
105 * @see DatabaseBase::mTrxLevel
107 private $mTrxFname = null;
110 * Record if possible write queries were done in the last transaction started
113 * @see DatabaseBase::mTrxLevel
115 private $mTrxDoneWrites = false;
118 * Record if the current transaction was started implicitly due to DBO_TRX being set.
121 * @see DatabaseBase::mTrxLevel
123 private $mTrxAutomatic = false;
126 * Array of levels of atomicity within transactions
130 private $mTrxAtomicLevels;
133 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
137 private $mTrxAutomaticAtomic = false;
140 * Track the seconds spent in write queries for the current transaction
144 private $mTrxWriteDuration = 0.0;
148 * @var resource File handle for upgrade
150 protected $fileHandle = null;
154 * @var string[] Process cache of VIEWs names in the database
156 protected $allViews = null;
158 /** @var TransactionProfiler */
159 protected $trxProfiler;
162 * A string describing the current software version, and possibly
163 * other details in a user-friendly way. Will be listed on Special:Version, etc.
164 * Use getServerVersion() to get machine-friendly information.
166 * @return string Version information from the database server
168 public function getServerInfo() {
169 return $this->getServerVersion();
173 * @return string Command delimiter used by this database engine
175 public function getDelimiter() {
176 return $this->delimiter
;
180 * Boolean, controls output of large amounts of debug information.
181 * @param bool|null $debug
182 * - true to enable debugging
183 * - false to disable debugging
184 * - omitted or null to do nothing
186 * @return bool|null Previous value of the flag
188 public function debug( $debug = null ) {
189 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
193 * Turns buffering of SQL result sets on (true) or off (false). Default is
196 * Unbuffered queries are very troublesome in MySQL:
198 * - If another query is executed while the first query is being read
199 * out, the first query is killed. This means you can't call normal
200 * MediaWiki functions while you are reading an unbuffered query result
201 * from a normal wfGetDB() connection.
203 * - Unbuffered queries cause the MySQL server to use large amounts of
204 * memory and to hold broad locks which block other queries.
206 * If you want to limit client-side memory, it's almost always better to
207 * split up queries into batches using a LIMIT clause than to switch off
210 * @param null|bool $buffer
211 * @return null|bool The previous value of the flag
213 public function bufferResults( $buffer = null ) {
214 if ( is_null( $buffer ) ) {
215 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
217 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
222 * Turns on (false) or off (true) the automatic generation and sending
223 * of a "we're sorry, but there has been a database error" page on
224 * database errors. Default is on (false). When turned off, the
225 * code should use lastErrno() and lastError() to handle the
226 * situation as appropriate.
228 * Do not use this function outside of the Database classes.
230 * @param null|bool $ignoreErrors
231 * @return bool The previous value of the flag.
233 public function ignoreErrors( $ignoreErrors = null ) {
234 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
238 * Gets the current transaction level.
240 * Historically, transactions were allowed to be "nested". This is no
241 * longer supported, so this function really only returns a boolean.
243 * @return int The previous value
245 public function trxLevel() {
246 return $this->mTrxLevel
;
250 * Get the UNIX timestamp of the time that the transaction was established
252 * This can be used to reason about the staleness of SELECT data
253 * in REPEATABLE-READ transaction isolation level.
255 * @return float|null Returns null if there is not active transaction
258 public function trxTimestamp() {
259 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
263 * Get/set the number of errors logged. Only useful when errors are ignored
264 * @param int $count The count to set, or omitted to leave it unchanged.
265 * @return int The error count
267 public function errorCount( $count = null ) {
268 return wfSetVar( $this->mErrorCount
, $count );
272 * Get/set the table prefix.
273 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
274 * @return string The previous table prefix.
276 public function tablePrefix( $prefix = null ) {
277 return wfSetVar( $this->mTablePrefix
, $prefix );
281 * Get/set the db schema.
282 * @param string $schema The database schema to set, or omitted to leave it unchanged.
283 * @return string The previous db schema.
285 public function dbSchema( $schema = null ) {
286 return wfSetVar( $this->mSchema
, $schema );
290 * Set the filehandle to copy write statements to.
292 * @param resource $fh File handle
294 public function setFileHandle( $fh ) {
295 $this->fileHandle
= $fh;
299 * Get properties passed down from the server info array of the load
302 * @param string $name The entry of the info array to get, or null to get the
305 * @return array|mixed|null
307 public function getLBInfo( $name = null ) {
308 if ( is_null( $name ) ) {
309 return $this->mLBInfo
;
311 if ( array_key_exists( $name, $this->mLBInfo
) ) {
312 return $this->mLBInfo
[$name];
320 * Set the LB info array, or a member of it. If called with one parameter,
321 * the LB info array is set to that parameter. If it is called with two
322 * parameters, the member with the given name is set to the given value.
324 * @param string $name
325 * @param array $value
327 public function setLBInfo( $name, $value = null ) {
328 if ( is_null( $value ) ) {
329 $this->mLBInfo
= $name;
331 $this->mLBInfo
[$name] = $value;
336 * Set lag time in seconds for a fake slave
338 * @param mixed $lag Valid values for this parameter are determined by the
339 * subclass, but should be a PHP scalar or array that would be sensible
340 * as part of $wgLBFactoryConf.
342 public function setFakeSlaveLag( $lag ) {
346 * Make this connection a fake master
348 * @param bool $enabled
350 public function setFakeMaster( $enabled = true ) {
354 * @return TransactionProfiler
356 protected function getTransactionProfiler() {
357 return $this->trxProfiler
359 : Profiler
::instance()->getTransactionProfiler();
363 * Returns true if this database supports (and uses) cascading deletes
367 public function cascadingDeletes() {
372 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
376 public function cleanupTriggers() {
381 * Returns true if this database is strict about what can be put into an IP field.
382 * Specifically, it uses a NULL value instead of an empty string.
386 public function strictIPs() {
391 * Returns true if this database uses timestamps rather than integers
395 public function realTimestamps() {
400 * Returns true if this database does an implicit sort when doing GROUP BY
404 public function implicitGroupby() {
409 * Returns true if this database does an implicit order by when the column has an index
410 * For example: SELECT page_title FROM page LIMIT 1
414 public function implicitOrderby() {
419 * Returns true if this database can do a native search on IP columns
420 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
424 public function searchableIPs() {
429 * Returns true if this database can use functional indexes
433 public function functionalIndexes() {
438 * Return the last query that went through DatabaseBase::query()
441 public function lastQuery() {
442 return $this->mLastQuery
;
446 * Returns true if the connection may have been used for write queries.
447 * Should return true if unsure.
451 public function doneWrites() {
452 return (bool)$this->mDoneWrites
;
456 * Returns the last time the connection may have been used for write queries.
457 * Should return a timestamp if unsure.
459 * @return int|float UNIX timestamp or false
462 public function lastDoneWrites() {
463 return $this->mDoneWrites ?
: false;
467 * Returns true if there is a transaction open with possible write
468 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
472 public function writesOrCallbacksPending() {
473 return $this->mTrxLevel
&& (
474 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
479 * Get the time spend running write queries for this
481 * High times could be due to scanning, updates, locking, and such
483 * @return float|bool Returns false if not transaction is active
486 public function pendingWriteQueryDuration() {
487 return $this->mTrxLevel ?
$this->mTrxWriteDuration
: false;
491 * Is a connection to the database open?
494 public function isOpen() {
495 return $this->mOpened
;
499 * Set a flag for this connection
501 * @param int $flag DBO_* constants from Defines.php:
502 * - DBO_DEBUG: output some debug info (same as debug())
503 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
504 * - DBO_TRX: automatically start transactions
505 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
506 * and removes it in command line mode
507 * - DBO_PERSISTENT: use persistant database connection
509 public function setFlag( $flag ) {
510 global $wgDebugDBTransactions;
511 $this->mFlags |
= $flag;
512 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
513 wfDebug( "Implicit transactions are now enabled.\n" );
518 * Clear a flag for this connection
520 * @param int $flag DBO_* constants from Defines.php:
521 * - DBO_DEBUG: output some debug info (same as debug())
522 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
523 * - DBO_TRX: automatically start transactions
524 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
525 * and removes it in command line mode
526 * - DBO_PERSISTENT: use persistant database connection
528 public function clearFlag( $flag ) {
529 global $wgDebugDBTransactions;
530 $this->mFlags
&= ~
$flag;
531 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
532 wfDebug( "Implicit transactions are now disabled.\n" );
537 * Returns a boolean whether the flag $flag is set for this connection
539 * @param int $flag DBO_* constants from Defines.php:
540 * - DBO_DEBUG: output some debug info (same as debug())
541 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
542 * - DBO_TRX: automatically start transactions
543 * - DBO_PERSISTENT: use persistant database connection
546 public function getFlag( $flag ) {
547 return !!( $this->mFlags
& $flag );
551 * General read-only accessor
553 * @param string $name
556 public function getProperty( $name ) {
563 public function getWikiID() {
564 if ( $this->mTablePrefix
) {
565 return "{$this->mDBname}-{$this->mTablePrefix}";
567 return $this->mDBname
;
572 * Return a path to the DBMS-specific SQL file if it exists,
573 * otherwise default SQL file
575 * @param string $filename
578 private function getSqlFilePath( $filename ) {
580 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
581 if ( file_exists( $dbmsSpecificFilePath ) ) {
582 return $dbmsSpecificFilePath;
584 return "$IP/maintenance/$filename";
589 * Return a path to the DBMS-specific schema file,
590 * otherwise default to tables.sql
594 public function getSchemaPath() {
595 return $this->getSqlFilePath( 'tables.sql' );
599 * Return a path to the DBMS-specific update key file,
600 * otherwise default to update-keys.sql
604 public function getUpdateKeysPath() {
605 return $this->getSqlFilePath( 'update-keys.sql' );
609 * Get the type of the DBMS, as it appears in $wgDBtype.
613 abstract function getType();
616 * Open a connection to the database. Usually aborts on failure
618 * @param string $server Database server host
619 * @param string $user Database user name
620 * @param string $password Database user password
621 * @param string $dbName Database name
623 * @throws DBConnectionError
625 abstract function open( $server, $user, $password, $dbName );
628 * Fetch the next row from the given result object, in object form.
629 * Fields can be retrieved with $row->fieldname, with fields acting like
631 * If no more rows are available, false is returned.
633 * @param ResultWrapper|stdClass $res Object as returned from DatabaseBase::query(), etc.
634 * @return stdClass|bool
635 * @throws DBUnexpectedError Thrown if the database returns an error
637 abstract function fetchObject( $res );
640 * Fetch the next row from the given result object, in associative array
641 * form. Fields are retrieved with $row['fieldname'].
642 * If no more rows are available, false is returned.
644 * @param ResultWrapper $res Result object as returned from DatabaseBase::query(), etc.
646 * @throws DBUnexpectedError Thrown if the database returns an error
648 abstract function fetchRow( $res );
651 * Get the number of rows in a result object
653 * @param mixed $res A SQL result
656 abstract function numRows( $res );
659 * Get the number of fields in a result object
660 * @see http://www.php.net/mysql_num_fields
662 * @param mixed $res A SQL result
665 abstract function numFields( $res );
668 * Get a field name in a result object
669 * @see http://www.php.net/mysql_field_name
671 * @param mixed $res A SQL result
675 abstract function fieldName( $res, $n );
678 * Get the inserted value of an auto-increment row
680 * The value inserted should be fetched from nextSequenceValue()
683 * $id = $dbw->nextSequenceValue( 'page_page_id_seq' );
684 * $dbw->insert( 'page', array( 'page_id' => $id ) );
685 * $id = $dbw->insertId();
689 abstract function insertId();
692 * Change the position of the cursor in a result object
693 * @see http://www.php.net/mysql_data_seek
695 * @param mixed $res A SQL result
698 abstract function dataSeek( $res, $row );
701 * Get the last error number
702 * @see http://www.php.net/mysql_errno
706 abstract function lastErrno();
709 * Get a description of the last error
710 * @see http://www.php.net/mysql_error
714 abstract function lastError();
717 * mysql_fetch_field() wrapper
718 * Returns false if the field doesn't exist
720 * @param string $table Table name
721 * @param string $field Field name
725 abstract function fieldInfo( $table, $field );
728 * Get information about an index into an object
729 * @param string $table Table name
730 * @param string $index Index name
731 * @param string $fname Calling function name
732 * @return mixed Database-specific index description class or false if the index does not exist
734 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
737 * Get the number of rows affected by the last write query
738 * @see http://www.php.net/mysql_affected_rows
742 abstract function affectedRows();
745 * Wrapper for addslashes()
747 * @param string $s String to be slashed.
748 * @return string Slashed string.
750 abstract function strencode( $s );
753 * Returns a wikitext link to the DB's website, e.g.,
754 * return "[http://www.mysql.com/ MySQL]";
755 * Should at least contain plain text, if for some reason
756 * your database has no website.
758 * @return string Wikitext of a link to the server software's web site
760 abstract function getSoftwareLink();
763 * A string describing the current software version, like from
764 * mysql_get_server_info().
766 * @return string Version information from the database server.
768 abstract function getServerVersion();
773 * FIXME: It is possible to construct a Database object with no associated
774 * connection object, by specifying no parameters to __construct(). This
775 * feature is deprecated and should be removed.
777 * DatabaseBase subclasses should not be constructed directly in external
778 * code. DatabaseBase::factory() should be used instead.
780 * @param array $params Parameters passed from DatabaseBase::factory()
782 function __construct( array $params ) {
783 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode, $wgDebugDBTransactions;
785 $this->mTrxAtomicLevels
= new SplStack
;
787 $server = $params['host'];
788 $user = $params['user'];
789 $password = $params['password'];
790 $dbName = $params['dbname'];
791 $flags = $params['flags'];
792 $tablePrefix = $params['tablePrefix'];
793 $schema = $params['schema'];
794 $foreign = $params['foreign'];
796 $this->mFlags
= $flags;
797 if ( $this->mFlags
& DBO_DEFAULT
) {
798 if ( $wgCommandLineMode ) {
799 $this->mFlags
&= ~DBO_TRX
;
800 if ( $wgDebugDBTransactions ) {
801 wfDebug( "Implicit transaction open disabled.\n" );
804 $this->mFlags |
= DBO_TRX
;
805 if ( $wgDebugDBTransactions ) {
806 wfDebug( "Implicit transaction open enabled.\n" );
811 $this->mSessionVars
= $params['variables'];
813 /** Get the default table prefix*/
814 if ( $tablePrefix === 'get from global' ) {
815 $this->mTablePrefix
= $wgDBprefix;
817 $this->mTablePrefix
= $tablePrefix;
820 /** Get the database schema*/
821 if ( $schema === 'get from global' ) {
822 $this->mSchema
= $wgDBmwschema;
824 $this->mSchema
= $schema;
827 $this->mForeign
= $foreign;
829 if ( isset( $params['trxProfiler'] ) ) {
830 $this->trxProfiler
= $params['trxProfiler']; // override
834 $this->open( $server, $user, $password, $dbName );
839 * Called by serialize. Throw an exception when DB connection is serialized.
840 * This causes problems on some database engines because the connection is
841 * not restored on unserialize.
843 public function __sleep() {
844 throw new MWException( 'Database serialization may cause problems, since ' .
845 'the connection is not restored on wakeup.' );
849 * Given a DB type, construct the name of the appropriate child class of
850 * DatabaseBase. This is designed to replace all of the manual stuff like:
851 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
852 * as well as validate against the canonical list of DB types we have
854 * This factory function is mostly useful for when you need to connect to a
855 * database other than the MediaWiki default (such as for external auth,
856 * an extension, et cetera). Do not use this to connect to the MediaWiki
857 * database. Example uses in core:
858 * @see LoadBalancer::reallyOpenConnection()
859 * @see ForeignDBRepo::getMasterDB()
860 * @see WebInstallerDBConnect::execute()
864 * @param string $dbType A possible DB type
865 * @param array $p An array of options to pass to the constructor.
866 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
867 * @throws MWException If the database driver or extension cannot be found
868 * @return DatabaseBase|null DatabaseBase subclass or null
870 final public static function factory( $dbType, $p = array() ) {
871 $canonicalDBTypes = array(
872 'mysql' => array( 'mysqli', 'mysql' ),
873 'postgres' => array(),
880 $dbType = strtolower( $dbType );
881 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
882 $possibleDrivers = $canonicalDBTypes[$dbType];
883 if ( !empty( $p['driver'] ) ) {
884 if ( in_array( $p['driver'], $possibleDrivers ) ) {
885 $driver = $p['driver'];
887 throw new MWException( __METHOD__
.
888 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
891 foreach ( $possibleDrivers as $posDriver ) {
892 if ( extension_loaded( $posDriver ) ) {
893 $driver = $posDriver;
901 if ( $driver === false ) {
902 throw new MWException( __METHOD__
.
903 " no viable database extension found for type '$dbType'" );
906 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
907 // and everything else doesn't use a schema (e.g. null)
908 // Although postgres and oracle support schemas, we don't use them (yet)
909 // to maintain backwards compatibility
910 $defaultSchemas = array(
911 'mssql' => 'get from global',
914 $class = 'Database' . ucfirst( $driver );
915 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
916 // Resolve some defaults for b/c
917 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
918 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
919 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
920 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
921 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
922 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : array();
923 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global';
924 if ( !isset( $p['schema'] ) ) {
925 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : null;
927 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
929 return new $class( $p );
935 protected function installErrorHandler() {
936 $this->mPHPError
= false;
937 $this->htmlErrors
= ini_set( 'html_errors', '0' );
938 set_error_handler( array( $this, 'connectionErrorHandler' ) );
942 * @return bool|string
944 protected function restoreErrorHandler() {
945 restore_error_handler();
946 if ( $this->htmlErrors
!== false ) {
947 ini_set( 'html_errors', $this->htmlErrors
);
949 if ( $this->mPHPError
) {
950 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
951 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
961 * @param string $errstr
963 public function connectionErrorHandler( $errno, $errstr ) {
964 $this->mPHPError
= $errstr;
968 * Create a log context to pass to wfLogDBError or other logging functions.
970 * @param array $extras Additional data to add to context
973 protected function getLogContext( array $extras = array() ) {
976 'db_server' => $this->mServer
,
977 'db_name' => $this->mDBname
,
978 'db_user' => $this->mUser
,
985 * Closes a database connection.
986 * if it is open : commits any open transactions
988 * @throws MWException
989 * @return bool Operation success. true if already closed.
991 public function close() {
992 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
993 throw new MWException( "Transaction idle callbacks still pending." );
995 if ( $this->mConn
) {
996 if ( $this->trxLevel() ) {
997 if ( !$this->mTrxAutomatic
) {
998 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
999 " performing implicit commit before closing connection!" );
1002 $this->commit( __METHOD__
, 'flush' );
1005 $closed = $this->closeConnection();
1006 $this->mConn
= false;
1010 $this->mOpened
= false;
1016 * Make sure isOpen() returns true as a sanity check
1018 * @throws DBUnexpectedError
1020 protected function assertOpen() {
1021 if ( !$this->isOpen() ) {
1022 throw new DBUnexpectedError( $this, "DB connection was already closed." );
1027 * Closes underlying database connection
1029 * @return bool Whether connection was closed successfully
1031 abstract protected function closeConnection();
1034 * @param string $error Fallback error message, used if none is given by DB
1035 * @throws DBConnectionError
1037 function reportConnectionError( $error = 'Unknown error' ) {
1038 $myError = $this->lastError();
1044 throw new DBConnectionError( $this, $error );
1048 * The DBMS-dependent part of query()
1050 * @param string $sql SQL query.
1051 * @return ResultWrapper|bool Result object to feed to fetchObject,
1052 * fetchRow, ...; or false on failure
1054 abstract protected function doQuery( $sql );
1057 * Determine whether a query writes to the DB.
1058 * Should return true if unsure.
1060 * @param string $sql
1063 protected function isWriteQuery( $sql ) {
1064 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
1068 * Determine whether a SQL statement is sensitive to isolation level.
1069 * A SQL statement is considered transactable if its result could vary
1070 * depending on the transaction isolation level. Operational commands
1071 * such as 'SET' and 'SHOW' are not considered to be transactable.
1073 * @param string $sql
1076 protected function isTransactableQuery( $sql ) {
1077 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
1078 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
1082 * Run an SQL query and return the result. Normally throws a DBQueryError
1083 * on failure. If errors are ignored, returns false instead.
1085 * In new code, the query wrappers select(), insert(), update(), delete(),
1086 * etc. should be used where possible, since they give much better DBMS
1087 * independence and automatically quote or validate user input in a variety
1088 * of contexts. This function is generally only useful for queries which are
1089 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
1092 * However, the query wrappers themselves should call this function.
1094 * @param string $sql SQL query
1095 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
1096 * comment (you can use __METHOD__ or add some extra info)
1097 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
1098 * maybe best to catch the exception instead?
1099 * @throws MWException
1100 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
1101 * for a successful read query, or false on failure if $tempIgnore set
1103 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
1104 global $wgUser, $wgDebugDBTransactions, $wgDebugDumpSqlLength;
1106 $this->mLastQuery
= $sql;
1108 $isWriteQuery = $this->isWriteQuery( $sql );
1109 if ( $isWriteQuery ) {
1110 if ( !$this->mDoneWrites
) {
1111 wfDebug( __METHOD__
. ': Writes done: ' .
1112 DatabaseBase
::generalizeSQL( $sql ) . "\n" );
1114 # Set a flag indicating that writes have been done
1115 $this->mDoneWrites
= microtime( true );
1118 # Add a comment for easy SHOW PROCESSLIST interpretation
1119 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
1120 $userName = $wgUser->getName();
1121 if ( mb_strlen( $userName ) > 15 ) {
1122 $userName = mb_substr( $userName, 0, 15 ) . '...';
1124 $userName = str_replace( '/', '', $userName );
1129 // Add trace comment to the begin of the sql string, right after the operator.
1130 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
1131 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
1133 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
) && $this->isTransactableQuery( $sql ) ) {
1134 if ( $wgDebugDBTransactions ) {
1135 wfDebug( "Implicit transaction start.\n" );
1137 $this->begin( __METHOD__
. " ($fname)" );
1138 $this->mTrxAutomatic
= true;
1141 # Keep track of whether the transaction has write queries pending
1142 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWriteQuery ) {
1143 $this->mTrxDoneWrites
= true;
1144 $this->getTransactionProfiler()->transactionWritingIn(
1145 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
1148 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1149 # generalizeSQL will probably cut down the query to reasonable
1150 # logging size most of the time. The substr is really just a sanity check.
1152 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1153 $totalProf = 'DatabaseBase::query-master';
1155 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1156 $totalProf = 'DatabaseBase::query';
1158 # Include query transaction state
1159 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
1161 $profiler = Profiler
::instance();
1162 if ( !$profiler instanceof ProfilerStub
) {
1163 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
1164 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
1167 if ( $this->debug() ) {
1171 $sqlx = $wgDebugDumpSqlLength ?
substr( $commentedSql, 0, $wgDebugDumpSqlLength )
1173 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1175 $master = $isMaster ?
'master' : 'slave';
1176 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1179 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
1181 # Avoid fatals if close() was called
1182 $this->assertOpen();
1184 # Do the query and handle errors
1185 $startTime = microtime( true );
1186 $ret = $this->doQuery( $commentedSql );
1187 $queryRuntime = microtime( true ) - $startTime;
1188 # Log the query time and feed it into the DB trx profiler
1189 $this->getTransactionProfiler()->recordQueryCompletion(
1190 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1192 MWDebug
::queryTime( $queryId );
1194 # Try reconnecting if the connection was lost
1195 if ( false === $ret && $this->wasErrorReissuable() ) {
1196 # Transaction is gone, like it or not
1197 $hadTrx = $this->mTrxLevel
; // possible lost transaction
1198 $this->mTrxLevel
= 0;
1199 $this->mTrxIdleCallbacks
= array(); // bug 65263
1200 $this->mTrxPreCommitCallbacks
= array(); // bug 65263
1201 wfDebug( "Connection lost, reconnecting...\n" );
1202 # Stash the last error values since ping() might clear them
1203 $lastError = $this->lastError();
1204 $lastErrno = $this->lastErrno();
1205 if ( $this->ping() ) {
1206 wfDebug( "Reconnected\n" );
1207 $server = $this->getServer();
1208 $msg = __METHOD__
. ": lost connection to $server; reconnected";
1209 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1212 # Leave $ret as false and let an error be reported.
1213 # Callers may catch the exception and continue to use the DB.
1214 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1216 # Should be safe to silently retry (no trx and thus no callbacks)
1217 $startTime = microtime( true );
1218 $ret = $this->doQuery( $commentedSql );
1219 $queryRuntime = microtime( true ) - $startTime;
1220 # Log the query time and feed it into the DB trx profiler
1221 $this->getTransactionProfiler()->recordQueryCompletion(
1222 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1225 wfDebug( "Failed\n" );
1229 if ( false === $ret ) {
1230 $this->reportQueryError(
1231 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1234 $res = $this->resultObject( $ret );
1236 // Destroy profile sections in the opposite order to their creation
1237 $queryProfSection = false;
1238 $totalProfSection = false;
1240 if ( $isWriteQuery && $this->mTrxLevel
) {
1241 $this->mTrxWriteDuration +
= $queryRuntime;
1248 * Report a query error. Log the error, and if neither the object ignore
1249 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1251 * @param string $error
1253 * @param string $sql
1254 * @param string $fname
1255 * @param bool $tempIgnore
1256 * @throws DBQueryError
1258 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1259 ++
$this->mErrorCount
;
1261 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1262 wfDebug( "SQL ERROR (ignored): $error\n" );
1264 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1266 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1267 $this->getLogContext( array(
1268 'method' => __METHOD__
,
1271 'sql1line' => $sql1line,
1275 wfDebug( "SQL ERROR: " . $error . "\n" );
1276 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1281 * Intended to be compatible with the PEAR::DB wrapper functions.
1282 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1284 * ? = scalar value, quoted as necessary
1285 * ! = raw SQL bit (a function for instance)
1286 * & = filename; reads the file and inserts as a blob
1287 * (we don't use this though...)
1289 * @param string $sql
1290 * @param string $func
1294 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1295 /* MySQL doesn't support prepared statements (yet), so just
1296 * pack up the query for reference. We'll manually replace
1299 return array( 'query' => $sql, 'func' => $func );
1303 * Free a prepared query, generated by prepare().
1304 * @param string $prepared
1306 protected function freePrepared( $prepared ) {
1307 /* No-op by default */
1311 * Execute a prepared query with the various arguments
1312 * @param string $prepared The prepared sql
1313 * @param mixed $args Either an array here, or put scalars as varargs
1315 * @return ResultWrapper
1317 public function execute( $prepared, $args = null ) {
1318 if ( !is_array( $args ) ) {
1320 $args = func_get_args();
1321 array_shift( $args );
1324 $sql = $this->fillPrepared( $prepared['query'], $args );
1326 return $this->query( $sql, $prepared['func'] );
1330 * For faking prepared SQL statements on DBs that don't support it directly.
1332 * @param string $preparedQuery A 'preparable' SQL statement
1333 * @param array $args Array of Arguments to fill it with
1334 * @return string Executable SQL
1336 public function fillPrepared( $preparedQuery, $args ) {
1338 $this->preparedArgs
=& $args;
1340 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1341 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1345 * preg_callback func for fillPrepared()
1346 * The arguments should be in $this->preparedArgs and must not be touched
1347 * while we're doing this.
1349 * @param array $matches
1350 * @throws DBUnexpectedError
1353 protected function fillPreparedArg( $matches ) {
1354 switch ( $matches[1] ) {
1363 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1365 switch ( $matches[1] ) {
1367 return $this->addQuotes( $arg );
1371 # return $this->addQuotes( file_get_contents( $arg ) );
1372 throw new DBUnexpectedError(
1374 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1377 throw new DBUnexpectedError(
1379 'Received invalid match. This should never happen!'
1385 * Free a result object returned by query() or select(). It's usually not
1386 * necessary to call this, just use unset() or let the variable holding
1387 * the result object go out of scope.
1389 * @param mixed $res A SQL result
1391 public function freeResult( $res ) {
1395 * A SELECT wrapper which returns a single field from a single result row.
1397 * Usually throws a DBQueryError on failure. If errors are explicitly
1398 * ignored, returns false on failure.
1400 * If no result rows are returned from the query, false is returned.
1402 * @param string|array $table Table name. See DatabaseBase::select() for details.
1403 * @param string $var The field name to select. This must be a valid SQL
1404 * fragment: do not use unvalidated user input.
1405 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1406 * @param string $fname The function name of the caller.
1407 * @param string|array $options The query options. See DatabaseBase::select() for details.
1409 * @return bool|mixed The value from the field, or false on failure.
1411 public function selectField(
1412 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1414 if ( $var === '*' ) { // sanity
1415 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1418 if ( !is_array( $options ) ) {
1419 $options = array( $options );
1422 $options['LIMIT'] = 1;
1424 $res = $this->select( $table, $var, $cond, $fname, $options );
1425 if ( $res === false ||
!$this->numRows( $res ) ) {
1429 $row = $this->fetchRow( $res );
1431 if ( $row !== false ) {
1432 return reset( $row );
1439 * A SELECT wrapper which returns a list of single field values from result rows.
1441 * Usually throws a DBQueryError on failure. If errors are explicitly
1442 * ignored, returns false on failure.
1444 * If no result rows are returned from the query, false is returned.
1446 * @param string|array $table Table name. See DatabaseBase::select() for details.
1447 * @param string $var The field name to select. This must be a valid SQL
1448 * fragment: do not use unvalidated user input.
1449 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1450 * @param string $fname The function name of the caller.
1451 * @param string|array $options The query options. See DatabaseBase::select() for details.
1453 * @return bool|array The values from the field, or false on failure
1454 * @throws DBUnexpectedError
1457 public function selectFieldValues(
1458 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1460 if ( $var === '*' ) { // sanity
1461 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1464 if ( !is_array( $options ) ) {
1465 $options = array( $options );
1468 $res = $this->select( $table, $var, $cond, $fname, $options );
1469 if ( $res === false ) {
1474 foreach ( $res as $row ) {
1475 $values[] = $row->$var;
1482 * Returns an optional USE INDEX clause to go after the table, and a
1483 * string to go at the end of the query.
1485 * @param array $options Associative array of options to be turned into
1486 * an SQL query, valid keys are listed in the function.
1488 * @see DatabaseBase::select()
1490 public function makeSelectOptions( $options ) {
1491 $preLimitTail = $postLimitTail = '';
1494 $noKeyOptions = array();
1496 foreach ( $options as $key => $option ) {
1497 if ( is_numeric( $key ) ) {
1498 $noKeyOptions[$option] = true;
1502 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1504 $preLimitTail .= $this->makeOrderBy( $options );
1506 // if (isset($options['LIMIT'])) {
1507 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1508 // isset($options['OFFSET']) ? $options['OFFSET']
1512 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1513 $postLimitTail .= ' FOR UPDATE';
1516 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1517 $postLimitTail .= ' LOCK IN SHARE MODE';
1520 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1521 $startOpts .= 'DISTINCT';
1524 # Various MySQL extensions
1525 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1526 $startOpts .= ' /*! STRAIGHT_JOIN */';
1529 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1530 $startOpts .= ' HIGH_PRIORITY';
1533 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1534 $startOpts .= ' SQL_BIG_RESULT';
1537 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1538 $startOpts .= ' SQL_BUFFER_RESULT';
1541 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1542 $startOpts .= ' SQL_SMALL_RESULT';
1545 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1546 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1549 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1550 $startOpts .= ' SQL_CACHE';
1553 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1554 $startOpts .= ' SQL_NO_CACHE';
1557 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1558 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1563 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1567 * Returns an optional GROUP BY with an optional HAVING
1569 * @param array $options Associative array of options
1571 * @see DatabaseBase::select()
1574 public function makeGroupByWithHaving( $options ) {
1576 if ( isset( $options['GROUP BY'] ) ) {
1577 $gb = is_array( $options['GROUP BY'] )
1578 ?
implode( ',', $options['GROUP BY'] )
1579 : $options['GROUP BY'];
1580 $sql .= ' GROUP BY ' . $gb;
1582 if ( isset( $options['HAVING'] ) ) {
1583 $having = is_array( $options['HAVING'] )
1584 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1585 : $options['HAVING'];
1586 $sql .= ' HAVING ' . $having;
1593 * Returns an optional ORDER BY
1595 * @param array $options Associative array of options
1597 * @see DatabaseBase::select()
1600 public function makeOrderBy( $options ) {
1601 if ( isset( $options['ORDER BY'] ) ) {
1602 $ob = is_array( $options['ORDER BY'] )
1603 ?
implode( ',', $options['ORDER BY'] )
1604 : $options['ORDER BY'];
1606 return ' ORDER BY ' . $ob;
1613 * Execute a SELECT query constructed using the various parameters provided.
1614 * See below for full details of the parameters.
1616 * @param string|array $table Table name
1617 * @param string|array $vars Field names
1618 * @param string|array $conds Conditions
1619 * @param string $fname Caller function name
1620 * @param array $options Query options
1621 * @param array $join_conds Join conditions
1624 * @param string|array $table
1626 * May be either an array of table names, or a single string holding a table
1627 * name. If an array is given, table aliases can be specified, for example:
1629 * array( 'a' => 'user' )
1631 * This includes the user table in the query, with the alias "a" available
1632 * for use in field names (e.g. a.user_name).
1634 * All of the table names given here are automatically run through
1635 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1636 * added, and various other table name mappings to be performed.
1639 * @param string|array $vars
1641 * May be either a field name or an array of field names. The field names
1642 * can be complete fragments of SQL, for direct inclusion into the SELECT
1643 * query. If an array is given, field aliases can be specified, for example:
1645 * array( 'maxrev' => 'MAX(rev_id)' )
1647 * This includes an expression with the alias "maxrev" in the query.
1649 * If an expression is given, care must be taken to ensure that it is
1653 * @param string|array $conds
1655 * May be either a string containing a single condition, or an array of
1656 * conditions. If an array is given, the conditions constructed from each
1657 * element are combined with AND.
1659 * Array elements may take one of two forms:
1661 * - Elements with a numeric key are interpreted as raw SQL fragments.
1662 * - Elements with a string key are interpreted as equality conditions,
1663 * where the key is the field name.
1664 * - If the value of such an array element is a scalar (such as a
1665 * string), it will be treated as data and thus quoted appropriately.
1666 * If it is null, an IS NULL clause will be added.
1667 * - If the value is an array, an IN (...) clause will be constructed
1668 * from its non-null elements, and an IS NULL clause will be added
1669 * if null is present, such that the field may match any of the
1670 * elements in the array. The non-null elements will be quoted.
1672 * Note that expressions are often DBMS-dependent in their syntax.
1673 * DBMS-independent wrappers are provided for constructing several types of
1674 * expression commonly used in condition queries. See:
1675 * - DatabaseBase::buildLike()
1676 * - DatabaseBase::conditional()
1679 * @param string|array $options
1681 * Optional: Array of query options. Boolean options are specified by
1682 * including them in the array as a string value with a numeric key, for
1685 * array( 'FOR UPDATE' )
1687 * The supported options are:
1689 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1690 * with LIMIT can theoretically be used for paging through a result set,
1691 * but this is discouraged in MediaWiki for performance reasons.
1693 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1694 * and then the first rows are taken until the limit is reached. LIMIT
1695 * is applied to a result set after OFFSET.
1697 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1698 * changed until the next COMMIT.
1700 * - DISTINCT: Boolean: return only unique result rows.
1702 * - GROUP BY: May be either an SQL fragment string naming a field or
1703 * expression to group by, or an array of such SQL fragments.
1705 * - HAVING: May be either an string containing a HAVING clause or an array of
1706 * conditions building the HAVING clause. If an array is given, the conditions
1707 * constructed from each element are combined with AND.
1709 * - ORDER BY: May be either an SQL fragment giving a field name or
1710 * expression to order by, or an array of such SQL fragments.
1712 * - USE INDEX: This may be either a string giving the index name to use
1713 * for the query, or an array. If it is an associative array, each key
1714 * gives the table name (or alias), each value gives the index name to
1715 * use for that table. All strings are SQL fragments and so should be
1716 * validated by the caller.
1718 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1719 * instead of SELECT.
1721 * And also the following boolean MySQL extensions, see the MySQL manual
1722 * for documentation:
1724 * - LOCK IN SHARE MODE
1728 * - SQL_BUFFER_RESULT
1729 * - SQL_SMALL_RESULT
1730 * - SQL_CALC_FOUND_ROWS
1735 * @param string|array $join_conds
1737 * Optional associative array of table-specific join conditions. In the
1738 * most common case, this is unnecessary, since the join condition can be
1739 * in $conds. However, it is useful for doing a LEFT JOIN.
1741 * The key of the array contains the table name or alias. The value is an
1742 * array with two elements, numbered 0 and 1. The first gives the type of
1743 * join, the second is an SQL fragment giving the join condition for that
1744 * table. For example:
1746 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1748 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1749 * with no rows in it will be returned. If there was a query error, a
1750 * DBQueryError exception will be thrown, except if the "ignore errors"
1751 * option was set, in which case false will be returned.
1753 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1754 $options = array(), $join_conds = array() ) {
1755 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1757 return $this->query( $sql, $fname );
1761 * The equivalent of DatabaseBase::select() except that the constructed SQL
1762 * is returned, instead of being immediately executed. This can be useful for
1763 * doing UNION queries, where the SQL text of each query is needed. In general,
1764 * however, callers outside of Database classes should just use select().
1766 * @param string|array $table Table name
1767 * @param string|array $vars Field names
1768 * @param string|array $conds Conditions
1769 * @param string $fname Caller function name
1770 * @param string|array $options Query options
1771 * @param string|array $join_conds Join conditions
1773 * @return string SQL query string.
1774 * @see DatabaseBase::select()
1776 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1777 $options = array(), $join_conds = array()
1779 if ( is_array( $vars ) ) {
1780 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1783 $options = (array)$options;
1784 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1785 ?
$options['USE INDEX']
1788 if ( is_array( $table ) ) {
1790 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1791 } elseif ( $table != '' ) {
1792 if ( $table[0] == ' ' ) {
1793 $from = ' FROM ' . $table;
1796 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1802 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1803 $this->makeSelectOptions( $options );
1805 if ( !empty( $conds ) ) {
1806 if ( is_array( $conds ) ) {
1807 $conds = $this->makeList( $conds, LIST_AND
);
1809 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1811 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1814 if ( isset( $options['LIMIT'] ) ) {
1815 $sql = $this->limitResult( $sql, $options['LIMIT'],
1816 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1818 $sql = "$sql $postLimitTail";
1820 if ( isset( $options['EXPLAIN'] ) ) {
1821 $sql = 'EXPLAIN ' . $sql;
1828 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1829 * that a single row object is returned. If the query returns no rows,
1830 * false is returned.
1832 * @param string|array $table Table name
1833 * @param string|array $vars Field names
1834 * @param array $conds Conditions
1835 * @param string $fname Caller function name
1836 * @param string|array $options Query options
1837 * @param array|string $join_conds Join conditions
1839 * @return stdClass|bool
1841 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1842 $options = array(), $join_conds = array()
1844 $options = (array)$options;
1845 $options['LIMIT'] = 1;
1846 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1848 if ( $res === false ) {
1852 if ( !$this->numRows( $res ) ) {
1856 $obj = $this->fetchObject( $res );
1862 * Estimate the number of rows in dataset
1864 * MySQL allows you to estimate the number of rows that would be returned
1865 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1866 * index cardinality statistics, and is notoriously inaccurate, especially
1867 * when large numbers of rows have recently been added or deleted.
1869 * For DBMSs that don't support fast result size estimation, this function
1870 * will actually perform the SELECT COUNT(*).
1872 * Takes the same arguments as DatabaseBase::select().
1874 * @param string $table Table name
1875 * @param string $vars Unused
1876 * @param array|string $conds Filters on the table
1877 * @param string $fname Function name for profiling
1878 * @param array $options Options for select
1879 * @return int Row count
1881 public function estimateRowCount(
1882 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1885 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1888 $row = $this->fetchRow( $res );
1889 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1896 * Get the number of rows in dataset
1898 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
1900 * Takes the same arguments as DatabaseBase::select().
1902 * @param string $table Table name
1903 * @param string $vars Unused
1904 * @param array|string $conds Filters on the table
1905 * @param string $fname Function name for profiling
1906 * @param array $options Options for select
1907 * @return int Row count
1910 public function selectRowCount(
1911 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1914 $sql = $this->selectSQLText( $table, '1', $conds, $fname, $options );
1915 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1918 $row = $this->fetchRow( $res );
1919 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1926 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1927 * It's only slightly flawed. Don't use for anything important.
1929 * @param string $sql A SQL Query
1933 static function generalizeSQL( $sql ) {
1934 # This does the same as the regexp below would do, but in such a way
1935 # as to avoid crashing php on some large strings.
1936 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1938 $sql = str_replace( "\\\\", '', $sql );
1939 $sql = str_replace( "\\'", '', $sql );
1940 $sql = str_replace( "\\\"", '', $sql );
1941 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1942 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1944 # All newlines, tabs, etc replaced by single space
1945 $sql = preg_replace( '/\s+/', ' ', $sql );
1948 # except the ones surrounded by characters, e.g. l10n
1949 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1950 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1956 * Determines whether a field exists in a table
1958 * @param string $table Table name
1959 * @param string $field Filed to check on that table
1960 * @param string $fname Calling function name (optional)
1961 * @return bool Whether $table has filed $field
1963 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1964 $info = $this->fieldInfo( $table, $field );
1970 * Determines whether an index exists
1971 * Usually throws a DBQueryError on failure
1972 * If errors are explicitly ignored, returns NULL on failure
1974 * @param string $table
1975 * @param string $index
1976 * @param string $fname
1979 public function indexExists( $table, $index, $fname = __METHOD__
) {
1980 if ( !$this->tableExists( $table ) ) {
1984 $info = $this->indexInfo( $table, $index, $fname );
1985 if ( is_null( $info ) ) {
1988 return $info !== false;
1993 * Query whether a given table exists
1995 * @param string $table
1996 * @param string $fname
1999 public function tableExists( $table, $fname = __METHOD__
) {
2000 $table = $this->tableName( $table );
2001 $old = $this->ignoreErrors( true );
2002 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
2003 $this->ignoreErrors( $old );
2009 * Determines if a given index is unique
2011 * @param string $table
2012 * @param string $index
2016 public function indexUnique( $table, $index ) {
2017 $indexInfo = $this->indexInfo( $table, $index );
2019 if ( !$indexInfo ) {
2023 return !$indexInfo[0]->Non_unique
;
2027 * Helper for DatabaseBase::insert().
2029 * @param array $options
2032 protected function makeInsertOptions( $options ) {
2033 return implode( ' ', $options );
2037 * INSERT wrapper, inserts an array into a table.
2041 * - A single associative array. The array keys are the field names, and
2042 * the values are the values to insert. The values are treated as data
2043 * and will be quoted appropriately. If NULL is inserted, this will be
2044 * converted to a database NULL.
2045 * - An array with numeric keys, holding a list of associative arrays.
2046 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2047 * each subarray must be identical to each other, and in the same order.
2049 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2052 * $options is an array of options, with boolean options encoded as values
2053 * with numeric keys, in the same style as $options in
2054 * DatabaseBase::select(). Supported options are:
2056 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
2057 * any rows which cause duplicate key errors are not inserted. It's
2058 * possible to determine how many rows were successfully inserted using
2059 * DatabaseBase::affectedRows().
2061 * @param string $table Table name. This will be passed through
2062 * DatabaseBase::tableName().
2063 * @param array $a Array of rows to insert
2064 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2065 * @param array $options Array of options
2069 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
2070 # No rows to insert, easy just return now
2071 if ( !count( $a ) ) {
2075 $table = $this->tableName( $table );
2077 if ( !is_array( $options ) ) {
2078 $options = array( $options );
2082 if ( isset( $options['fileHandle'] ) ) {
2083 $fh = $options['fileHandle'];
2085 $options = $this->makeInsertOptions( $options );
2087 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
2089 $keys = array_keys( $a[0] );
2092 $keys = array_keys( $a );
2095 $sql = 'INSERT ' . $options .
2096 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
2100 foreach ( $a as $row ) {
2106 $sql .= '(' . $this->makeList( $row ) . ')';
2109 $sql .= '(' . $this->makeList( $a ) . ')';
2112 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
2114 } elseif ( $fh !== null ) {
2118 return (bool)$this->query( $sql, $fname );
2122 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
2124 * @param array $options
2127 protected function makeUpdateOptionsArray( $options ) {
2128 if ( !is_array( $options ) ) {
2129 $options = array( $options );
2134 if ( in_array( 'LOW_PRIORITY', $options ) ) {
2135 $opts[] = $this->lowPriorityOption();
2138 if ( in_array( 'IGNORE', $options ) ) {
2146 * Make UPDATE options for the DatabaseBase::update function
2148 * @param array $options The options passed to DatabaseBase::update
2151 protected function makeUpdateOptions( $options ) {
2152 $opts = $this->makeUpdateOptionsArray( $options );
2154 return implode( ' ', $opts );
2158 * UPDATE wrapper. Takes a condition array and a SET array.
2160 * @param string $table Name of the table to UPDATE. This will be passed through
2161 * DatabaseBase::tableName().
2162 * @param array $values An array of values to SET. For each array element,
2163 * the key gives the field name, and the value gives the data to set
2164 * that field to. The data will be quoted by DatabaseBase::addQuotes().
2165 * @param array $conds An array of conditions (WHERE). See
2166 * DatabaseBase::select() for the details of the format of condition
2167 * arrays. Use '*' to update all rows.
2168 * @param string $fname The function name of the caller (from __METHOD__),
2169 * for logging and profiling.
2170 * @param array $options An array of UPDATE options, can be:
2171 * - IGNORE: Ignore unique key conflicts
2172 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
2175 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
2176 $table = $this->tableName( $table );
2177 $opts = $this->makeUpdateOptions( $options );
2178 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
2180 if ( $conds !== array() && $conds !== '*' ) {
2181 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
2184 return $this->query( $sql, $fname );
2188 * Makes an encoded list of strings from an array
2190 * @param array $a Containing the data
2191 * @param int $mode Constant
2192 * - LIST_COMMA: Comma separated, no field names
2193 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2194 * documentation for $conds in DatabaseBase::select().
2195 * - LIST_OR: ORed WHERE clause (without the WHERE)
2196 * - LIST_SET: Comma separated with field names, like a SET clause
2197 * - LIST_NAMES: Comma separated field names
2198 * @throws MWException|DBUnexpectedError
2201 public function makeList( $a, $mode = LIST_COMMA
) {
2202 if ( !is_array( $a ) ) {
2203 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2209 foreach ( $a as $field => $value ) {
2211 if ( $mode == LIST_AND
) {
2213 } elseif ( $mode == LIST_OR
) {
2222 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
2223 $list .= "($value)";
2224 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
2226 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
2227 // Remove null from array to be handled separately if found
2228 $includeNull = false;
2229 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2230 $includeNull = true;
2231 unset( $value[$nullKey] );
2233 if ( count( $value ) == 0 && !$includeNull ) {
2234 throw new MWException( __METHOD__
. ": empty input for field $field" );
2235 } elseif ( count( $value ) == 0 ) {
2236 // only check if $field is null
2237 $list .= "$field IS NULL";
2239 // IN clause contains at least one valid element
2240 if ( $includeNull ) {
2241 // Group subconditions to ensure correct precedence
2244 if ( count( $value ) == 1 ) {
2245 // Special-case single values, as IN isn't terribly efficient
2246 // Don't necessarily assume the single key is 0; we don't
2247 // enforce linear numeric ordering on other arrays here.
2248 $value = array_values( $value );
2249 $list .= $field . " = " . $this->addQuotes( $value[0] );
2251 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2253 // if null present in array, append IS NULL
2254 if ( $includeNull ) {
2255 $list .= " OR $field IS NULL)";
2258 } elseif ( $value === null ) {
2259 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
2260 $list .= "$field IS ";
2261 } elseif ( $mode == LIST_SET
) {
2262 $list .= "$field = ";
2266 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
2267 $list .= "$field = ";
2269 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
2277 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2278 * The keys on each level may be either integers or strings.
2280 * @param array $data Organized as 2-d
2281 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2282 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2283 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2284 * @return string|bool SQL fragment, or false if no items in array
2286 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2289 foreach ( $data as $base => $sub ) {
2290 if ( count( $sub ) ) {
2291 $conds[] = $this->makeList(
2292 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2298 return $this->makeList( $conds, LIST_OR
);
2300 // Nothing to search for...
2306 * Return aggregated value alias
2308 * @param array $valuedata
2309 * @param string $valuename
2313 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2318 * @param string $field
2321 public function bitNot( $field ) {
2326 * @param string $fieldLeft
2327 * @param string $fieldRight
2330 public function bitAnd( $fieldLeft, $fieldRight ) {
2331 return "($fieldLeft & $fieldRight)";
2335 * @param string $fieldLeft
2336 * @param string $fieldRight
2339 public function bitOr( $fieldLeft, $fieldRight ) {
2340 return "($fieldLeft | $fieldRight)";
2344 * Build a concatenation list to feed into a SQL query
2345 * @param array $stringList List of raw SQL expressions; caller is
2346 * responsible for any quoting
2349 public function buildConcat( $stringList ) {
2350 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2354 * Build a GROUP_CONCAT or equivalent statement for a query.
2356 * This is useful for combining a field for several rows into a single string.
2357 * NULL values will not appear in the output, duplicated values will appear,
2358 * and the resulting delimiter-separated values have no defined sort order.
2359 * Code using the results may need to use the PHP unique() or sort() methods.
2361 * @param string $delim Glue to bind the results together
2362 * @param string|array $table Table name
2363 * @param string $field Field name
2364 * @param string|array $conds Conditions
2365 * @param string|array $join_conds Join conditions
2366 * @return string SQL text
2369 public function buildGroupConcatField(
2370 $delim, $table, $field, $conds = '', $join_conds = array()
2372 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2374 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2378 * Change the current database
2380 * @todo Explain what exactly will fail if this is not overridden.
2384 * @return bool Success or failure
2386 public function selectDB( $db ) {
2387 # Stub. Shouldn't cause serious problems if it's not overridden, but
2388 # if your database engine supports a concept similar to MySQL's
2389 # databases you may as well.
2390 $this->mDBname
= $db;
2396 * Get the current DB name
2399 public function getDBname() {
2400 return $this->mDBname
;
2404 * Get the server hostname or IP address
2407 public function getServer() {
2408 return $this->mServer
;
2412 * Format a table name ready for use in constructing an SQL query
2414 * This does two important things: it quotes the table names to clean them up,
2415 * and it adds a table prefix if only given a table name with no quotes.
2417 * All functions of this object which require a table name call this function
2418 * themselves. Pass the canonical name to such functions. This is only needed
2419 * when calling query() directly.
2421 * @param string $name Database table name
2422 * @param string $format One of:
2423 * quoted - Automatically pass the table name through addIdentifierQuotes()
2424 * so that it can be used in a query.
2425 * raw - Do not add identifier quotes to the table name
2426 * @return string Full database name
2428 public function tableName( $name, $format = 'quoted' ) {
2429 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2430 # Skip the entire process when we have a string quoted on both ends.
2431 # Note that we check the end so that we will still quote any use of
2432 # use of `database`.table. But won't break things if someone wants
2433 # to query a database table with a dot in the name.
2434 if ( $this->isQuotedIdentifier( $name ) ) {
2438 # Lets test for any bits of text that should never show up in a table
2439 # name. Basically anything like JOIN or ON which are actually part of
2440 # SQL queries, but may end up inside of the table value to combine
2441 # sql. Such as how the API is doing.
2442 # Note that we use a whitespace test rather than a \b test to avoid
2443 # any remote case where a word like on may be inside of a table name
2444 # surrounded by symbols which may be considered word breaks.
2445 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2449 # Split database and table into proper variables.
2450 # We reverse the explode so that database.table and table both output
2451 # the correct table.
2452 $dbDetails = explode( '.', $name, 3 );
2453 if ( count( $dbDetails ) == 3 ) {
2454 list( $database, $schema, $table ) = $dbDetails;
2455 # We don't want any prefix added in this case
2457 } elseif ( count( $dbDetails ) == 2 ) {
2458 list( $database, $table ) = $dbDetails;
2459 # We don't want any prefix added in this case
2460 # In dbs that support it, $database may actually be the schema
2461 # but that doesn't affect any of the functionality here
2465 list( $table ) = $dbDetails;
2466 if ( $wgSharedDB !== null # We have a shared database
2467 && $this->mForeign
== false # We're not working on a foreign database
2468 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2469 && in_array( $table, $wgSharedTables ) # A shared table is selected
2471 $database = $wgSharedDB;
2472 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
2473 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
2476 $schema = $this->mSchema
; # Default schema
2477 $prefix = $this->mTablePrefix
; # Default prefix
2481 # Quote $table and apply the prefix if not quoted.
2482 # $tableName might be empty if this is called from Database::replaceVars()
2483 $tableName = "{$prefix}{$table}";
2484 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2485 $tableName = $this->addIdentifierQuotes( $tableName );
2488 # Quote $schema and merge it with the table name if needed
2489 if ( strlen( $schema ) ) {
2490 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2491 $schema = $this->addIdentifierQuotes( $schema );
2493 $tableName = $schema . '.' . $tableName;
2496 # Quote $database and merge it with the table name if needed
2497 if ( $database !== null ) {
2498 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2499 $database = $this->addIdentifierQuotes( $database );
2501 $tableName = $database . '.' . $tableName;
2508 * Fetch a number of table names into an array
2509 * This is handy when you need to construct SQL for joins
2512 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2513 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2514 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2518 public function tableNames() {
2519 $inArray = func_get_args();
2522 foreach ( $inArray as $name ) {
2523 $retVal[$name] = $this->tableName( $name );
2530 * Fetch a number of table names into an zero-indexed numerical array
2531 * This is handy when you need to construct SQL for joins
2534 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2535 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2536 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2540 public function tableNamesN() {
2541 $inArray = func_get_args();
2544 foreach ( $inArray as $name ) {
2545 $retVal[] = $this->tableName( $name );
2552 * Get an aliased table name
2553 * e.g. tableName AS newTableName
2555 * @param string $name Table name, see tableName()
2556 * @param string|bool $alias Alias (optional)
2557 * @return string SQL name for aliased table. Will not alias a table to its own name
2559 public function tableNameWithAlias( $name, $alias = false ) {
2560 if ( !$alias ||
$alias == $name ) {
2561 return $this->tableName( $name );
2563 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2568 * Gets an array of aliased table names
2570 * @param array $tables Array( [alias] => table )
2571 * @return string[] See tableNameWithAlias()
2573 public function tableNamesWithAlias( $tables ) {
2575 foreach ( $tables as $alias => $table ) {
2576 if ( is_numeric( $alias ) ) {
2579 $retval[] = $this->tableNameWithAlias( $table, $alias );
2586 * Get an aliased field name
2587 * e.g. fieldName AS newFieldName
2589 * @param string $name Field name
2590 * @param string|bool $alias Alias (optional)
2591 * @return string SQL name for aliased field. Will not alias a field to its own name
2593 public function fieldNameWithAlias( $name, $alias = false ) {
2594 if ( !$alias ||
(string)$alias === (string)$name ) {
2597 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2602 * Gets an array of aliased field names
2604 * @param array $fields Array( [alias] => field )
2605 * @return string[] See fieldNameWithAlias()
2607 public function fieldNamesWithAlias( $fields ) {
2609 foreach ( $fields as $alias => $field ) {
2610 if ( is_numeric( $alias ) ) {
2613 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2620 * Get the aliased table name clause for a FROM clause
2621 * which might have a JOIN and/or USE INDEX clause
2623 * @param array $tables ( [alias] => table )
2624 * @param array $use_index Same as for select()
2625 * @param array $join_conds Same as for select()
2628 protected function tableNamesWithUseIndexOrJOIN(
2629 $tables, $use_index = array(), $join_conds = array()
2633 $use_index = (array)$use_index;
2634 $join_conds = (array)$join_conds;
2636 foreach ( $tables as $alias => $table ) {
2637 if ( !is_string( $alias ) ) {
2638 // No alias? Set it equal to the table name
2641 // Is there a JOIN clause for this table?
2642 if ( isset( $join_conds[$alias] ) ) {
2643 list( $joinType, $conds ) = $join_conds[$alias];
2644 $tableClause = $joinType;
2645 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2646 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2647 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2649 $tableClause .= ' ' . $use;
2652 $on = $this->makeList( (array)$conds, LIST_AND
);
2654 $tableClause .= ' ON (' . $on . ')';
2657 $retJOIN[] = $tableClause;
2658 } elseif ( isset( $use_index[$alias] ) ) {
2659 // Is there an INDEX clause for this table?
2660 $tableClause = $this->tableNameWithAlias( $table, $alias );
2661 $tableClause .= ' ' . $this->useIndexClause(
2662 implode( ',', (array)$use_index[$alias] )
2665 $ret[] = $tableClause;
2667 $tableClause = $this->tableNameWithAlias( $table, $alias );
2669 $ret[] = $tableClause;
2673 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2674 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2675 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2677 // Compile our final table clause
2678 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2682 * Get the name of an index in a given table.
2684 * @protected Don't use outside of DatabaseBase and childs
2685 * @param string $index
2688 public function indexName( $index ) {
2689 // @FIXME: Make this protected once we move away from PHP 5.3
2690 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
2692 // Backwards-compatibility hack
2694 'ar_usertext_timestamp' => 'usertext_timestamp',
2695 'un_user_id' => 'user_id',
2696 'un_user_ip' => 'user_ip',
2699 if ( isset( $renamed[$index] ) ) {
2700 return $renamed[$index];
2707 * Adds quotes and backslashes.
2709 * @param string|Blob $s
2712 public function addQuotes( $s ) {
2713 if ( $s instanceof Blob
) {
2716 if ( $s === null ) {
2719 # This will also quote numeric values. This should be harmless,
2720 # and protects against weird problems that occur when they really
2721 # _are_ strings such as article titles and string->number->string
2722 # conversion is not 1:1.
2723 return "'" . $this->strencode( $s ) . "'";
2728 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2729 * MySQL uses `backticks` while basically everything else uses double quotes.
2730 * Since MySQL is the odd one out here the double quotes are our generic
2731 * and we implement backticks in DatabaseMysql.
2736 public function addIdentifierQuotes( $s ) {
2737 return '"' . str_replace( '"', '""', $s ) . '"';
2741 * Returns if the given identifier looks quoted or not according to
2742 * the database convention for quoting identifiers .
2744 * @param string $name
2747 public function isQuotedIdentifier( $name ) {
2748 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2755 protected function escapeLikeInternal( $s ) {
2756 return addcslashes( $s, '\%_' );
2760 * LIKE statement wrapper, receives a variable-length argument list with
2761 * parts of pattern to match containing either string literals that will be
2762 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2763 * the function could be provided with an array of aforementioned
2766 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2767 * a LIKE clause that searches for subpages of 'My page title'.
2769 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2770 * $query .= $dbr->buildLike( $pattern );
2773 * @return string Fully built LIKE statement
2775 public function buildLike() {
2776 $params = func_get_args();
2778 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2779 $params = $params[0];
2784 foreach ( $params as $value ) {
2785 if ( $value instanceof LikeMatch
) {
2786 $s .= $value->toString();
2788 $s .= $this->escapeLikeInternal( $value );
2792 return " LIKE {$this->addQuotes( $s )} ";
2796 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2800 public function anyChar() {
2801 return new LikeMatch( '_' );
2805 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2809 public function anyString() {
2810 return new LikeMatch( '%' );
2814 * Returns an appropriately quoted sequence value for inserting a new row.
2815 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2816 * subclass will return an integer, and save the value for insertId()
2818 * Any implementation of this function should *not* involve reusing
2819 * sequence numbers created for rolled-back transactions.
2820 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2821 * @param string $seqName
2824 public function nextSequenceValue( $seqName ) {
2829 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2830 * is only needed because a) MySQL must be as efficient as possible due to
2831 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2832 * which index to pick. Anyway, other databases might have different
2833 * indexes on a given table. So don't bother overriding this unless you're
2835 * @param string $index
2838 public function useIndexClause( $index ) {
2843 * REPLACE query wrapper.
2845 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2846 * except that when there is a duplicate key error, the old row is deleted
2847 * and the new row is inserted in its place.
2849 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2850 * perform the delete, we need to know what the unique indexes are so that
2851 * we know how to find the conflicting rows.
2853 * It may be more efficient to leave off unique indexes which are unlikely
2854 * to collide. However if you do this, you run the risk of encountering
2855 * errors which wouldn't have occurred in MySQL.
2857 * @param string $table The table to replace the row(s) in.
2858 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2859 * a field name or an array of field names
2860 * @param array $rows Can be either a single row to insert, or multiple rows,
2861 * in the same format as for DatabaseBase::insert()
2862 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2864 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2865 $quotedTable = $this->tableName( $table );
2867 if ( count( $rows ) == 0 ) {
2872 if ( !is_array( reset( $rows ) ) ) {
2873 $rows = array( $rows );
2876 foreach ( $rows as $row ) {
2877 # Delete rows which collide
2878 if ( $uniqueIndexes ) {
2879 $sql = "DELETE FROM $quotedTable WHERE ";
2881 foreach ( $uniqueIndexes as $index ) {
2888 if ( is_array( $index ) ) {
2890 foreach ( $index as $col ) {
2896 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2899 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2903 $this->query( $sql, $fname );
2906 # Now insert the row
2907 $this->insert( $table, $row, $fname );
2912 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2915 * @param string $table Table name
2916 * @param array|string $rows Row(s) to insert
2917 * @param string $fname Caller function name
2919 * @return ResultWrapper
2921 protected function nativeReplace( $table, $rows, $fname ) {
2922 $table = $this->tableName( $table );
2925 if ( !is_array( reset( $rows ) ) ) {
2926 $rows = array( $rows );
2929 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2932 foreach ( $rows as $row ) {
2939 $sql .= '(' . $this->makeList( $row ) . ')';
2942 return $this->query( $sql, $fname );
2946 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2948 * This updates any conflicting rows (according to the unique indexes) using
2949 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2951 * $rows may be either:
2952 * - A single associative array. The array keys are the field names, and
2953 * the values are the values to insert. The values are treated as data
2954 * and will be quoted appropriately. If NULL is inserted, this will be
2955 * converted to a database NULL.
2956 * - An array with numeric keys, holding a list of associative arrays.
2957 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2958 * each subarray must be identical to each other, and in the same order.
2960 * It may be more efficient to leave off unique indexes which are unlikely
2961 * to collide. However if you do this, you run the risk of encountering
2962 * errors which wouldn't have occurred in MySQL.
2964 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2969 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2970 * @param array $rows A single row or list of rows to insert
2971 * @param array $uniqueIndexes List of single field names or field name tuples
2972 * @param array $set An array of values to SET. For each array element, the
2973 * key gives the field name, and the value gives the data to set that
2974 * field to. The data will be quoted by DatabaseBase::addQuotes().
2975 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2979 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2982 if ( !count( $rows ) ) {
2983 return true; // nothing to do
2986 if ( !is_array( reset( $rows ) ) ) {
2987 $rows = array( $rows );
2990 if ( count( $uniqueIndexes ) ) {
2991 $clauses = array(); // list WHERE clauses that each identify a single row
2992 foreach ( $rows as $row ) {
2993 foreach ( $uniqueIndexes as $index ) {
2994 $index = is_array( $index ) ?
$index : array( $index ); // columns
2995 $rowKey = array(); // unique key to this row
2996 foreach ( $index as $column ) {
2997 $rowKey[$column] = $row[$column];
2999 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
3002 $where = array( $this->makeList( $clauses, LIST_OR
) );
3007 $useTrx = !$this->mTrxLevel
;
3009 $this->begin( $fname );
3012 # Update any existing conflicting row(s)
3013 if ( $where !== false ) {
3014 $ok = $this->update( $table, $set, $where, $fname );
3018 # Now insert any non-conflicting row(s)
3019 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
3020 } catch ( Exception
$e ) {
3022 $this->rollback( $fname );
3027 $this->commit( $fname );
3034 * DELETE where the condition is a join.
3036 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
3037 * we use sub-selects
3039 * For safety, an empty $conds will not delete everything. If you want to
3040 * delete all rows where the join condition matches, set $conds='*'.
3042 * DO NOT put the join condition in $conds.
3044 * @param string $delTable The table to delete from.
3045 * @param string $joinTable The other table.
3046 * @param string $delVar The variable to join on, in the first table.
3047 * @param string $joinVar The variable to join on, in the second table.
3048 * @param array $conds Condition array of field names mapped to variables,
3049 * ANDed together in the WHERE clause
3050 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
3051 * @throws DBUnexpectedError
3053 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
3057 throw new DBUnexpectedError( $this,
3058 'DatabaseBase::deleteJoin() called with empty $conds' );
3061 $delTable = $this->tableName( $delTable );
3062 $joinTable = $this->tableName( $joinTable );
3063 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
3064 if ( $conds != '*' ) {
3065 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
3069 $this->query( $sql, $fname );
3073 * Returns the size of a text field, or -1 for "unlimited"
3075 * @param string $table
3076 * @param string $field
3079 public function textFieldSize( $table, $field ) {
3080 $table = $this->tableName( $table );
3081 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
3082 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
3083 $row = $this->fetchObject( $res );
3087 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
3097 * A string to insert into queries to show that they're low-priority, like
3098 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
3099 * string and nothing bad should happen.
3101 * @return string Returns the text of the low priority option if it is
3102 * supported, or a blank string otherwise
3104 public function lowPriorityOption() {
3109 * DELETE query wrapper.
3111 * @param array $table Table name
3112 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
3113 * for the format. Use $conds == "*" to delete all rows
3114 * @param string $fname Name of the calling function
3115 * @throws DBUnexpectedError
3116 * @return bool|ResultWrapper
3118 public function delete( $table, $conds, $fname = __METHOD__
) {
3120 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
3123 $table = $this->tableName( $table );
3124 $sql = "DELETE FROM $table";
3126 if ( $conds != '*' ) {
3127 if ( is_array( $conds ) ) {
3128 $conds = $this->makeList( $conds, LIST_AND
);
3130 $sql .= ' WHERE ' . $conds;
3133 return $this->query( $sql, $fname );
3137 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
3138 * into another table.
3140 * @param string $destTable The table name to insert into
3141 * @param string|array $srcTable May be either a table name, or an array of table names
3142 * to include in a join.
3144 * @param array $varMap Must be an associative array of the form
3145 * array( 'dest1' => 'source1', ...). Source items may be literals
3146 * rather than field names, but strings should be quoted with
3147 * DatabaseBase::addQuotes()
3149 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
3150 * the details of the format of condition arrays. May be "*" to copy the
3153 * @param string $fname The function name of the caller, from __METHOD__
3155 * @param array $insertOptions Options for the INSERT part of the query, see
3156 * DatabaseBase::insert() for details.
3157 * @param array $selectOptions Options for the SELECT part of the query, see
3158 * DatabaseBase::select() for details.
3160 * @return ResultWrapper
3162 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
3163 $fname = __METHOD__
,
3164 $insertOptions = array(), $selectOptions = array()
3166 $destTable = $this->tableName( $destTable );
3168 if ( !is_array( $insertOptions ) ) {
3169 $insertOptions = array( $insertOptions );
3172 $insertOptions = $this->makeInsertOptions( $insertOptions );
3174 if ( !is_array( $selectOptions ) ) {
3175 $selectOptions = array( $selectOptions );
3178 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
3180 if ( is_array( $srcTable ) ) {
3181 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
3183 $srcTable = $this->tableName( $srcTable );
3186 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
3187 " SELECT $startOpts " . implode( ',', $varMap ) .
3188 " FROM $srcTable $useIndex ";
3190 if ( $conds != '*' ) {
3191 if ( is_array( $conds ) ) {
3192 $conds = $this->makeList( $conds, LIST_AND
);
3194 $sql .= " WHERE $conds";
3197 $sql .= " $tailOpts";
3199 return $this->query( $sql, $fname );
3203 * Construct a LIMIT query with optional offset. This is used for query
3204 * pages. The SQL should be adjusted so that only the first $limit rows
3205 * are returned. If $offset is provided as well, then the first $offset
3206 * rows should be discarded, and the next $limit rows should be returned.
3207 * If the result of the query is not ordered, then the rows to be returned
3208 * are theoretically arbitrary.
3210 * $sql is expected to be a SELECT, if that makes a difference.
3212 * The version provided by default works in MySQL and SQLite. It will very
3213 * likely need to be overridden for most other DBMSes.
3215 * @param string $sql SQL query we will append the limit too
3216 * @param int $limit The SQL limit
3217 * @param int|bool $offset The SQL offset (default false)
3218 * @throws DBUnexpectedError
3221 public function limitResult( $sql, $limit, $offset = false ) {
3222 if ( !is_numeric( $limit ) ) {
3223 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3226 return "$sql LIMIT "
3227 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3232 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3233 * within the UNION construct.
3236 public function unionSupportsOrderAndLimit() {
3237 return true; // True for almost every DB supported
3241 * Construct a UNION query
3242 * This is used for providing overload point for other DB abstractions
3243 * not compatible with the MySQL syntax.
3244 * @param array $sqls SQL statements to combine
3245 * @param bool $all Use UNION ALL
3246 * @return string SQL fragment
3248 public function unionQueries( $sqls, $all ) {
3249 $glue = $all ?
') UNION ALL (' : ') UNION (';
3251 return '(' . implode( $glue, $sqls ) . ')';
3255 * Returns an SQL expression for a simple conditional. This doesn't need
3256 * to be overridden unless CASE isn't supported in your DBMS.
3258 * @param string|array $cond SQL expression which will result in a boolean value
3259 * @param string $trueVal SQL expression to return if true
3260 * @param string $falseVal SQL expression to return if false
3261 * @return string SQL fragment
3263 public function conditional( $cond, $trueVal, $falseVal ) {
3264 if ( is_array( $cond ) ) {
3265 $cond = $this->makeList( $cond, LIST_AND
);
3268 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3272 * Returns a comand for str_replace function in SQL query.
3273 * Uses REPLACE() in MySQL
3275 * @param string $orig Column to modify
3276 * @param string $old Column to seek
3277 * @param string $new Column to replace with
3281 public function strreplace( $orig, $old, $new ) {
3282 return "REPLACE({$orig}, {$old}, {$new})";
3286 * Determines how long the server has been up
3291 public function getServerUptime() {
3296 * Determines if the last failure was due to a deadlock
3301 public function wasDeadlock() {
3306 * Determines if the last failure was due to a lock timeout
3311 public function wasLockTimeout() {
3316 * Determines if the last query error was something that should be dealt
3317 * with by pinging the connection and reissuing the query.
3322 public function wasErrorReissuable() {
3327 * Determines if the last failure was due to the database being read-only.
3332 public function wasReadOnlyError() {
3337 * Perform a deadlock-prone transaction.
3339 * This function invokes a callback function to perform a set of write
3340 * queries. If a deadlock occurs during the processing, the transaction
3341 * will be rolled back and the callback function will be called again.
3344 * $dbw->deadlockLoop( callback, ... );
3346 * Extra arguments are passed through to the specified callback function.
3348 * Returns whatever the callback function returned on its successful,
3349 * iteration, or false on error, for example if the retry limit was
3354 public function deadlockLoop() {
3355 $args = func_get_args();
3356 $function = array_shift( $args );
3357 $tries = self
::DEADLOCK_TRIES
;
3358 if ( is_array( $function ) ) {
3359 $fname = $function[0];
3364 $this->begin( __METHOD__
);
3369 $retVal = call_user_func_array( $function, $args );
3371 } catch ( DBQueryError
$e ) {
3372 $error = $this->lastError();
3373 $errno = $this->lastErrno();
3374 $sql = $this->lastQuery();
3375 if ( $this->wasDeadlock() ) {
3376 // Retry after a randomized delay
3377 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3379 // Throw the error back up
3383 } while ( --$tries > 0 );
3385 if ( $tries <= 0 ) {
3386 // Too many deadlocks; give up
3387 $this->rollback( __METHOD__
);
3390 $this->commit( __METHOD__
);
3397 * Wait for the slave to catch up to a given master position.
3399 * @param DBMasterPos $pos
3400 * @param int $timeout The maximum number of seconds to wait for
3402 * @return int Zero if the slave was past that position already,
3403 * greater than zero if we waited for some period of time, less than
3404 * zero if we timed out.
3406 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3407 # Real waits are implemented in the subclass.
3412 * Get the replication position of this slave
3414 * @return DBMasterPos|bool False if this is not a slave.
3416 public function getSlavePos() {
3422 * Get the position of this master
3424 * @return DBMasterPos|bool False if this is not a master
3426 public function getMasterPos() {
3432 * Run an anonymous function as soon as there is no transaction pending.
3433 * If there is a transaction and it is rolled back, then the callback is cancelled.
3434 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3435 * Callbacks must commit any transactions that they begin.
3437 * This is useful for updates to different systems or when separate transactions are needed.
3438 * For example, one might want to enqueue jobs into a system outside the database, but only
3439 * after the database is updated so that the jobs will see the data when they actually run.
3440 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3442 * @param callable $callback
3445 final public function onTransactionIdle( $callback ) {
3446 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
3447 if ( !$this->mTrxLevel
) {
3448 $this->runOnTransactionIdleCallbacks();
3453 * Run an anonymous function before the current transaction commits or now if there is none.
3454 * If there is a transaction and it is rolled back, then the callback is cancelled.
3455 * Callbacks must not start nor commit any transactions.
3457 * This is useful for updates that easily cause deadlocks if locks are held too long
3458 * but where atomicity is strongly desired for these updates and some related updates.
3460 * @param callable $callback
3463 final public function onTransactionPreCommitOrIdle( $callback ) {
3464 if ( $this->mTrxLevel
) {
3465 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
3467 $this->onTransactionIdle( $callback ); // this will trigger immediately
3472 * Actually any "on transaction idle" callbacks.
3476 protected function runOnTransactionIdleCallbacks() {
3477 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
3479 $e = $ePrior = null; // last exception
3480 do { // callbacks may add callbacks :)
3481 $callbacks = $this->mTrxIdleCallbacks
;
3482 $this->mTrxIdleCallbacks
= array(); // recursion guard
3483 foreach ( $callbacks as $callback ) {
3485 list( $phpCallback ) = $callback;
3486 $this->clearFlag( DBO_TRX
); // make each query its own transaction
3487 call_user_func( $phpCallback );
3488 $this->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
3489 } catch ( Exception
$e ) {
3491 MWExceptionHandler
::logException( $ePrior );
3496 } while ( count( $this->mTrxIdleCallbacks
) );
3498 if ( $e instanceof Exception
) {
3499 throw $e; // re-throw any last exception
3504 * Actually any "on transaction pre-commit" callbacks.
3508 protected function runOnTransactionPreCommitCallbacks() {
3509 $e = $ePrior = null; // last exception
3510 do { // callbacks may add callbacks :)
3511 $callbacks = $this->mTrxPreCommitCallbacks
;
3512 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
3513 foreach ( $callbacks as $callback ) {
3515 list( $phpCallback ) = $callback;
3516 call_user_func( $phpCallback );
3517 } catch ( Exception
$e ) {
3519 MWExceptionHandler
::logException( $ePrior );
3524 } while ( count( $this->mTrxPreCommitCallbacks
) );
3526 if ( $e instanceof Exception
) {
3527 throw $e; // re-throw any last exception
3532 * Begin an atomic section of statements
3534 * If a transaction has been started already, just keep track of the given
3535 * section name to make sure the transaction is not committed pre-maturely.
3536 * This function can be used in layers (with sub-sections), so use a stack
3537 * to keep track of the different atomic sections. If there is no transaction,
3538 * start one implicitly.
3540 * The goal of this function is to create an atomic section of SQL queries
3541 * without having to start a new transaction if it already exists.
3543 * Atomic sections are more strict than transactions. With transactions,
3544 * attempting to begin a new transaction when one is already running results
3545 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3546 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3547 * and any database transactions cannot be began or committed until all atomic
3548 * levels are closed. There is no such thing as implicitly opening or closing
3549 * an atomic section.
3552 * @param string $fname
3555 final public function startAtomic( $fname = __METHOD__
) {
3556 if ( !$this->mTrxLevel
) {
3557 $this->begin( $fname );
3558 $this->mTrxAutomatic
= true;
3559 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3560 // in all changes being in one transaction to keep requests transactional.
3561 if ( !$this->getFlag( DBO_TRX
) ) {
3562 $this->mTrxAutomaticAtomic
= true;
3566 $this->mTrxAtomicLevels
->push( $fname );
3570 * Ends an atomic section of SQL statements
3572 * Ends the next section of atomic SQL statements and commits the transaction
3576 * @see DatabaseBase::startAtomic
3577 * @param string $fname
3580 final public function endAtomic( $fname = __METHOD__
) {
3581 if ( !$this->mTrxLevel
) {
3582 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3584 if ( $this->mTrxAtomicLevels
->isEmpty() ||
3585 $this->mTrxAtomicLevels
->pop() !== $fname
3587 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3590 if ( $this->mTrxAtomicLevels
->isEmpty() && $this->mTrxAutomaticAtomic
) {
3591 $this->commit( $fname, 'flush' );
3596 * Begin a transaction. If a transaction is already in progress,
3597 * that transaction will be committed before the new transaction is started.
3599 * Note that when the DBO_TRX flag is set (which is usually the case for web
3600 * requests, but not for maintenance scripts), any previous database query
3601 * will have started a transaction automatically.
3603 * Nesting of transactions is not supported. Attempts to nest transactions
3604 * will cause a warning, unless the current transaction was started
3605 * automatically because of the DBO_TRX flag.
3607 * @param string $fname
3610 final public function begin( $fname = __METHOD__
) {
3611 global $wgDebugDBTransactions;
3613 if ( $this->mTrxLevel
) { // implicit commit
3614 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3615 // If the current transaction was an automatic atomic one, then we definitely have
3616 // a problem. Same if there is any unclosed atomic level.
3617 throw new DBUnexpectedError( $this,
3618 "Attempted to start explicit transaction when atomic levels are still open."
3620 } elseif ( !$this->mTrxAutomatic
) {
3621 // We want to warn about inadvertently nested begin/commit pairs, but not about
3622 // auto-committing implicit transactions that were started by query() via DBO_TRX
3623 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3624 " performing implicit commit!";
3627 $this->getLogContext( array(
3628 'method' => __METHOD__
,
3633 // if the transaction was automatic and has done write operations,
3634 // log it if $wgDebugDBTransactions is enabled.
3635 if ( $this->mTrxDoneWrites
&& $wgDebugDBTransactions ) {
3636 wfDebug( "$fname: Automatic transaction with writes in progress" .
3637 " (from {$this->mTrxFname}), performing implicit commit!\n"
3642 $this->runOnTransactionPreCommitCallbacks();
3643 $writeTime = $this->pendingWriteQueryDuration();
3644 $this->doCommit( $fname );
3645 if ( $this->mTrxDoneWrites
) {
3646 $this->mDoneWrites
= microtime( true );
3647 $this->getTransactionProfiler()->transactionWritingOut(
3648 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
3650 $this->runOnTransactionIdleCallbacks();
3653 # Avoid fatals if close() was called
3654 $this->assertOpen();
3656 $this->doBegin( $fname );
3657 $this->mTrxTimestamp
= microtime( true );
3658 $this->mTrxFname
= $fname;
3659 $this->mTrxDoneWrites
= false;
3660 $this->mTrxAutomatic
= false;
3661 $this->mTrxAutomaticAtomic
= false;
3662 $this->mTrxAtomicLevels
= new SplStack
;
3663 $this->mTrxIdleCallbacks
= array();
3664 $this->mTrxPreCommitCallbacks
= array();
3665 $this->mTrxShortId
= wfRandomString( 12 );
3666 $this->mTrxWriteDuration
= 0.0;
3670 * Issues the BEGIN command to the database server.
3672 * @see DatabaseBase::begin()
3673 * @param string $fname
3675 protected function doBegin( $fname ) {
3676 $this->query( 'BEGIN', $fname );
3677 $this->mTrxLevel
= 1;
3681 * Commits a transaction previously started using begin().
3682 * If no transaction is in progress, a warning is issued.
3684 * Nesting of transactions is not supported.
3686 * @param string $fname
3687 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3688 * explicitly committing implicit transactions, or calling commit when no
3689 * transaction is in progress. This will silently break any ongoing
3690 * explicit transaction. Only set the flush flag if you are sure that it
3691 * is safe to ignore these warnings in your context.
3692 * @throws DBUnexpectedError
3694 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3695 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3696 // There are still atomic sections open. This cannot be ignored
3697 throw new DBUnexpectedError(
3699 "Attempted to commit transaction while atomic sections are still open"
3703 if ( $flush === 'flush' ) {
3704 if ( !$this->mTrxLevel
) {
3705 return; // nothing to do
3706 } elseif ( !$this->mTrxAutomatic
) {
3707 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3710 if ( !$this->mTrxLevel
) {
3711 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3712 return; // nothing to do
3713 } elseif ( $this->mTrxAutomatic
) {
3714 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3718 # Avoid fatals if close() was called
3719 $this->assertOpen();
3721 $this->runOnTransactionPreCommitCallbacks();
3722 $writeTime = $this->pendingWriteQueryDuration();
3723 $this->doCommit( $fname );
3724 if ( $this->mTrxDoneWrites
) {
3725 $this->mDoneWrites
= microtime( true );
3726 $this->getTransactionProfiler()->transactionWritingOut(
3727 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
3729 $this->runOnTransactionIdleCallbacks();
3733 * Issues the COMMIT command to the database server.
3735 * @see DatabaseBase::commit()
3736 * @param string $fname
3738 protected function doCommit( $fname ) {
3739 if ( $this->mTrxLevel
) {
3740 $this->query( 'COMMIT', $fname );
3741 $this->mTrxLevel
= 0;
3746 * Rollback a transaction previously started using begin().
3747 * If no transaction is in progress, a warning is issued.
3749 * No-op on non-transactional databases.
3751 * @param string $fname
3752 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3753 * calling rollback when no transaction is in progress. This will silently
3754 * break any ongoing explicit transaction. Only set the flush flag if you
3755 * are sure that it is safe to ignore these warnings in your context.
3756 * @throws DBUnexpectedError
3757 * @since 1.23 Added $flush parameter
3759 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3760 if ( $flush !== 'flush' ) {
3761 if ( !$this->mTrxLevel
) {
3762 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3763 return; // nothing to do
3764 } elseif ( $this->mTrxAutomatic
) {
3765 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3768 if ( !$this->mTrxLevel
) {
3769 return; // nothing to do
3770 } elseif ( !$this->mTrxAutomatic
) {
3771 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3775 # Avoid fatals if close() was called
3776 $this->assertOpen();
3778 $this->doRollback( $fname );
3779 $this->mTrxIdleCallbacks
= array(); // cancel
3780 $this->mTrxPreCommitCallbacks
= array(); // cancel
3781 $this->mTrxAtomicLevels
= new SplStack
;
3782 if ( $this->mTrxDoneWrites
) {
3783 $this->getTransactionProfiler()->transactionWritingOut(
3784 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3789 * Issues the ROLLBACK command to the database server.
3791 * @see DatabaseBase::rollback()
3792 * @param string $fname
3794 protected function doRollback( $fname ) {
3795 if ( $this->mTrxLevel
) {
3796 $this->query( 'ROLLBACK', $fname, true );
3797 $this->mTrxLevel
= 0;
3802 * Creates a new table with structure copied from existing table
3803 * Note that unlike most database abstraction functions, this function does not
3804 * automatically append database prefix, because it works at a lower
3805 * abstraction level.
3806 * The table names passed to this function shall not be quoted (this
3807 * function calls addIdentifierQuotes when needed).
3809 * @param string $oldName Name of table whose structure should be copied
3810 * @param string $newName Name of table to be created
3811 * @param bool $temporary Whether the new table should be temporary
3812 * @param string $fname Calling function name
3813 * @throws MWException
3814 * @return bool True if operation was successful
3816 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3819 throw new MWException(
3820 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3824 * List all tables on the database
3826 * @param string $prefix Only show tables with this prefix, e.g. mw_
3827 * @param string $fname Calling function name
3828 * @throws MWException
3831 function listTables( $prefix = null, $fname = __METHOD__
) {
3832 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3836 * Reset the views process cache set by listViews()
3839 final public function clearViewsCache() {
3840 $this->allViews
= null;
3844 * Lists all the VIEWs in the database
3846 * For caching purposes the list of all views should be stored in
3847 * $this->allViews. The process cache can be cleared with clearViewsCache()
3849 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3850 * @param string $fname Name of calling function
3851 * @throws MWException
3855 public function listViews( $prefix = null, $fname = __METHOD__
) {
3856 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3860 * Differentiates between a TABLE and a VIEW
3862 * @param string $name Name of the database-structure to test.
3863 * @throws MWException
3867 public function isView( $name ) {
3868 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3872 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3873 * to the format used for inserting into timestamp fields in this DBMS.
3875 * The result is unquoted, and needs to be passed through addQuotes()
3876 * before it can be included in raw SQL.
3878 * @param string|int $ts
3882 public function timestamp( $ts = 0 ) {
3883 return wfTimestamp( TS_MW
, $ts );
3887 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3888 * to the format used for inserting into timestamp fields in this DBMS. If
3889 * NULL is input, it is passed through, allowing NULL values to be inserted
3890 * into timestamp fields.
3892 * The result is unquoted, and needs to be passed through addQuotes()
3893 * before it can be included in raw SQL.
3895 * @param string|int $ts
3899 public function timestampOrNull( $ts = null ) {
3900 if ( is_null( $ts ) ) {
3903 return $this->timestamp( $ts );
3908 * Take the result from a query, and wrap it in a ResultWrapper if
3909 * necessary. Boolean values are passed through as is, to indicate success
3910 * of write queries or failure.
3912 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3913 * resource, and it was necessary to call this function to convert it to
3914 * a wrapper. Nowadays, raw database objects are never exposed to external
3915 * callers, so this is unnecessary in external code. For compatibility with
3916 * old code, ResultWrapper objects are passed through unaltered.
3918 * @param bool|ResultWrapper|resource $result
3919 * @return bool|ResultWrapper
3921 public function resultObject( $result ) {
3922 if ( empty( $result ) ) {
3924 } elseif ( $result instanceof ResultWrapper
) {
3926 } elseif ( $result === true ) {
3927 // Successful write query
3930 return new ResultWrapper( $this, $result );
3935 * Ping the server and try to reconnect if it there is no connection
3937 * @return bool Success or failure
3939 public function ping() {
3940 # Stub. Not essential to override.
3945 * Get slave lag. Currently supported only by MySQL.
3947 * Note that this function will generate a fatal error on many
3948 * installations. Most callers should use LoadBalancer::safeGetLag()
3951 * @return int Database replication lag in seconds
3953 public function getLag() {
3958 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3962 function maxListLen() {
3967 * Some DBMSs have a special format for inserting into blob fields, they
3968 * don't allow simple quoted strings to be inserted. To insert into such
3969 * a field, pass the data through this function before passing it to
3970 * DatabaseBase::insert().
3975 public function encodeBlob( $b ) {
3980 * Some DBMSs return a special placeholder object representing blob fields
3981 * in result objects. Pass the object through this function to return the
3984 * @param string|Blob $b
3987 public function decodeBlob( $b ) {
3988 if ( $b instanceof Blob
) {
3995 * Override database's default behavior. $options include:
3996 * 'connTimeout' : Set the connection timeout value in seconds.
3997 * May be useful for very long batch queries such as
3998 * full-wiki dumps, where a single query reads out over
4001 * @param array $options
4004 public function setSessionOptions( array $options ) {
4008 * Read and execute SQL commands from a file.
4010 * Returns true on success, error string or exception on failure (depending
4011 * on object's error ignore settings).
4013 * @param string $filename File name to open
4014 * @param bool|callable $lineCallback Optional function called before reading each line
4015 * @param bool|callable $resultCallback Optional function called for each MySQL result
4016 * @param bool|string $fname Calling function name or false if name should be
4017 * generated dynamically using $filename
4018 * @param bool|callable $inputCallback Optional function called for each
4019 * complete line sent
4020 * @throws Exception|MWException
4021 * @return bool|string
4023 public function sourceFile(
4024 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
4026 MediaWiki\
suppressWarnings();
4027 $fp = fopen( $filename, 'r' );
4028 MediaWiki\restoreWarnings
();
4030 if ( false === $fp ) {
4031 throw new MWException( "Could not open \"{$filename}\".\n" );
4035 $fname = __METHOD__
. "( $filename )";
4039 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
4040 } catch ( Exception
$e ) {
4051 * Get the full path of a patch file. Originally based on archive()
4052 * from updaters.inc. Keep in mind this always returns a patch, as
4053 * it fails back to MySQL if no DB-specific patch can be found
4055 * @param string $patch The name of the patch, like patch-something.sql
4056 * @return string Full path to patch file
4058 public function patchPath( $patch ) {
4061 $dbType = $this->getType();
4062 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
4063 return "$IP/maintenance/$dbType/archives/$patch";
4065 return "$IP/maintenance/archives/$patch";
4070 * Set variables to be used in sourceFile/sourceStream, in preference to the
4071 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
4072 * all. If it's set to false, $GLOBALS will be used.
4074 * @param bool|array $vars Mapping variable name to value.
4076 public function setSchemaVars( $vars ) {
4077 $this->mSchemaVars
= $vars;
4081 * Read and execute commands from an open file handle.
4083 * Returns true on success, error string or exception on failure (depending
4084 * on object's error ignore settings).
4086 * @param resource $fp File handle
4087 * @param bool|callable $lineCallback Optional function called before reading each query
4088 * @param bool|callable $resultCallback Optional function called for each MySQL result
4089 * @param string $fname Calling function name
4090 * @param bool|callable $inputCallback Optional function called for each complete query sent
4091 * @return bool|string
4093 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
4094 $fname = __METHOD__
, $inputCallback = false
4098 while ( !feof( $fp ) ) {
4099 if ( $lineCallback ) {
4100 call_user_func( $lineCallback );
4103 $line = trim( fgets( $fp ) );
4105 if ( $line == '' ) {
4109 if ( '-' == $line[0] && '-' == $line[1] ) {
4117 $done = $this->streamStatementEnd( $cmd, $line );
4121 if ( $done ||
feof( $fp ) ) {
4122 $cmd = $this->replaceVars( $cmd );
4124 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
4125 $res = $this->query( $cmd, $fname );
4127 if ( $resultCallback ) {
4128 call_user_func( $resultCallback, $res, $this );
4131 if ( false === $res ) {
4132 $err = $this->lastError();
4134 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4145 * Called by sourceStream() to check if we've reached a statement end
4147 * @param string $sql SQL assembled so far
4148 * @param string $newLine New line about to be added to $sql
4149 * @return bool Whether $newLine contains end of the statement
4151 public function streamStatementEnd( &$sql, &$newLine ) {
4152 if ( $this->delimiter
) {
4154 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4155 if ( $newLine != $prev ) {
4164 * Database independent variable replacement. Replaces a set of variables
4165 * in an SQL statement with their contents as given by $this->getSchemaVars().
4167 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4169 * - '{$var}' should be used for text and is passed through the database's
4171 * - `{$var}` should be used for identifiers (e.g. table and database names).
4172 * It is passed through the database's addIdentifierQuotes method which
4173 * can be overridden if the database uses something other than backticks.
4174 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4175 * database's tableName method.
4176 * - / *i* / passes the name that follows through the database's indexName method.
4177 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4178 * its use should be avoided. In 1.24 and older, string encoding was applied.
4180 * @param string $ins SQL statement to replace variables in
4181 * @return string The new SQL statement with variables replaced
4183 protected function replaceVars( $ins ) {
4185 $vars = $this->getSchemaVars();
4186 return preg_replace_callback(
4188 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4189 \'\{\$ (\w+) }\' | # 3. addQuotes
4190 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4191 /\*\$ (\w+) \*/ # 5. leave unencoded
4193 function ( $m ) use ( $that, $vars ) {
4194 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4195 // check for both nonexistent keys *and* the empty string.
4196 if ( isset( $m[1] ) && $m[1] !== '' ) {
4197 if ( $m[1] === 'i' ) {
4198 return $that->indexName( $m[2] );
4200 return $that->tableName( $m[2] );
4202 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4203 return $that->addQuotes( $vars[$m[3]] );
4204 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4205 return $that->addIdentifierQuotes( $vars[$m[4]] );
4206 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4207 return $vars[$m[5]];
4217 * Get schema variables. If none have been set via setSchemaVars(), then
4218 * use some defaults from the current object.
4222 protected function getSchemaVars() {
4223 if ( $this->mSchemaVars
) {
4224 return $this->mSchemaVars
;
4226 return $this->getDefaultSchemaVars();
4231 * Get schema variables to use if none have been set via setSchemaVars().
4233 * Override this in derived classes to provide variables for tables.sql
4234 * and SQL patch files.
4238 protected function getDefaultSchemaVars() {
4243 * Check to see if a named lock is available (non-blocking)
4245 * @param string $lockName Name of lock to poll
4246 * @param string $method Name of method calling us
4250 public function lockIsFree( $lockName, $method ) {
4255 * Acquire a named lock
4257 * Named locks are not related to transactions
4259 * @param string $lockName Name of lock to aquire
4260 * @param string $method Name of method calling us
4261 * @param int $timeout
4264 public function lock( $lockName, $method, $timeout = 5 ) {
4271 * Named locks are not related to transactions
4273 * @param string $lockName Name of lock to release
4274 * @param string $method Name of method calling us
4276 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4277 * by this thread (in which case the lock is not released), and NULL if the named
4278 * lock did not exist
4280 public function unlock( $lockName, $method ) {
4285 * Check to see if a named lock used by lock() use blocking queues
4290 public function namedLocksEnqueue() {
4295 * Lock specific tables
4297 * @param array $read Array of tables to lock for read access
4298 * @param array $write Array of tables to lock for write access
4299 * @param string $method Name of caller
4300 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4303 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4308 * Unlock specific tables
4310 * @param string $method The caller
4313 public function unlockTables( $method ) {
4319 * @param string $tableName
4320 * @param string $fName
4321 * @return bool|ResultWrapper
4324 public function dropTable( $tableName, $fName = __METHOD__
) {
4325 if ( !$this->tableExists( $tableName, $fName ) ) {
4328 $sql = "DROP TABLE " . $this->tableName( $tableName );
4329 if ( $this->cascadingDeletes() ) {
4333 return $this->query( $sql, $fName );
4337 * Get search engine class. All subclasses of this need to implement this
4338 * if they wish to use searching.
4342 public function getSearchEngine() {
4343 return 'SearchEngineDummy';
4347 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4348 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4349 * because "i" sorts after all numbers.
4353 public function getInfinity() {
4358 * Encode an expiry time into the DBMS dependent format
4360 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4363 public function encodeExpiry( $expiry ) {
4364 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4365 ?
$this->getInfinity()
4366 : $this->timestamp( $expiry );
4370 * Decode an expiry time into a DBMS independent format
4372 * @param string $expiry DB timestamp field value for expiry
4373 * @param int $format TS_* constant, defaults to TS_MW
4376 public function decodeExpiry( $expiry, $format = TS_MW
) {
4377 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4379 : wfTimestamp( $format, $expiry );
4383 * Allow or deny "big selects" for this session only. This is done by setting
4384 * the sql_big_selects session variable.
4386 * This is a MySQL-specific feature.
4388 * @param bool|string $value True for allow, false for deny, or "default" to
4389 * restore the initial value
4391 public function setBigSelects( $value = true ) {
4399 public function __toString() {
4400 return (string)$this->mConn
;
4404 * Run a few simple sanity checks
4406 public function __destruct() {
4407 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
4408 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4410 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
4412 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
4413 $callers[] = $callbackInfo[1];
4415 $callers = implode( ', ', $callers );
4416 trigger_error( "DB transaction callbacks still pending (from $callers)." );