Merge "move page_restrictions.pr_id to top in tables.sql"
[mediawiki.git] / includes / db / Database.php
blobe2c59edb6b94b420953bc2e40366f754267e14b5
1 <?php
2 /**
3 * @defgroup Database Database
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
23 * @file
24 * @ingroup Database
27 /**
28 * Base interface for all DBMS-specific code. At a bare minimum, all of the
29 * following must be implemented to support MediaWiki
31 * @file
32 * @ingroup Database
34 interface DatabaseType {
35 /**
36 * Get the type of the DBMS, as it appears in $wgDBtype.
38 * @return string
40 function getType();
42 /**
43 * Open a connection to the database. Usually aborts on failure
45 * @param string $server database server host
46 * @param string $user database user name
47 * @param string $password database user password
48 * @param string $dbName database name
49 * @return bool
50 * @throws DBConnectionError
52 function open( $server, $user, $password, $dbName );
54 /**
55 * Fetch the next row from the given result object, in object form.
56 * Fields can be retrieved with $row->fieldname, with fields acting like
57 * member variables.
58 * If no more rows are available, false is returned.
60 * @param $res ResultWrapper|object as returned from DatabaseBase::query(), etc.
61 * @return object|bool
62 * @throws DBUnexpectedError Thrown if the database returns an error
64 function fetchObject( $res );
66 /**
67 * Fetch the next row from the given result object, in associative array
68 * form. Fields are retrieved with $row['fieldname'].
69 * If no more rows are available, false is returned.
71 * @param $res ResultWrapper result object as returned from DatabaseBase::query(), etc.
72 * @return array|bool
73 * @throws DBUnexpectedError Thrown if the database returns an error
75 function fetchRow( $res );
77 /**
78 * Get the number of rows in a result object
80 * @param $res Mixed: A SQL result
81 * @return int
83 function numRows( $res );
85 /**
86 * Get the number of fields in a result object
87 * @see http://www.php.net/mysql_num_fields
89 * @param $res Mixed: A SQL result
90 * @return int
92 function numFields( $res );
94 /**
95 * Get a field name in a result object
96 * @see http://www.php.net/mysql_field_name
98 * @param $res Mixed: A SQL result
99 * @param $n Integer
100 * @return string
102 function fieldName( $res, $n );
105 * Get the inserted value of an auto-increment row
107 * The value inserted should be fetched from nextSequenceValue()
109 * Example:
110 * $id = $dbw->nextSequenceValue( 'page_page_id_seq' );
111 * $dbw->insert( 'page', array( 'page_id' => $id ) );
112 * $id = $dbw->insertId();
114 * @return int
116 function insertId();
119 * Change the position of the cursor in a result object
120 * @see http://www.php.net/mysql_data_seek
122 * @param $res Mixed: A SQL result
123 * @param $row Mixed: Either MySQL row or ResultWrapper
125 function dataSeek( $res, $row );
128 * Get the last error number
129 * @see http://www.php.net/mysql_errno
131 * @return int
133 function lastErrno();
136 * Get a description of the last error
137 * @see http://www.php.net/mysql_error
139 * @return string
141 function lastError();
144 * mysql_fetch_field() wrapper
145 * Returns false if the field doesn't exist
147 * @param string $table table name
148 * @param string $field field name
150 * @return Field
152 function fieldInfo( $table, $field );
155 * Get information about an index into an object
156 * @param string $table Table name
157 * @param string $index Index name
158 * @param string $fname Calling function name
159 * @return Mixed: Database-specific index description class or false if the index does not exist
161 function indexInfo( $table, $index, $fname = __METHOD__ );
164 * Get the number of rows affected by the last write query
165 * @see http://www.php.net/mysql_affected_rows
167 * @return int
169 function affectedRows();
172 * Wrapper for addslashes()
174 * @param string $s to be slashed.
175 * @return string: slashed string.
177 function strencode( $s );
180 * Returns a wikitext link to the DB's website, e.g.,
181 * return "[http://www.mysql.com/ MySQL]";
182 * Should at least contain plain text, if for some reason
183 * your database has no website.
185 * @return string: wikitext of a link to the server software's web site
187 function getSoftwareLink();
190 * A string describing the current software version, like from
191 * mysql_get_server_info().
193 * @return string: Version information from the database server.
195 function getServerVersion();
198 * A string describing the current software version, and possibly
199 * other details in a user-friendly way. Will be listed on Special:Version, etc.
200 * Use getServerVersion() to get machine-friendly information.
202 * @return string: Version information from the database server
204 function getServerInfo();
208 * Interface for classes that implement or wrap DatabaseBase
209 * @ingroup Database
211 interface IDatabase {}
214 * Database abstraction object
215 * @ingroup Database
217 abstract class DatabaseBase implements IDatabase, DatabaseType {
218 /** Number of times to re-try an operation in case of deadlock */
219 const DEADLOCK_TRIES = 4;
220 /** Minimum time to wait before retry, in microseconds */
221 const DEADLOCK_DELAY_MIN = 500000;
222 /** Maximum time to wait before retry */
223 const DEADLOCK_DELAY_MAX = 1500000;
225 # ------------------------------------------------------------------------------
226 # Variables
227 # ------------------------------------------------------------------------------
229 protected $mLastQuery = '';
230 protected $mDoneWrites = false;
231 protected $mPHPError = false;
233 protected $mServer, $mUser, $mPassword, $mDBname;
235 protected $mConn = null;
236 protected $mOpened = false;
238 /** @var callable[] */
239 protected $mTrxIdleCallbacks = array();
240 /** @var callable[] */
241 protected $mTrxPreCommitCallbacks = array();
243 protected $mTablePrefix;
244 protected $mFlags;
245 protected $mForeign;
246 protected $mErrorCount = 0;
247 protected $mLBInfo = array();
248 protected $mFakeSlaveLag = null, $mFakeMaster = false;
249 protected $mDefaultBigSelects = null;
250 protected $mSchemaVars = false;
252 protected $preparedArgs;
254 protected $htmlErrors;
256 protected $delimiter = ';';
259 * Either 1 if a transaction is active or 0 otherwise.
260 * The other Trx fields may not be meaningfull if this is 0.
262 * @var int
264 protected $mTrxLevel = 0;
267 * Remembers the function name given for starting the most recent transaction via begin().
268 * Used to provide additional context for error reporting.
270 * @var String
271 * @see DatabaseBase::mTrxLevel
273 private $mTrxFname = null;
276 * Record if possible write queries were done in the last transaction started
278 * @var Bool
279 * @see DatabaseBase::mTrxLevel
281 private $mTrxDoneWrites = false;
284 * Record if the current transaction was started implicitly due to DBO_TRX being set.
286 * @var Bool
287 * @see DatabaseBase::mTrxLevel
289 private $mTrxAutomatic = false;
292 * Array of levels of atomicity within transactions
294 * @var SplStack
296 private $mTrxAtomicLevels;
299 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
301 * @var Bool
303 private $mTrxAutomaticAtomic = false;
306 * @since 1.21
307 * @var file handle for upgrade
309 protected $fileHandle = null;
312 * @since 1.22
313 * @var Process cache of VIEWs names in the database
315 protected $allViews = null;
317 # ------------------------------------------------------------------------------
318 # Accessors
319 # ------------------------------------------------------------------------------
320 # These optionally set a variable and return the previous state
323 * A string describing the current software version, and possibly
324 * other details in a user-friendly way. Will be listed on Special:Version, etc.
325 * Use getServerVersion() to get machine-friendly information.
327 * @return string: Version information from the database server
329 public function getServerInfo() {
330 return $this->getServerVersion();
334 * @return string: command delimiter used by this database engine
336 public function getDelimiter() {
337 return $this->delimiter;
341 * Boolean, controls output of large amounts of debug information.
342 * @param $debug bool|null
343 * - true to enable debugging
344 * - false to disable debugging
345 * - omitted or null to do nothing
347 * @return bool|null previous value of the flag
349 public function debug( $debug = null ) {
350 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
354 * Turns buffering of SQL result sets on (true) or off (false). Default is
355 * "on".
357 * Unbuffered queries are very troublesome in MySQL:
359 * - If another query is executed while the first query is being read
360 * out, the first query is killed. This means you can't call normal
361 * MediaWiki functions while you are reading an unbuffered query result
362 * from a normal wfGetDB() connection.
364 * - Unbuffered queries cause the MySQL server to use large amounts of
365 * memory and to hold broad locks which block other queries.
367 * If you want to limit client-side memory, it's almost always better to
368 * split up queries into batches using a LIMIT clause than to switch off
369 * buffering.
371 * @param $buffer null|bool
373 * @return null|bool The previous value of the flag
375 public function bufferResults( $buffer = null ) {
376 if ( is_null( $buffer ) ) {
377 return !(bool)( $this->mFlags & DBO_NOBUFFER );
378 } else {
379 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
384 * Turns on (false) or off (true) the automatic generation and sending
385 * of a "we're sorry, but there has been a database error" page on
386 * database errors. Default is on (false). When turned off, the
387 * code should use lastErrno() and lastError() to handle the
388 * situation as appropriate.
390 * Do not use this function outside of the Database classes.
392 * @param $ignoreErrors bool|null
394 * @return bool The previous value of the flag.
396 public function ignoreErrors( $ignoreErrors = null ) {
397 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
401 * Gets the current transaction level.
403 * Historically, transactions were allowed to be "nested". This is no
404 * longer supported, so this function really only returns a boolean.
406 * @return int The previous value
408 public function trxLevel() {
409 return $this->mTrxLevel;
413 * Get/set the number of errors logged. Only useful when errors are ignored
414 * @param int $count The count to set, or omitted to leave it unchanged.
415 * @return int The error count
417 public function errorCount( $count = null ) {
418 return wfSetVar( $this->mErrorCount, $count );
422 * Get/set the table prefix.
423 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
424 * @return string The previous table prefix.
426 public function tablePrefix( $prefix = null ) {
427 return wfSetVar( $this->mTablePrefix, $prefix );
431 * Set the filehandle to copy write statements to.
433 * @param $fh filehandle
435 public function setFileHandle( $fh ) {
436 $this->fileHandle = $fh;
440 * Get properties passed down from the server info array of the load
441 * balancer.
443 * @param string $name The entry of the info array to get, or null to get the
444 * whole array
446 * @return LoadBalancer|null
448 public function getLBInfo( $name = null ) {
449 if ( is_null( $name ) ) {
450 return $this->mLBInfo;
451 } else {
452 if ( array_key_exists( $name, $this->mLBInfo ) ) {
453 return $this->mLBInfo[$name];
454 } else {
455 return null;
461 * Set the LB info array, or a member of it. If called with one parameter,
462 * the LB info array is set to that parameter. If it is called with two
463 * parameters, the member with the given name is set to the given value.
465 * @param $name
466 * @param $value
468 public function setLBInfo( $name, $value = null ) {
469 if ( is_null( $value ) ) {
470 $this->mLBInfo = $name;
471 } else {
472 $this->mLBInfo[$name] = $value;
477 * Set lag time in seconds for a fake slave
479 * @param $lag int
481 public function setFakeSlaveLag( $lag ) {
482 $this->mFakeSlaveLag = $lag;
486 * Make this connection a fake master
488 * @param $enabled bool
490 public function setFakeMaster( $enabled = true ) {
491 $this->mFakeMaster = $enabled;
495 * Returns true if this database supports (and uses) cascading deletes
497 * @return bool
499 public function cascadingDeletes() {
500 return false;
504 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
506 * @return bool
508 public function cleanupTriggers() {
509 return false;
513 * Returns true if this database is strict about what can be put into an IP field.
514 * Specifically, it uses a NULL value instead of an empty string.
516 * @return bool
518 public function strictIPs() {
519 return false;
523 * Returns true if this database uses timestamps rather than integers
525 * @return bool
527 public function realTimestamps() {
528 return false;
532 * Returns true if this database does an implicit sort when doing GROUP BY
534 * @return bool
536 public function implicitGroupby() {
537 return true;
541 * Returns true if this database does an implicit order by when the column has an index
542 * For example: SELECT page_title FROM page LIMIT 1
544 * @return bool
546 public function implicitOrderby() {
547 return true;
551 * Returns true if this database can do a native search on IP columns
552 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
554 * @return bool
556 public function searchableIPs() {
557 return false;
561 * Returns true if this database can use functional indexes
563 * @return bool
565 public function functionalIndexes() {
566 return false;
570 * Return the last query that went through DatabaseBase::query()
571 * @return String
573 public function lastQuery() {
574 return $this->mLastQuery;
578 * Returns true if the connection may have been used for write queries.
579 * Should return true if unsure.
581 * @return bool
583 public function doneWrites() {
584 return $this->mDoneWrites;
588 * Returns true if there is a transaction open with possible write
589 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
591 * @return bool
593 public function writesOrCallbacksPending() {
594 return $this->mTrxLevel && (
595 $this->mTrxDoneWrites || $this->mTrxIdleCallbacks || $this->mTrxPreCommitCallbacks
600 * Is a connection to the database open?
601 * @return Boolean
603 public function isOpen() {
604 return $this->mOpened;
608 * Set a flag for this connection
610 * @param $flag Integer: DBO_* constants from Defines.php:
611 * - DBO_DEBUG: output some debug info (same as debug())
612 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
613 * - DBO_TRX: automatically start transactions
614 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
615 * and removes it in command line mode
616 * - DBO_PERSISTENT: use persistant database connection
618 public function setFlag( $flag ) {
619 global $wgDebugDBTransactions;
620 $this->mFlags |= $flag;
621 if ( ( $flag & DBO_TRX ) & $wgDebugDBTransactions ) {
622 wfDebug( "Implicit transactions are now disabled.\n" );
627 * Clear a flag for this connection
629 * @param $flag: same as setFlag()'s $flag param
631 public function clearFlag( $flag ) {
632 global $wgDebugDBTransactions;
633 $this->mFlags &= ~$flag;
634 if ( ( $flag & DBO_TRX ) && $wgDebugDBTransactions ) {
635 wfDebug( "Implicit transactions are now disabled.\n" );
640 * Returns a boolean whether the flag $flag is set for this connection
642 * @param $flag: same as setFlag()'s $flag param
643 * @return Boolean
645 public function getFlag( $flag ) {
646 return !!( $this->mFlags & $flag );
650 * General read-only accessor
652 * @param $name string
654 * @return string
656 public function getProperty( $name ) {
657 return $this->$name;
661 * @return string
663 public function getWikiID() {
664 if ( $this->mTablePrefix ) {
665 return "{$this->mDBname}-{$this->mTablePrefix}";
666 } else {
667 return $this->mDBname;
672 * Return a path to the DBMS-specific schema file, otherwise default to tables.sql
674 * @return string
676 public function getSchemaPath() {
677 global $IP;
678 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
679 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
680 } else {
681 return "$IP/maintenance/tables.sql";
685 # ------------------------------------------------------------------------------
686 # Other functions
687 # ------------------------------------------------------------------------------
690 * Constructor.
692 * FIXME: It is possible to construct a Database object with no associated
693 * connection object, by specifying no parameters to __construct(). This
694 * feature is deprecated and should be removed.
696 * DatabaseBase subclasses should not be constructed directly in external
697 * code. DatabaseBase::factory() should be used instead.
699 * @param array Parameters passed from DatabaseBase::factory()
701 function __construct( $params = null ) {
702 global $wgDBprefix, $wgCommandLineMode, $wgDebugDBTransactions;
704 $this->mTrxAtomicLevels = new SplStack;
706 if ( is_array( $params ) ) { // MW 1.22
707 $server = $params['host'];
708 $user = $params['user'];
709 $password = $params['password'];
710 $dbName = $params['dbname'];
711 $flags = $params['flags'];
712 $tablePrefix = $params['tablePrefix'];
713 $foreign = $params['foreign'];
714 } else { // legacy calling pattern
715 wfDeprecated( __METHOD__ . " method called without parameter array.", "1.23" );
716 $args = func_get_args();
717 $server = isset( $args[0] ) ? $args[0] : false;
718 $user = isset( $args[1] ) ? $args[1] : false;
719 $password = isset( $args[2] ) ? $args[2] : false;
720 $dbName = isset( $args[3] ) ? $args[3] : false;
721 $flags = isset( $args[4] ) ? $args[4] : 0;
722 $tablePrefix = isset( $args[5] ) ? $args[5] : 'get from global';
723 $foreign = isset( $args[6] ) ? $args[6] : false;
726 $this->mFlags = $flags;
727 if ( $this->mFlags & DBO_DEFAULT ) {
728 if ( $wgCommandLineMode ) {
729 $this->mFlags &= ~DBO_TRX;
730 if ( $wgDebugDBTransactions ) {
731 wfDebug( "Implicit transaction open disabled.\n" );
733 } else {
734 $this->mFlags |= DBO_TRX;
735 if ( $wgDebugDBTransactions ) {
736 wfDebug( "Implicit transaction open enabled.\n" );
741 /** Get the default table prefix*/
742 if ( $tablePrefix == 'get from global' ) {
743 $this->mTablePrefix = $wgDBprefix;
744 } else {
745 $this->mTablePrefix = $tablePrefix;
748 $this->mForeign = $foreign;
750 if ( $user ) {
751 $this->open( $server, $user, $password, $dbName );
756 * Called by serialize. Throw an exception when DB connection is serialized.
757 * This causes problems on some database engines because the connection is
758 * not restored on unserialize.
760 public function __sleep() {
761 throw new MWException( 'Database serialization may cause problems, since the connection is not restored on wakeup.' );
765 * Given a DB type, construct the name of the appropriate child class of
766 * DatabaseBase. This is designed to replace all of the manual stuff like:
767 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
768 * as well as validate against the canonical list of DB types we have
770 * This factory function is mostly useful for when you need to connect to a
771 * database other than the MediaWiki default (such as for external auth,
772 * an extension, et cetera). Do not use this to connect to the MediaWiki
773 * database. Example uses in core:
774 * @see LoadBalancer::reallyOpenConnection()
775 * @see ForeignDBRepo::getMasterDB()
776 * @see WebInstaller_DBConnect::execute()
778 * @since 1.18
780 * @param string $dbType A possible DB type
781 * @param array $p An array of options to pass to the constructor.
782 * Valid options are: host, user, password, dbname, flags, tablePrefix, driver
783 * @return DatabaseBase subclass or null
785 final public static function factory( $dbType, $p = array() ) {
786 $canonicalDBTypes = array(
787 'mysql' => array( 'mysqli', 'mysql' ),
788 'postgres' => array(),
789 'sqlite' => array(),
790 'oracle' => array(),
791 'mssql' => array(),
794 $driver = false;
795 $dbType = strtolower( $dbType );
796 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
797 $possibleDrivers = $canonicalDBTypes[$dbType];
798 if ( !empty( $p['driver'] ) ) {
799 if ( in_array( $p['driver'], $possibleDrivers ) ) {
800 $driver = $p['driver'];
801 } else {
802 throw new MWException( __METHOD__ .
803 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
805 } else {
806 foreach ( $possibleDrivers as $posDriver ) {
807 if ( extension_loaded( $posDriver ) ) {
808 $driver = $posDriver;
809 break;
813 } else {
814 $driver = $dbType;
816 if ( $driver === false ) {
817 throw new MWException( __METHOD__ .
818 " no viable database extension found for type '$dbType'" );
821 $class = 'Database' . ucfirst( $driver );
822 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
823 $params = array(
824 'host' => isset( $p['host'] ) ? $p['host'] : false,
825 'user' => isset( $p['user'] ) ? $p['user'] : false,
826 'password' => isset( $p['password'] ) ? $p['password'] : false,
827 'dbname' => isset( $p['dbname'] ) ? $p['dbname'] : false,
828 'flags' => isset( $p['flags'] ) ? $p['flags'] : 0,
829 'tablePrefix' => isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : 'get from global',
830 'foreign' => isset( $p['foreign'] ) ? $p['foreign'] : false
832 return new $class( $params );
833 } else {
834 return null;
838 protected function installErrorHandler() {
839 $this->mPHPError = false;
840 $this->htmlErrors = ini_set( 'html_errors', '0' );
841 set_error_handler( array( $this, 'connectionErrorHandler' ) );
845 * @return bool|string
847 protected function restoreErrorHandler() {
848 restore_error_handler();
849 if ( $this->htmlErrors !== false ) {
850 ini_set( 'html_errors', $this->htmlErrors );
852 if ( $this->mPHPError ) {
853 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
854 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
855 return $error;
856 } else {
857 return false;
862 * @param $errno
863 * @param $errstr
864 * @access private
866 public function connectionErrorHandler( $errno, $errstr ) {
867 $this->mPHPError = $errstr;
871 * Closes a database connection.
872 * if it is open : commits any open transactions
874 * @throws MWException
875 * @return Bool operation success. true if already closed.
877 public function close() {
878 if ( count( $this->mTrxIdleCallbacks ) ) { // sanity
879 throw new MWException( "Transaction idle callbacks still pending." );
881 $this->mOpened = false;
882 if ( $this->mConn ) {
883 if ( $this->trxLevel() ) {
884 if ( !$this->mTrxAutomatic ) {
885 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
886 " performing implicit commit before closing connection!" );
889 $this->commit( __METHOD__, 'flush' );
892 $ret = $this->closeConnection();
893 $this->mConn = false;
894 return $ret;
895 } else {
896 return true;
901 * Closes underlying database connection
902 * @since 1.20
903 * @return bool: Whether connection was closed successfully
905 abstract protected function closeConnection();
908 * @param string $error fallback error message, used if none is given by DB
909 * @throws DBConnectionError
911 function reportConnectionError( $error = 'Unknown error' ) {
912 $myError = $this->lastError();
913 if ( $myError ) {
914 $error = $myError;
917 # New method
918 throw new DBConnectionError( $this, $error );
922 * The DBMS-dependent part of query()
924 * @param $sql String: SQL query.
925 * @return ResultWrapper Result object to feed to fetchObject, fetchRow, ...; or false on failure
927 abstract protected function doQuery( $sql );
930 * Determine whether a query writes to the DB.
931 * Should return true if unsure.
933 * @param $sql string
935 * @return bool
937 public function isWriteQuery( $sql ) {
938 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
942 * Run an SQL query and return the result. Normally throws a DBQueryError
943 * on failure. If errors are ignored, returns false instead.
945 * In new code, the query wrappers select(), insert(), update(), delete(),
946 * etc. should be used where possible, since they give much better DBMS
947 * independence and automatically quote or validate user input in a variety
948 * of contexts. This function is generally only useful for queries which are
949 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
950 * as CREATE TABLE.
952 * However, the query wrappers themselves should call this function.
954 * @param $sql String: SQL query
955 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
956 * comment (you can use __METHOD__ or add some extra info)
957 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
958 * maybe best to catch the exception instead?
959 * @throws MWException
960 * @return boolean|ResultWrapper. true for a successful write query, ResultWrapper object
961 * for a successful read query, or false on failure if $tempIgnore set
963 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
964 global $wgUser, $wgDebugDBTransactions;
966 $this->mLastQuery = $sql;
967 if ( !$this->mDoneWrites && $this->isWriteQuery( $sql ) ) {
968 # Set a flag indicating that writes have been done
969 wfDebug( __METHOD__ . ": Writes done: $sql\n" );
970 $this->mDoneWrites = true;
973 # Add a comment for easy SHOW PROCESSLIST interpretation
974 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
975 $userName = $wgUser->getName();
976 if ( mb_strlen( $userName ) > 15 ) {
977 $userName = mb_substr( $userName, 0, 15 ) . '...';
979 $userName = str_replace( '/', '', $userName );
980 } else {
981 $userName = '';
984 // Add trace comment to the begin of the sql string, right after the operator.
985 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
986 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
988 # If DBO_TRX is set, start a transaction
989 if ( ( $this->mFlags & DBO_TRX ) && !$this->mTrxLevel &&
990 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' )
992 # Avoid establishing transactions for SHOW and SET statements too -
993 # that would delay transaction initializations to once connection
994 # is really used by application
995 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
996 if ( strpos( $sqlstart, "SHOW " ) !== 0 && strpos( $sqlstart, "SET " ) !== 0 ) {
997 if ( $wgDebugDBTransactions ) {
998 wfDebug( "Implicit transaction start.\n" );
1000 $this->begin( __METHOD__ . " ($fname)" );
1001 $this->mTrxAutomatic = true;
1005 # Keep track of whether the transaction has write queries pending
1006 if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $this->isWriteQuery( $sql ) ) {
1007 $this->mTrxDoneWrites = true;
1008 Profiler::instance()->transactionWritingIn( $this->mServer, $this->mDBname );
1011 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1012 if ( !Profiler::instance()->isStub() ) {
1013 # generalizeSQL will probably cut down the query to reasonable
1014 # logging size most of the time. The substr is really just a sanity check.
1015 if ( $isMaster ) {
1016 $queryProf = 'query-m: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
1017 $totalProf = 'DatabaseBase::query-master';
1018 } else {
1019 $queryProf = 'query: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
1020 $totalProf = 'DatabaseBase::query';
1022 wfProfileIn( $totalProf );
1023 wfProfileIn( $queryProf );
1026 if ( $this->debug() ) {
1027 static $cnt = 0;
1029 $cnt++;
1030 $sqlx = substr( $commentedSql, 0, 500 );
1031 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1033 $master = $isMaster ? 'master' : 'slave';
1034 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1037 $queryId = MWDebug::query( $sql, $fname, $isMaster );
1039 # Do the query and handle errors
1040 $ret = $this->doQuery( $commentedSql );
1042 MWDebug::queryTime( $queryId );
1044 # Try reconnecting if the connection was lost
1045 if ( false === $ret && $this->wasErrorReissuable() ) {
1046 # Transaction is gone, like it or not
1047 $hadTrx = $this->mTrxLevel; // possible lost transaction
1048 wfDebug( "Connection lost, reconnecting...\n" );
1049 $this->mTrxLevel = 0;
1050 wfDebug( "Connection lost, reconnecting...\n" );
1052 if ( $this->ping() ) {
1053 wfDebug( "Reconnected\n" );
1054 $sqlx = substr( $commentedSql, 0, 500 );
1055 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1056 global $wgRequestTime;
1057 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
1058 if ( $elapsed < 300 ) {
1059 # Not a database error to lose a transaction after a minute or two
1060 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
1062 if ( !$hadTrx ) {
1063 # Should be safe to silently retry
1064 $ret = $this->doQuery( $commentedSql );
1066 } else {
1067 wfDebug( "Failed\n" );
1071 if ( false === $ret ) {
1072 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1075 if ( !Profiler::instance()->isStub() ) {
1076 wfProfileOut( $queryProf );
1077 wfProfileOut( $totalProf );
1080 return $this->resultObject( $ret );
1084 * Report a query error. Log the error, and if neither the object ignore
1085 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1087 * @param $error String
1088 * @param $errno Integer
1089 * @param $sql String
1090 * @param $fname String
1091 * @param $tempIgnore Boolean
1092 * @throws DBQueryError
1094 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1095 # Ignore errors during error handling to avoid infinite recursion
1096 $ignore = $this->ignoreErrors( true );
1097 ++$this->mErrorCount;
1099 if ( $ignore || $tempIgnore ) {
1100 wfDebug( "SQL ERROR (ignored): $error\n" );
1101 $this->ignoreErrors( $ignore );
1102 } else {
1103 $sql1line = str_replace( "\n", "\\n", $sql );
1104 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
1105 wfDebug( "SQL ERROR: " . $error . "\n" );
1106 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1111 * Intended to be compatible with the PEAR::DB wrapper functions.
1112 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1114 * ? = scalar value, quoted as necessary
1115 * ! = raw SQL bit (a function for instance)
1116 * & = filename; reads the file and inserts as a blob
1117 * (we don't use this though...)
1119 * @param $sql string
1120 * @param $func string
1122 * @return array
1124 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1125 /* MySQL doesn't support prepared statements (yet), so just
1126 pack up the query for reference. We'll manually replace
1127 the bits later. */
1128 return array( 'query' => $sql, 'func' => $func );
1132 * Free a prepared query, generated by prepare().
1133 * @param $prepared
1135 protected function freePrepared( $prepared ) {
1136 /* No-op by default */
1140 * Execute a prepared query with the various arguments
1141 * @param string $prepared the prepared sql
1142 * @param $args Mixed: Either an array here, or put scalars as varargs
1144 * @return ResultWrapper
1146 public function execute( $prepared, $args = null ) {
1147 if ( !is_array( $args ) ) {
1148 # Pull the var args
1149 $args = func_get_args();
1150 array_shift( $args );
1153 $sql = $this->fillPrepared( $prepared['query'], $args );
1155 return $this->query( $sql, $prepared['func'] );
1159 * For faking prepared SQL statements on DBs that don't support it directly.
1161 * @param string $preparedQuery a 'preparable' SQL statement
1162 * @param array $args of arguments to fill it with
1163 * @return string executable SQL
1165 public function fillPrepared( $preparedQuery, $args ) {
1166 reset( $args );
1167 $this->preparedArgs =& $args;
1169 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1170 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1174 * preg_callback func for fillPrepared()
1175 * The arguments should be in $this->preparedArgs and must not be touched
1176 * while we're doing this.
1178 * @param $matches Array
1179 * @throws DBUnexpectedError
1180 * @return String
1182 protected function fillPreparedArg( $matches ) {
1183 switch ( $matches[1] ) {
1184 case '\\?':
1185 return '?';
1186 case '\\!':
1187 return '!';
1188 case '\\&':
1189 return '&';
1192 list( /* $n */, $arg ) = each( $this->preparedArgs );
1194 switch ( $matches[1] ) {
1195 case '?':
1196 return $this->addQuotes( $arg );
1197 case '!':
1198 return $arg;
1199 case '&':
1200 # return $this->addQuotes( file_get_contents( $arg ) );
1201 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
1202 default:
1203 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
1208 * Free a result object returned by query() or select(). It's usually not
1209 * necessary to call this, just use unset() or let the variable holding
1210 * the result object go out of scope.
1212 * @param $res Mixed: A SQL result
1214 public function freeResult( $res ) {
1218 * A SELECT wrapper which returns a single field from a single result row.
1220 * Usually throws a DBQueryError on failure. If errors are explicitly
1221 * ignored, returns false on failure.
1223 * If no result rows are returned from the query, false is returned.
1225 * @param string|array $table Table name. See DatabaseBase::select() for details.
1226 * @param string $var The field name to select. This must be a valid SQL
1227 * fragment: do not use unvalidated user input.
1228 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1229 * @param string $fname The function name of the caller.
1230 * @param string|array $options The query options. See DatabaseBase::select() for details.
1232 * @return bool|mixed The value from the field, or false on failure.
1234 public function selectField( $table, $var, $cond = '', $fname = __METHOD__,
1235 $options = array()
1237 if ( !is_array( $options ) ) {
1238 $options = array( $options );
1241 $options['LIMIT'] = 1;
1243 $res = $this->select( $table, $var, $cond, $fname, $options );
1245 if ( $res === false || !$this->numRows( $res ) ) {
1246 return false;
1249 $row = $this->fetchRow( $res );
1251 if ( $row !== false ) {
1252 return reset( $row );
1253 } else {
1254 return false;
1259 * Returns an optional USE INDEX clause to go after the table, and a
1260 * string to go at the end of the query.
1262 * @param array $options associative array of options to be turned into
1263 * an SQL query, valid keys are listed in the function.
1264 * @return Array
1265 * @see DatabaseBase::select()
1267 public function makeSelectOptions( $options ) {
1268 $preLimitTail = $postLimitTail = '';
1269 $startOpts = '';
1271 $noKeyOptions = array();
1273 foreach ( $options as $key => $option ) {
1274 if ( is_numeric( $key ) ) {
1275 $noKeyOptions[$option] = true;
1279 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1281 $preLimitTail .= $this->makeOrderBy( $options );
1283 // if (isset($options['LIMIT'])) {
1284 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1285 // isset($options['OFFSET']) ? $options['OFFSET']
1286 // : false);
1287 // }
1289 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1290 $postLimitTail .= ' FOR UPDATE';
1293 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1294 $postLimitTail .= ' LOCK IN SHARE MODE';
1297 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1298 $startOpts .= 'DISTINCT';
1301 # Various MySQL extensions
1302 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1303 $startOpts .= ' /*! STRAIGHT_JOIN */';
1306 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1307 $startOpts .= ' HIGH_PRIORITY';
1310 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1311 $startOpts .= ' SQL_BIG_RESULT';
1314 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1315 $startOpts .= ' SQL_BUFFER_RESULT';
1318 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1319 $startOpts .= ' SQL_SMALL_RESULT';
1322 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1323 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1326 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1327 $startOpts .= ' SQL_CACHE';
1330 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1331 $startOpts .= ' SQL_NO_CACHE';
1334 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1335 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1336 } else {
1337 $useIndex = '';
1340 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1344 * Returns an optional GROUP BY with an optional HAVING
1346 * @param array $options associative array of options
1347 * @return string
1348 * @see DatabaseBase::select()
1349 * @since 1.21
1351 public function makeGroupByWithHaving( $options ) {
1352 $sql = '';
1353 if ( isset( $options['GROUP BY'] ) ) {
1354 $gb = is_array( $options['GROUP BY'] )
1355 ? implode( ',', $options['GROUP BY'] )
1356 : $options['GROUP BY'];
1357 $sql .= ' GROUP BY ' . $gb;
1359 if ( isset( $options['HAVING'] ) ) {
1360 $having = is_array( $options['HAVING'] )
1361 ? $this->makeList( $options['HAVING'], LIST_AND )
1362 : $options['HAVING'];
1363 $sql .= ' HAVING ' . $having;
1365 return $sql;
1369 * Returns an optional ORDER BY
1371 * @param array $options associative array of options
1372 * @return string
1373 * @see DatabaseBase::select()
1374 * @since 1.21
1376 public function makeOrderBy( $options ) {
1377 if ( isset( $options['ORDER BY'] ) ) {
1378 $ob = is_array( $options['ORDER BY'] )
1379 ? implode( ',', $options['ORDER BY'] )
1380 : $options['ORDER BY'];
1381 return ' ORDER BY ' . $ob;
1383 return '';
1387 * Execute a SELECT query constructed using the various parameters provided.
1388 * See below for full details of the parameters.
1390 * @param string|array $table Table name
1391 * @param string|array $vars Field names
1392 * @param string|array $conds Conditions
1393 * @param string $fname Caller function name
1394 * @param array $options Query options
1395 * @param $join_conds Array Join conditions
1397 * @param $table string|array
1399 * May be either an array of table names, or a single string holding a table
1400 * name. If an array is given, table aliases can be specified, for example:
1402 * array( 'a' => 'user' )
1404 * This includes the user table in the query, with the alias "a" available
1405 * for use in field names (e.g. a.user_name).
1407 * All of the table names given here are automatically run through
1408 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1409 * added, and various other table name mappings to be performed.
1412 * @param $vars string|array
1414 * May be either a field name or an array of field names. The field names
1415 * can be complete fragments of SQL, for direct inclusion into the SELECT
1416 * query. If an array is given, field aliases can be specified, for example:
1418 * array( 'maxrev' => 'MAX(rev_id)' )
1420 * This includes an expression with the alias "maxrev" in the query.
1422 * If an expression is given, care must be taken to ensure that it is
1423 * DBMS-independent.
1426 * @param $conds string|array
1428 * May be either a string containing a single condition, or an array of
1429 * conditions. If an array is given, the conditions constructed from each
1430 * element are combined with AND.
1432 * Array elements may take one of two forms:
1434 * - Elements with a numeric key are interpreted as raw SQL fragments.
1435 * - Elements with a string key are interpreted as equality conditions,
1436 * where the key is the field name.
1437 * - If the value of such an array element is a scalar (such as a
1438 * string), it will be treated as data and thus quoted appropriately.
1439 * If it is null, an IS NULL clause will be added.
1440 * - If the value is an array, an IN(...) clause will be constructed,
1441 * such that the field name may match any of the elements in the
1442 * array. The elements of the array will be quoted.
1444 * Note that expressions are often DBMS-dependent in their syntax.
1445 * DBMS-independent wrappers are provided for constructing several types of
1446 * expression commonly used in condition queries. See:
1447 * - DatabaseBase::buildLike()
1448 * - DatabaseBase::conditional()
1451 * @param $options string|array
1453 * Optional: Array of query options. Boolean options are specified by
1454 * including them in the array as a string value with a numeric key, for
1455 * example:
1457 * array( 'FOR UPDATE' )
1459 * The supported options are:
1461 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1462 * with LIMIT can theoretically be used for paging through a result set,
1463 * but this is discouraged in MediaWiki for performance reasons.
1465 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1466 * and then the first rows are taken until the limit is reached. LIMIT
1467 * is applied to a result set after OFFSET.
1469 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1470 * changed until the next COMMIT.
1472 * - DISTINCT: Boolean: return only unique result rows.
1474 * - GROUP BY: May be either an SQL fragment string naming a field or
1475 * expression to group by, or an array of such SQL fragments.
1477 * - HAVING: May be either an string containing a HAVING clause or an array of
1478 * conditions building the HAVING clause. If an array is given, the conditions
1479 * constructed from each element are combined with AND.
1481 * - ORDER BY: May be either an SQL fragment giving a field name or
1482 * expression to order by, or an array of such SQL fragments.
1484 * - USE INDEX: This may be either a string giving the index name to use
1485 * for the query, or an array. If it is an associative array, each key
1486 * gives the table name (or alias), each value gives the index name to
1487 * use for that table. All strings are SQL fragments and so should be
1488 * validated by the caller.
1490 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1491 * instead of SELECT.
1493 * And also the following boolean MySQL extensions, see the MySQL manual
1494 * for documentation:
1496 * - LOCK IN SHARE MODE
1497 * - STRAIGHT_JOIN
1498 * - HIGH_PRIORITY
1499 * - SQL_BIG_RESULT
1500 * - SQL_BUFFER_RESULT
1501 * - SQL_SMALL_RESULT
1502 * - SQL_CALC_FOUND_ROWS
1503 * - SQL_CACHE
1504 * - SQL_NO_CACHE
1507 * @param $join_conds string|array
1509 * Optional associative array of table-specific join conditions. In the
1510 * most common case, this is unnecessary, since the join condition can be
1511 * in $conds. However, it is useful for doing a LEFT JOIN.
1513 * The key of the array contains the table name or alias. The value is an
1514 * array with two elements, numbered 0 and 1. The first gives the type of
1515 * join, the second is an SQL fragment giving the join condition for that
1516 * table. For example:
1518 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1520 * @return ResultWrapper. If the query returned no rows, a ResultWrapper
1521 * with no rows in it will be returned. If there was a query error, a
1522 * DBQueryError exception will be thrown, except if the "ignore errors"
1523 * option was set, in which case false will be returned.
1525 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1526 $options = array(), $join_conds = array() ) {
1527 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1529 return $this->query( $sql, $fname );
1533 * The equivalent of DatabaseBase::select() except that the constructed SQL
1534 * is returned, instead of being immediately executed. This can be useful for
1535 * doing UNION queries, where the SQL text of each query is needed. In general,
1536 * however, callers outside of Database classes should just use select().
1538 * @param string|array $table Table name
1539 * @param string|array $vars Field names
1540 * @param string|array $conds Conditions
1541 * @param string $fname Caller function name
1542 * @param string|array $options Query options
1543 * @param $join_conds string|array Join conditions
1545 * @return string SQL query string.
1546 * @see DatabaseBase::select()
1548 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1549 $options = array(), $join_conds = array() )
1551 if ( is_array( $vars ) ) {
1552 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1555 $options = (array)$options;
1556 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1557 ? $options['USE INDEX']
1558 : array();
1560 if ( is_array( $table ) ) {
1561 $from = ' FROM ' .
1562 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1563 } elseif ( $table != '' ) {
1564 if ( $table[0] == ' ' ) {
1565 $from = ' FROM ' . $table;
1566 } else {
1567 $from = ' FROM ' .
1568 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1570 } else {
1571 $from = '';
1574 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1575 $this->makeSelectOptions( $options );
1577 if ( !empty( $conds ) ) {
1578 if ( is_array( $conds ) ) {
1579 $conds = $this->makeList( $conds, LIST_AND );
1581 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1582 } else {
1583 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1586 if ( isset( $options['LIMIT'] ) ) {
1587 $sql = $this->limitResult( $sql, $options['LIMIT'],
1588 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1590 $sql = "$sql $postLimitTail";
1592 if ( isset( $options['EXPLAIN'] ) ) {
1593 $sql = 'EXPLAIN ' . $sql;
1596 return $sql;
1600 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1601 * that a single row object is returned. If the query returns no rows,
1602 * false is returned.
1604 * @param string|array $table Table name
1605 * @param string|array $vars Field names
1606 * @param array $conds Conditions
1607 * @param string $fname Caller function name
1608 * @param string|array $options Query options
1609 * @param $join_conds array|string Join conditions
1611 * @return object|bool
1613 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1614 $options = array(), $join_conds = array() )
1616 $options = (array)$options;
1617 $options['LIMIT'] = 1;
1618 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1620 if ( $res === false ) {
1621 return false;
1624 if ( !$this->numRows( $res ) ) {
1625 return false;
1628 $obj = $this->fetchObject( $res );
1630 return $obj;
1634 * Estimate rows in dataset.
1636 * MySQL allows you to estimate the number of rows that would be returned
1637 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1638 * index cardinality statistics, and is notoriously inaccurate, especially
1639 * when large numbers of rows have recently been added or deleted.
1641 * For DBMSs that don't support fast result size estimation, this function
1642 * will actually perform the SELECT COUNT(*).
1644 * Takes the same arguments as DatabaseBase::select().
1646 * @param string $table table name
1647 * @param array|string $vars : unused
1648 * @param array|string $conds : filters on the table
1649 * @param string $fname function name for profiling
1650 * @param array $options options for select
1651 * @return Integer: row count
1653 public function estimateRowCount( $table, $vars = '*', $conds = '',
1654 $fname = __METHOD__, $options = array() )
1656 $rows = 0;
1657 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1659 if ( $res ) {
1660 $row = $this->fetchRow( $res );
1661 $rows = ( isset( $row['rowcount'] ) ) ? $row['rowcount'] : 0;
1664 return $rows;
1668 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1669 * It's only slightly flawed. Don't use for anything important.
1671 * @param string $sql A SQL Query
1673 * @return string
1675 static function generalizeSQL( $sql ) {
1676 # This does the same as the regexp below would do, but in such a way
1677 # as to avoid crashing php on some large strings.
1678 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1680 $sql = str_replace( "\\\\", '', $sql );
1681 $sql = str_replace( "\\'", '', $sql );
1682 $sql = str_replace( "\\\"", '', $sql );
1683 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1684 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1686 # All newlines, tabs, etc replaced by single space
1687 $sql = preg_replace( '/\s+/', ' ', $sql );
1689 # All numbers => N
1690 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1691 $sql = preg_replace( '/-?\d+/s', 'N', $sql );
1693 return $sql;
1697 * Determines whether a field exists in a table
1699 * @param string $table table name
1700 * @param string $field filed to check on that table
1701 * @param string $fname calling function name (optional)
1702 * @return Boolean: whether $table has filed $field
1704 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1705 $info = $this->fieldInfo( $table, $field );
1707 return (bool)$info;
1711 * Determines whether an index exists
1712 * Usually throws a DBQueryError on failure
1713 * If errors are explicitly ignored, returns NULL on failure
1715 * @param $table
1716 * @param $index
1717 * @param $fname string
1719 * @return bool|null
1721 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1722 if ( !$this->tableExists( $table ) ) {
1723 return null;
1726 $info = $this->indexInfo( $table, $index, $fname );
1727 if ( is_null( $info ) ) {
1728 return null;
1729 } else {
1730 return $info !== false;
1735 * Query whether a given table exists
1737 * @param $table string
1738 * @param $fname string
1740 * @return bool
1742 public function tableExists( $table, $fname = __METHOD__ ) {
1743 $table = $this->tableName( $table );
1744 $old = $this->ignoreErrors( true );
1745 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1746 $this->ignoreErrors( $old );
1748 return (bool)$res;
1752 * mysql_field_type() wrapper
1753 * @param $res
1754 * @param $index
1755 * @return string
1757 public function fieldType( $res, $index ) {
1758 if ( $res instanceof ResultWrapper ) {
1759 $res = $res->result;
1762 return mysql_field_type( $res, $index );
1766 * Determines if a given index is unique
1768 * @param $table string
1769 * @param $index string
1771 * @return bool
1773 public function indexUnique( $table, $index ) {
1774 $indexInfo = $this->indexInfo( $table, $index );
1776 if ( !$indexInfo ) {
1777 return null;
1780 return !$indexInfo[0]->Non_unique;
1784 * Helper for DatabaseBase::insert().
1786 * @param $options array
1787 * @return string
1789 protected function makeInsertOptions( $options ) {
1790 return implode( ' ', $options );
1794 * INSERT wrapper, inserts an array into a table.
1796 * $a may be either:
1798 * - A single associative array. The array keys are the field names, and
1799 * the values are the values to insert. The values are treated as data
1800 * and will be quoted appropriately. If NULL is inserted, this will be
1801 * converted to a database NULL.
1802 * - An array with numeric keys, holding a list of associative arrays.
1803 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1804 * each subarray must be identical to each other, and in the same order.
1806 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1807 * returns success.
1809 * $options is an array of options, with boolean options encoded as values
1810 * with numeric keys, in the same style as $options in
1811 * DatabaseBase::select(). Supported options are:
1813 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1814 * any rows which cause duplicate key errors are not inserted. It's
1815 * possible to determine how many rows were successfully inserted using
1816 * DatabaseBase::affectedRows().
1818 * @param $table String Table name. This will be passed through
1819 * DatabaseBase::tableName().
1820 * @param $a Array of rows to insert
1821 * @param $fname String Calling function name (use __METHOD__) for logs/profiling
1822 * @param array $options of options
1824 * @return bool
1826 public function insert( $table, $a, $fname = __METHOD__, $options = array() ) {
1827 # No rows to insert, easy just return now
1828 if ( !count( $a ) ) {
1829 return true;
1832 $table = $this->tableName( $table );
1834 if ( !is_array( $options ) ) {
1835 $options = array( $options );
1838 $fh = null;
1839 if ( isset( $options['fileHandle'] ) ) {
1840 $fh = $options['fileHandle'];
1842 $options = $this->makeInsertOptions( $options );
1844 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1845 $multi = true;
1846 $keys = array_keys( $a[0] );
1847 } else {
1848 $multi = false;
1849 $keys = array_keys( $a );
1852 $sql = 'INSERT ' . $options .
1853 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1855 if ( $multi ) {
1856 $first = true;
1857 foreach ( $a as $row ) {
1858 if ( $first ) {
1859 $first = false;
1860 } else {
1861 $sql .= ',';
1863 $sql .= '(' . $this->makeList( $row ) . ')';
1865 } else {
1866 $sql .= '(' . $this->makeList( $a ) . ')';
1869 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1870 return false;
1871 } elseif ( $fh !== null ) {
1872 return true;
1875 return (bool)$this->query( $sql, $fname );
1879 * Make UPDATE options for the DatabaseBase::update function
1881 * @param array $options The options passed to DatabaseBase::update
1882 * @return string
1884 protected function makeUpdateOptions( $options ) {
1885 if ( !is_array( $options ) ) {
1886 $options = array( $options );
1889 $opts = array();
1891 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1892 $opts[] = $this->lowPriorityOption();
1895 if ( in_array( 'IGNORE', $options ) ) {
1896 $opts[] = 'IGNORE';
1899 return implode( ' ', $opts );
1903 * UPDATE wrapper. Takes a condition array and a SET array.
1905 * @param $table String name of the table to UPDATE. This will be passed through
1906 * DatabaseBase::tableName().
1908 * @param array $values An array of values to SET. For each array element,
1909 * the key gives the field name, and the value gives the data
1910 * to set that field to. The data will be quoted by
1911 * DatabaseBase::addQuotes().
1913 * @param $conds Array: An array of conditions (WHERE). See
1914 * DatabaseBase::select() for the details of the format of
1915 * condition arrays. Use '*' to update all rows.
1917 * @param $fname String: The function name of the caller (from __METHOD__),
1918 * for logging and profiling.
1920 * @param array $options An array of UPDATE options, can be:
1921 * - IGNORE: Ignore unique key conflicts
1922 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1923 * @return Boolean
1925 function update( $table, $values, $conds, $fname = __METHOD__, $options = array() ) {
1926 $table = $this->tableName( $table );
1927 $opts = $this->makeUpdateOptions( $options );
1928 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1930 if ( $conds !== array() && $conds !== '*' ) {
1931 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1934 return $this->query( $sql, $fname );
1938 * Makes an encoded list of strings from an array
1939 * @param array $a containing the data
1940 * @param int $mode Constant
1941 * - LIST_COMMA: comma separated, no field names
1942 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
1943 * the documentation for $conds in DatabaseBase::select().
1944 * - LIST_OR: ORed WHERE clause (without the WHERE)
1945 * - LIST_SET: comma separated with field names, like a SET clause
1946 * - LIST_NAMES: comma separated field names
1948 * @throws MWException|DBUnexpectedError
1949 * @return string
1951 public function makeList( $a, $mode = LIST_COMMA ) {
1952 if ( !is_array( $a ) ) {
1953 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1956 $first = true;
1957 $list = '';
1959 foreach ( $a as $field => $value ) {
1960 if ( !$first ) {
1961 if ( $mode == LIST_AND ) {
1962 $list .= ' AND ';
1963 } elseif ( $mode == LIST_OR ) {
1964 $list .= ' OR ';
1965 } else {
1966 $list .= ',';
1968 } else {
1969 $first = false;
1972 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
1973 $list .= "($value)";
1974 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
1975 $list .= "$value";
1976 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
1977 if ( count( $value ) == 0 ) {
1978 throw new MWException( __METHOD__ . ": empty input for field $field" );
1979 } elseif ( count( $value ) == 1 ) {
1980 // Special-case single values, as IN isn't terribly efficient
1981 // Don't necessarily assume the single key is 0; we don't
1982 // enforce linear numeric ordering on other arrays here.
1983 $value = array_values( $value );
1984 $list .= $field . " = " . $this->addQuotes( $value[0] );
1985 } else {
1986 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1988 } elseif ( $value === null ) {
1989 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1990 $list .= "$field IS ";
1991 } elseif ( $mode == LIST_SET ) {
1992 $list .= "$field = ";
1994 $list .= 'NULL';
1995 } else {
1996 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1997 $list .= "$field = ";
1999 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
2003 return $list;
2007 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2008 * The keys on each level may be either integers or strings.
2010 * @param array $data organized as 2-d
2011 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2012 * @param string $baseKey field name to match the base-level keys to (eg 'pl_namespace')
2013 * @param string $subKey field name to match the sub-level keys to (eg 'pl_title')
2014 * @return Mixed: string SQL fragment, or false if no items in array.
2016 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2017 $conds = array();
2019 foreach ( $data as $base => $sub ) {
2020 if ( count( $sub ) ) {
2021 $conds[] = $this->makeList(
2022 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2023 LIST_AND );
2027 if ( $conds ) {
2028 return $this->makeList( $conds, LIST_OR );
2029 } else {
2030 // Nothing to search for...
2031 return false;
2036 * Return aggregated value alias
2038 * @param $valuedata
2039 * @param $valuename string
2041 * @return string
2043 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2044 return $valuename;
2048 * @param $field
2049 * @return string
2051 public function bitNot( $field ) {
2052 return "(~$field)";
2056 * @param $fieldLeft
2057 * @param $fieldRight
2058 * @return string
2060 public function bitAnd( $fieldLeft, $fieldRight ) {
2061 return "($fieldLeft & $fieldRight)";
2065 * @param $fieldLeft
2066 * @param $fieldRight
2067 * @return string
2069 public function bitOr( $fieldLeft, $fieldRight ) {
2070 return "($fieldLeft | $fieldRight)";
2074 * Build a concatenation list to feed into a SQL query
2075 * @param array $stringList list of raw SQL expressions; caller is responsible for any quoting
2076 * @return String
2078 public function buildConcat( $stringList ) {
2079 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2083 * Build a GROUP_CONCAT or equivalent statement for a query.
2085 * This is useful for combining a field for several rows into a single string.
2086 * NULL values will not appear in the output, duplicated values will appear,
2087 * and the resulting delimiter-separated values have no defined sort order.
2088 * Code using the results may need to use the PHP unique() or sort() methods.
2090 * @param string $delim Glue to bind the results together
2091 * @param string|array $table Table name
2092 * @param string $field Field name
2093 * @param string|array $conds Conditions
2094 * @param string|array $join_conds Join conditions
2095 * @return String SQL text
2096 * @since 1.23
2098 public function buildGroupConcatField(
2099 $delim, $table, $field, $conds = '', $join_conds = array()
2101 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2102 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2106 * Change the current database
2108 * @todo Explain what exactly will fail if this is not overridden.
2110 * @param $db
2112 * @return bool Success or failure
2114 public function selectDB( $db ) {
2115 # Stub. Shouldn't cause serious problems if it's not overridden, but
2116 # if your database engine supports a concept similar to MySQL's
2117 # databases you may as well.
2118 $this->mDBname = $db;
2119 return true;
2123 * Get the current DB name
2125 public function getDBname() {
2126 return $this->mDBname;
2130 * Get the server hostname or IP address
2132 public function getServer() {
2133 return $this->mServer;
2137 * Format a table name ready for use in constructing an SQL query
2139 * This does two important things: it quotes the table names to clean them up,
2140 * and it adds a table prefix if only given a table name with no quotes.
2142 * All functions of this object which require a table name call this function
2143 * themselves. Pass the canonical name to such functions. This is only needed
2144 * when calling query() directly.
2146 * @param string $name database table name
2147 * @param string $format One of:
2148 * quoted - Automatically pass the table name through addIdentifierQuotes()
2149 * so that it can be used in a query.
2150 * raw - Do not add identifier quotes to the table name
2151 * @return String: full database name
2153 public function tableName( $name, $format = 'quoted' ) {
2154 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
2155 # Skip the entire process when we have a string quoted on both ends.
2156 # Note that we check the end so that we will still quote any use of
2157 # use of `database`.table. But won't break things if someone wants
2158 # to query a database table with a dot in the name.
2159 if ( $this->isQuotedIdentifier( $name ) ) {
2160 return $name;
2163 # Lets test for any bits of text that should never show up in a table
2164 # name. Basically anything like JOIN or ON which are actually part of
2165 # SQL queries, but may end up inside of the table value to combine
2166 # sql. Such as how the API is doing.
2167 # Note that we use a whitespace test rather than a \b test to avoid
2168 # any remote case where a word like on may be inside of a table name
2169 # surrounded by symbols which may be considered word breaks.
2170 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2171 return $name;
2174 # Split database and table into proper variables.
2175 # We reverse the explode so that database.table and table both output
2176 # the correct table.
2177 $dbDetails = explode( '.', $name, 2 );
2178 if ( count( $dbDetails ) == 2 ) {
2179 list( $database, $table ) = $dbDetails;
2180 # We don't want any prefix added in this case
2181 $prefix = '';
2182 } else {
2183 list( $table ) = $dbDetails;
2184 if ( $wgSharedDB !== null # We have a shared database
2185 && $this->mForeign == false # We're not working on a foreign database
2186 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
2187 && in_array( $table, $wgSharedTables ) # A shared table is selected
2189 $database = $wgSharedDB;
2190 $prefix = $wgSharedPrefix === null ? $this->mTablePrefix : $wgSharedPrefix;
2191 } else {
2192 $database = null;
2193 $prefix = $this->mTablePrefix; # Default prefix
2197 # Quote $table and apply the prefix if not quoted.
2198 $tableName = "{$prefix}{$table}";
2199 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) ) {
2200 $tableName = $this->addIdentifierQuotes( $tableName );
2203 # Quote $database and merge it with the table name if needed
2204 if ( $database !== null ) {
2205 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2206 $database = $this->addIdentifierQuotes( $database );
2208 $tableName = $database . '.' . $tableName;
2211 return $tableName;
2215 * Fetch a number of table names into an array
2216 * This is handy when you need to construct SQL for joins
2218 * Example:
2219 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2220 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2221 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2223 * @return array
2225 public function tableNames() {
2226 $inArray = func_get_args();
2227 $retVal = array();
2229 foreach ( $inArray as $name ) {
2230 $retVal[$name] = $this->tableName( $name );
2233 return $retVal;
2237 * Fetch a number of table names into an zero-indexed numerical array
2238 * This is handy when you need to construct SQL for joins
2240 * Example:
2241 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2242 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2243 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2245 * @return array
2247 public function tableNamesN() {
2248 $inArray = func_get_args();
2249 $retVal = array();
2251 foreach ( $inArray as $name ) {
2252 $retVal[] = $this->tableName( $name );
2255 return $retVal;
2259 * Get an aliased table name
2260 * e.g. tableName AS newTableName
2262 * @param string $name Table name, see tableName()
2263 * @param string|bool $alias Alias (optional)
2264 * @return string SQL name for aliased table. Will not alias a table to its own name
2266 public function tableNameWithAlias( $name, $alias = false ) {
2267 if ( !$alias || $alias == $name ) {
2268 return $this->tableName( $name );
2269 } else {
2270 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2275 * Gets an array of aliased table names
2277 * @param $tables array( [alias] => table )
2278 * @return array of strings, see tableNameWithAlias()
2280 public function tableNamesWithAlias( $tables ) {
2281 $retval = array();
2282 foreach ( $tables as $alias => $table ) {
2283 if ( is_numeric( $alias ) ) {
2284 $alias = $table;
2286 $retval[] = $this->tableNameWithAlias( $table, $alias );
2288 return $retval;
2292 * Get an aliased field name
2293 * e.g. fieldName AS newFieldName
2295 * @param string $name Field name
2296 * @param string|bool $alias Alias (optional)
2297 * @return string SQL name for aliased field. Will not alias a field to its own name
2299 public function fieldNameWithAlias( $name, $alias = false ) {
2300 if ( !$alias || (string)$alias === (string)$name ) {
2301 return $name;
2302 } else {
2303 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2308 * Gets an array of aliased field names
2310 * @param $fields array( [alias] => field )
2311 * @return array of strings, see fieldNameWithAlias()
2313 public function fieldNamesWithAlias( $fields ) {
2314 $retval = array();
2315 foreach ( $fields as $alias => $field ) {
2316 if ( is_numeric( $alias ) ) {
2317 $alias = $field;
2319 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2321 return $retval;
2325 * Get the aliased table name clause for a FROM clause
2326 * which might have a JOIN and/or USE INDEX clause
2328 * @param array $tables ( [alias] => table )
2329 * @param $use_index array Same as for select()
2330 * @param $join_conds array Same as for select()
2331 * @return string
2333 protected function tableNamesWithUseIndexOrJOIN(
2334 $tables, $use_index = array(), $join_conds = array()
2336 $ret = array();
2337 $retJOIN = array();
2338 $use_index = (array)$use_index;
2339 $join_conds = (array)$join_conds;
2341 foreach ( $tables as $alias => $table ) {
2342 if ( !is_string( $alias ) ) {
2343 // No alias? Set it equal to the table name
2344 $alias = $table;
2346 // Is there a JOIN clause for this table?
2347 if ( isset( $join_conds[$alias] ) ) {
2348 list( $joinType, $conds ) = $join_conds[$alias];
2349 $tableClause = $joinType;
2350 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2351 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2352 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2353 if ( $use != '' ) {
2354 $tableClause .= ' ' . $use;
2357 $on = $this->makeList( (array)$conds, LIST_AND );
2358 if ( $on != '' ) {
2359 $tableClause .= ' ON (' . $on . ')';
2362 $retJOIN[] = $tableClause;
2363 // Is there an INDEX clause for this table?
2364 } elseif ( isset( $use_index[$alias] ) ) {
2365 $tableClause = $this->tableNameWithAlias( $table, $alias );
2366 $tableClause .= ' ' . $this->useIndexClause(
2367 implode( ',', (array)$use_index[$alias] ) );
2369 $ret[] = $tableClause;
2370 } else {
2371 $tableClause = $this->tableNameWithAlias( $table, $alias );
2373 $ret[] = $tableClause;
2377 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2378 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
2379 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
2381 // Compile our final table clause
2382 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2386 * Get the name of an index in a given table
2388 * @param $index
2390 * @return string
2392 protected function indexName( $index ) {
2393 // Backwards-compatibility hack
2394 $renamed = array(
2395 'ar_usertext_timestamp' => 'usertext_timestamp',
2396 'un_user_id' => 'user_id',
2397 'un_user_ip' => 'user_ip',
2400 if ( isset( $renamed[$index] ) ) {
2401 return $renamed[$index];
2402 } else {
2403 return $index;
2408 * Adds quotes and backslashes.
2410 * @param $s string
2412 * @return string
2414 public function addQuotes( $s ) {
2415 if ( $s === null ) {
2416 return 'NULL';
2417 } else {
2418 # This will also quote numeric values. This should be harmless,
2419 # and protects against weird problems that occur when they really
2420 # _are_ strings such as article titles and string->number->string
2421 # conversion is not 1:1.
2422 return "'" . $this->strencode( $s ) . "'";
2427 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2428 * MySQL uses `backticks` while basically everything else uses double quotes.
2429 * Since MySQL is the odd one out here the double quotes are our generic
2430 * and we implement backticks in DatabaseMysql.
2432 * @param $s string
2434 * @return string
2436 public function addIdentifierQuotes( $s ) {
2437 return '"' . str_replace( '"', '""', $s ) . '"';
2441 * Returns if the given identifier looks quoted or not according to
2442 * the database convention for quoting identifiers .
2444 * @param $name string
2446 * @return boolean
2448 public function isQuotedIdentifier( $name ) {
2449 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2453 * @param $s string
2454 * @return string
2456 protected function escapeLikeInternal( $s ) {
2457 $s = str_replace( '\\', '\\\\', $s );
2458 $s = $this->strencode( $s );
2459 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
2461 return $s;
2465 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
2466 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
2467 * Alternatively, the function could be provided with an array of aforementioned parameters.
2469 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
2470 * for subpages of 'My page title'.
2471 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
2473 * @since 1.16
2474 * @return String: fully built LIKE statement
2476 public function buildLike() {
2477 $params = func_get_args();
2479 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2480 $params = $params[0];
2483 $s = '';
2485 foreach ( $params as $value ) {
2486 if ( $value instanceof LikeMatch ) {
2487 $s .= $value->toString();
2488 } else {
2489 $s .= $this->escapeLikeInternal( $value );
2493 return " LIKE '" . $s . "' ";
2497 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2499 * @return LikeMatch
2501 public function anyChar() {
2502 return new LikeMatch( '_' );
2506 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2508 * @return LikeMatch
2510 public function anyString() {
2511 return new LikeMatch( '%' );
2515 * Returns an appropriately quoted sequence value for inserting a new row.
2516 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2517 * subclass will return an integer, and save the value for insertId()
2519 * Any implementation of this function should *not* involve reusing
2520 * sequence numbers created for rolled-back transactions.
2521 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2522 * @param $seqName string
2523 * @return null
2525 public function nextSequenceValue( $seqName ) {
2526 return null;
2530 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2531 * is only needed because a) MySQL must be as efficient as possible due to
2532 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2533 * which index to pick. Anyway, other databases might have different
2534 * indexes on a given table. So don't bother overriding this unless you're
2535 * MySQL.
2536 * @param $index
2537 * @return string
2539 public function useIndexClause( $index ) {
2540 return '';
2544 * REPLACE query wrapper.
2546 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2547 * except that when there is a duplicate key error, the old row is deleted
2548 * and the new row is inserted in its place.
2550 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2551 * perform the delete, we need to know what the unique indexes are so that
2552 * we know how to find the conflicting rows.
2554 * It may be more efficient to leave off unique indexes which are unlikely
2555 * to collide. However if you do this, you run the risk of encountering
2556 * errors which wouldn't have occurred in MySQL.
2558 * @param string $table The table to replace the row(s) in.
2559 * @param array $rows Can be either a single row to insert, or multiple rows,
2560 * in the same format as for DatabaseBase::insert()
2561 * @param array $uniqueIndexes is an array of indexes. Each element may be either
2562 * a field name or an array of field names
2563 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2565 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2566 $quotedTable = $this->tableName( $table );
2568 if ( count( $rows ) == 0 ) {
2569 return;
2572 # Single row case
2573 if ( !is_array( reset( $rows ) ) ) {
2574 $rows = array( $rows );
2577 foreach ( $rows as $row ) {
2578 # Delete rows which collide
2579 if ( $uniqueIndexes ) {
2580 $sql = "DELETE FROM $quotedTable WHERE ";
2581 $first = true;
2582 foreach ( $uniqueIndexes as $index ) {
2583 if ( $first ) {
2584 $first = false;
2585 $sql .= '( ';
2586 } else {
2587 $sql .= ' ) OR ( ';
2589 if ( is_array( $index ) ) {
2590 $first2 = true;
2591 foreach ( $index as $col ) {
2592 if ( $first2 ) {
2593 $first2 = false;
2594 } else {
2595 $sql .= ' AND ';
2597 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2599 } else {
2600 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2603 $sql .= ' )';
2604 $this->query( $sql, $fname );
2607 # Now insert the row
2608 $this->insert( $table, $row, $fname );
2613 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2614 * statement.
2616 * @param string $table Table name
2617 * @param array $rows Rows to insert
2618 * @param string $fname Caller function name
2620 * @return ResultWrapper
2622 protected function nativeReplace( $table, $rows, $fname ) {
2623 $table = $this->tableName( $table );
2625 # Single row case
2626 if ( !is_array( reset( $rows ) ) ) {
2627 $rows = array( $rows );
2630 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2631 $first = true;
2633 foreach ( $rows as $row ) {
2634 if ( $first ) {
2635 $first = false;
2636 } else {
2637 $sql .= ',';
2640 $sql .= '(' . $this->makeList( $row ) . ')';
2643 return $this->query( $sql, $fname );
2647 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2649 * This updates any conflicting rows (according to the unique indexes) using
2650 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2652 * $rows may be either:
2653 * - A single associative array. The array keys are the field names, and
2654 * the values are the values to insert. The values are treated as data
2655 * and will be quoted appropriately. If NULL is inserted, this will be
2656 * converted to a database NULL.
2657 * - An array with numeric keys, holding a list of associative arrays.
2658 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2659 * each subarray must be identical to each other, and in the same order.
2661 * It may be more efficient to leave off unique indexes which are unlikely
2662 * to collide. However if you do this, you run the risk of encountering
2663 * errors which wouldn't have occurred in MySQL.
2665 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2666 * returns success.
2668 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2669 * @param array $rows A single row or list of rows to insert
2670 * @param array $uniqueIndexes List of single field names or field name tuples
2671 * @param array $set An array of values to SET. For each array element,
2672 * the key gives the field name, and the value gives the data
2673 * to set that field to. The data will be quoted by
2674 * DatabaseBase::addQuotes().
2675 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2676 * @param array $options of options
2678 * @return bool
2679 * @since 1.22
2681 public function upsert(
2682 $table, array $rows, array $uniqueIndexes, array $set, $fname = __METHOD__
2684 if ( !count( $rows ) ) {
2685 return true; // nothing to do
2687 $rows = is_array( reset( $rows ) ) ? $rows : array( $rows );
2689 if ( count( $uniqueIndexes ) ) {
2690 $clauses = array(); // list WHERE clauses that each identify a single row
2691 foreach ( $rows as $row ) {
2692 foreach ( $uniqueIndexes as $index ) {
2693 $index = is_array( $index ) ? $index : array( $index ); // columns
2694 $rowKey = array(); // unique key to this row
2695 foreach ( $index as $column ) {
2696 $rowKey[$column] = $row[$column];
2698 $clauses[] = $this->makeList( $rowKey, LIST_AND );
2701 $where = array( $this->makeList( $clauses, LIST_OR ) );
2702 } else {
2703 $where = false;
2706 $useTrx = !$this->mTrxLevel;
2707 if ( $useTrx ) {
2708 $this->begin( $fname );
2710 try {
2711 # Update any existing conflicting row(s)
2712 if ( $where !== false ) {
2713 $ok = $this->update( $table, $set, $where, $fname );
2714 } else {
2715 $ok = true;
2717 # Now insert any non-conflicting row(s)
2718 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2719 } catch ( Exception $e ) {
2720 if ( $useTrx ) {
2721 $this->rollback( $fname );
2723 throw $e;
2725 if ( $useTrx ) {
2726 $this->commit( $fname );
2729 return $ok;
2733 * DELETE where the condition is a join.
2735 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2736 * we use sub-selects
2738 * For safety, an empty $conds will not delete everything. If you want to
2739 * delete all rows where the join condition matches, set $conds='*'.
2741 * DO NOT put the join condition in $conds.
2743 * @param $delTable String: The table to delete from.
2744 * @param $joinTable String: The other table.
2745 * @param $delVar String: The variable to join on, in the first table.
2746 * @param $joinVar String: The variable to join on, in the second table.
2747 * @param $conds Array: Condition array of field names mapped to variables,
2748 * ANDed together in the WHERE clause
2749 * @param $fname String: Calling function name (use __METHOD__) for
2750 * logs/profiling
2751 * @throws DBUnexpectedError
2753 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2754 $fname = __METHOD__ )
2756 if ( !$conds ) {
2757 throw new DBUnexpectedError( $this,
2758 'DatabaseBase::deleteJoin() called with empty $conds' );
2761 $delTable = $this->tableName( $delTable );
2762 $joinTable = $this->tableName( $joinTable );
2763 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2764 if ( $conds != '*' ) {
2765 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
2767 $sql .= ')';
2769 $this->query( $sql, $fname );
2773 * Returns the size of a text field, or -1 for "unlimited"
2775 * @param $table string
2776 * @param $field string
2778 * @return int
2780 public function textFieldSize( $table, $field ) {
2781 $table = $this->tableName( $table );
2782 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2783 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2784 $row = $this->fetchObject( $res );
2786 $m = array();
2788 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2789 $size = $m[1];
2790 } else {
2791 $size = -1;
2794 return $size;
2798 * A string to insert into queries to show that they're low-priority, like
2799 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2800 * string and nothing bad should happen.
2802 * @return string Returns the text of the low priority option if it is
2803 * supported, or a blank string otherwise
2805 public function lowPriorityOption() {
2806 return '';
2810 * DELETE query wrapper.
2812 * @param array $table Table name
2813 * @param string|array $conds of conditions. See $conds in DatabaseBase::select() for
2814 * the format. Use $conds == "*" to delete all rows
2815 * @param string $fname name of the calling function
2817 * @throws DBUnexpectedError
2818 * @return bool|ResultWrapper
2820 public function delete( $table, $conds, $fname = __METHOD__ ) {
2821 if ( !$conds ) {
2822 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2825 $table = $this->tableName( $table );
2826 $sql = "DELETE FROM $table";
2828 if ( $conds != '*' ) {
2829 if ( is_array( $conds ) ) {
2830 $conds = $this->makeList( $conds, LIST_AND );
2832 $sql .= ' WHERE ' . $conds;
2835 return $this->query( $sql, $fname );
2839 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2840 * into another table.
2842 * @param string $destTable The table name to insert into
2843 * @param string|array $srcTable May be either a table name, or an array of table names
2844 * to include in a join.
2846 * @param array $varMap must be an associative array of the form
2847 * array( 'dest1' => 'source1', ...). Source items may be literals
2848 * rather than field names, but strings should be quoted with
2849 * DatabaseBase::addQuotes()
2851 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
2852 * the details of the format of condition arrays. May be "*" to copy the
2853 * whole table.
2855 * @param string $fname The function name of the caller, from __METHOD__
2857 * @param array $insertOptions Options for the INSERT part of the query, see
2858 * DatabaseBase::insert() for details.
2859 * @param array $selectOptions Options for the SELECT part of the query, see
2860 * DatabaseBase::select() for details.
2862 * @return ResultWrapper
2864 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2865 $fname = __METHOD__,
2866 $insertOptions = array(), $selectOptions = array() )
2868 $destTable = $this->tableName( $destTable );
2870 if ( is_array( $insertOptions ) ) {
2871 $insertOptions = implode( ' ', $insertOptions );
2874 if ( !is_array( $selectOptions ) ) {
2875 $selectOptions = array( $selectOptions );
2878 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2880 if ( is_array( $srcTable ) ) {
2881 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2882 } else {
2883 $srcTable = $this->tableName( $srcTable );
2886 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2887 " SELECT $startOpts " . implode( ',', $varMap ) .
2888 " FROM $srcTable $useIndex ";
2890 if ( $conds != '*' ) {
2891 if ( is_array( $conds ) ) {
2892 $conds = $this->makeList( $conds, LIST_AND );
2894 $sql .= " WHERE $conds";
2897 $sql .= " $tailOpts";
2899 return $this->query( $sql, $fname );
2903 * Construct a LIMIT query with optional offset. This is used for query
2904 * pages. The SQL should be adjusted so that only the first $limit rows
2905 * are returned. If $offset is provided as well, then the first $offset
2906 * rows should be discarded, and the next $limit rows should be returned.
2907 * If the result of the query is not ordered, then the rows to be returned
2908 * are theoretically arbitrary.
2910 * $sql is expected to be a SELECT, if that makes a difference.
2912 * The version provided by default works in MySQL and SQLite. It will very
2913 * likely need to be overridden for most other DBMSes.
2915 * @param string $sql SQL query we will append the limit too
2916 * @param $limit Integer the SQL limit
2917 * @param $offset Integer|bool the SQL offset (default false)
2919 * @throws DBUnexpectedError
2920 * @return string
2922 public function limitResult( $sql, $limit, $offset = false ) {
2923 if ( !is_numeric( $limit ) ) {
2924 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2926 return "$sql LIMIT "
2927 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2928 . "{$limit} ";
2932 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2933 * within the UNION construct.
2934 * @return Boolean
2936 public function unionSupportsOrderAndLimit() {
2937 return true; // True for almost every DB supported
2941 * Construct a UNION query
2942 * This is used for providing overload point for other DB abstractions
2943 * not compatible with the MySQL syntax.
2944 * @param array $sqls SQL statements to combine
2945 * @param $all Boolean: use UNION ALL
2946 * @return String: SQL fragment
2948 public function unionQueries( $sqls, $all ) {
2949 $glue = $all ? ') UNION ALL (' : ') UNION (';
2950 return '(' . implode( $glue, $sqls ) . ')';
2954 * Returns an SQL expression for a simple conditional. This doesn't need
2955 * to be overridden unless CASE isn't supported in your DBMS.
2957 * @param string|array $cond SQL expression which will result in a boolean value
2958 * @param string $trueVal SQL expression to return if true
2959 * @param string $falseVal SQL expression to return if false
2960 * @return String: SQL fragment
2962 public function conditional( $cond, $trueVal, $falseVal ) {
2963 if ( is_array( $cond ) ) {
2964 $cond = $this->makeList( $cond, LIST_AND );
2966 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2970 * Returns a comand for str_replace function in SQL query.
2971 * Uses REPLACE() in MySQL
2973 * @param string $orig column to modify
2974 * @param string $old column to seek
2975 * @param string $new column to replace with
2977 * @return string
2979 public function strreplace( $orig, $old, $new ) {
2980 return "REPLACE({$orig}, {$old}, {$new})";
2984 * Determines how long the server has been up
2985 * STUB
2987 * @return int
2989 public function getServerUptime() {
2990 return 0;
2994 * Determines if the last failure was due to a deadlock
2995 * STUB
2997 * @return bool
2999 public function wasDeadlock() {
3000 return false;
3004 * Determines if the last failure was due to a lock timeout
3005 * STUB
3007 * @return bool
3009 public function wasLockTimeout() {
3010 return false;
3014 * Determines if the last query error was something that should be dealt
3015 * with by pinging the connection and reissuing the query.
3016 * STUB
3018 * @return bool
3020 public function wasErrorReissuable() {
3021 return false;
3025 * Determines if the last failure was due to the database being read-only.
3026 * STUB
3028 * @return bool
3030 public function wasReadOnlyError() {
3031 return false;
3035 * Perform a deadlock-prone transaction.
3037 * This function invokes a callback function to perform a set of write
3038 * queries. If a deadlock occurs during the processing, the transaction
3039 * will be rolled back and the callback function will be called again.
3041 * Usage:
3042 * $dbw->deadlockLoop( callback, ... );
3044 * Extra arguments are passed through to the specified callback function.
3046 * Returns whatever the callback function returned on its successful,
3047 * iteration, or false on error, for example if the retry limit was
3048 * reached.
3050 * @return bool
3052 public function deadlockLoop() {
3053 $this->begin( __METHOD__ );
3054 $args = func_get_args();
3055 $function = array_shift( $args );
3056 $oldIgnore = $this->ignoreErrors( true );
3057 $tries = self::DEADLOCK_TRIES;
3059 if ( is_array( $function ) ) {
3060 $fname = $function[0];
3061 } else {
3062 $fname = $function;
3065 do {
3066 $retVal = call_user_func_array( $function, $args );
3067 $error = $this->lastError();
3068 $errno = $this->lastErrno();
3069 $sql = $this->lastQuery();
3071 if ( $errno ) {
3072 if ( $this->wasDeadlock() ) {
3073 # Retry
3074 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
3075 } else {
3076 $this->reportQueryError( $error, $errno, $sql, $fname );
3079 } while ( $this->wasDeadlock() && --$tries > 0 );
3081 $this->ignoreErrors( $oldIgnore );
3083 if ( $tries <= 0 ) {
3084 $this->rollback( __METHOD__ );
3085 $this->reportQueryError( $error, $errno, $sql, $fname );
3086 return false;
3087 } else {
3088 $this->commit( __METHOD__ );
3089 return $retVal;
3094 * Wait for the slave to catch up to a given master position.
3096 * @param $pos DBMasterPos object
3097 * @param $timeout Integer: the maximum number of seconds to wait for
3098 * synchronisation
3100 * @return integer: zero if the slave was past that position already,
3101 * greater than zero if we waited for some period of time, less than
3102 * zero if we timed out.
3104 public function masterPosWait( DBMasterPos $pos, $timeout ) {
3105 wfProfileIn( __METHOD__ );
3107 if ( !is_null( $this->mFakeSlaveLag ) ) {
3108 $wait = intval( ( $pos->pos - microtime( true ) + $this->mFakeSlaveLag ) * 1e6 );
3110 if ( $wait > $timeout * 1e6 ) {
3111 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
3112 wfProfileOut( __METHOD__ );
3113 return -1;
3114 } elseif ( $wait > 0 ) {
3115 wfDebug( "Fake slave waiting $wait us\n" );
3116 usleep( $wait );
3117 wfProfileOut( __METHOD__ );
3118 return 1;
3119 } else {
3120 wfDebug( "Fake slave up to date ($wait us)\n" );
3121 wfProfileOut( __METHOD__ );
3122 return 0;
3126 wfProfileOut( __METHOD__ );
3128 # Real waits are implemented in the subclass.
3129 return 0;
3133 * Get the replication position of this slave
3135 * @return DBMasterPos, or false if this is not a slave.
3137 public function getSlavePos() {
3138 if ( !is_null( $this->mFakeSlaveLag ) ) {
3139 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag );
3140 wfDebug( __METHOD__ . ": fake slave pos = $pos\n" );
3141 return $pos;
3142 } else {
3143 # Stub
3144 return false;
3149 * Get the position of this master
3151 * @return DBMasterPos, or false if this is not a master
3153 public function getMasterPos() {
3154 if ( $this->mFakeMaster ) {
3155 return new MySQLMasterPos( 'fake', microtime( true ) );
3156 } else {
3157 return false;
3162 * Run an anonymous function as soon as there is no transaction pending.
3163 * If there is a transaction and it is rolled back, then the callback is cancelled.
3164 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3165 * Callbacks must commit any transactions that they begin.
3167 * This is useful for updates to different systems or when separate transactions are needed.
3168 * For example, one might want to enqueue jobs into a system outside the database, but only
3169 * after the database is updated so that the jobs will see the data when they actually run.
3170 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3172 * @param callable $callback
3173 * @since 1.20
3175 final public function onTransactionIdle( $callback ) {
3176 $this->mTrxIdleCallbacks[] = array( $callback, wfGetCaller() );
3177 if ( !$this->mTrxLevel ) {
3178 $this->runOnTransactionIdleCallbacks();
3183 * Run an anonymous function before the current transaction commits or now if there is none.
3184 * If there is a transaction and it is rolled back, then the callback is cancelled.
3185 * Callbacks must not start nor commit any transactions.
3187 * This is useful for updates that easily cause deadlocks if locks are held too long
3188 * but where atomicity is strongly desired for these updates and some related updates.
3190 * @param callable $callback
3191 * @since 1.22
3193 final public function onTransactionPreCommitOrIdle( $callback ) {
3194 if ( $this->mTrxLevel ) {
3195 $this->mTrxPreCommitCallbacks[] = array( $callback, wfGetCaller() );
3196 } else {
3197 $this->onTransactionIdle( $callback ); // this will trigger immediately
3202 * Actually any "on transaction idle" callbacks.
3204 * @since 1.20
3206 protected function runOnTransactionIdleCallbacks() {
3207 $autoTrx = $this->getFlag( DBO_TRX ); // automatic begin() enabled?
3209 $e = null; // last exception
3210 do { // callbacks may add callbacks :)
3211 $callbacks = $this->mTrxIdleCallbacks;
3212 $this->mTrxIdleCallbacks = array(); // recursion guard
3213 foreach ( $callbacks as $callback ) {
3214 try {
3215 list( $phpCallback ) = $callback;
3216 $this->clearFlag( DBO_TRX ); // make each query its own transaction
3217 call_user_func( $phpCallback );
3218 $this->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
3219 } catch ( Exception $e ) {}
3221 } while ( count( $this->mTrxIdleCallbacks ) );
3223 if ( $e instanceof Exception ) {
3224 throw $e; // re-throw any last exception
3229 * Actually any "on transaction pre-commit" callbacks.
3231 * @since 1.22
3233 protected function runOnTransactionPreCommitCallbacks() {
3234 $e = null; // last exception
3235 do { // callbacks may add callbacks :)
3236 $callbacks = $this->mTrxPreCommitCallbacks;
3237 $this->mTrxPreCommitCallbacks = array(); // recursion guard
3238 foreach ( $callbacks as $callback ) {
3239 try {
3240 list( $phpCallback ) = $callback;
3241 call_user_func( $phpCallback );
3242 } catch ( Exception $e ) {}
3244 } while ( count( $this->mTrxPreCommitCallbacks ) );
3246 if ( $e instanceof Exception ) {
3247 throw $e; // re-throw any last exception
3252 * Begin an atomic section of statements
3254 * If a transaction has been started already, just keep track of the given
3255 * section name to make sure the transaction is not committed pre-maturely.
3256 * This function can be used in layers (with sub-sections), so use a stack
3257 * to keep track of the different atomic sections. If there is no transaction,
3258 * start one implicitly.
3260 * The goal of this function is to create an atomic section of SQL queries
3261 * without having to start a new transaction if it already exists.
3263 * Atomic sections are more strict than transactions. With transactions,
3264 * attempting to begin a new transaction when one is already running results
3265 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3266 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3267 * and any database transactions cannot be began or committed until all atomic
3268 * levels are closed. There is no such thing as implicitly opening or closing
3269 * an atomic section.
3271 * @since 1.23
3272 * @param string $fname
3273 * @throws DBError
3275 final public function startAtomic( $fname = __METHOD__ ) {
3276 if ( !$this->mTrxLevel ) {
3277 $this->begin( $fname );
3278 $this->mTrxAutomatic = true;
3279 $this->mTrxAutomaticAtomic = true;
3282 $this->mTrxAtomicLevels->push( $fname );
3286 * Ends an atomic section of SQL statements
3288 * Ends the next section of atomic SQL statements and commits the transaction
3289 * if necessary.
3291 * @since 1.23
3292 * @see DatabaseBase::startAtomic
3293 * @param string $fname
3294 * @throws DBError
3296 final public function endAtomic( $fname = __METHOD__ ) {
3297 if ( !$this->mTrxLevel ) {
3298 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3300 if ( $this->mTrxAtomicLevels->isEmpty() ||
3301 $this->mTrxAtomicLevels->pop() !== $fname
3303 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3306 if ( $this->mTrxAtomicLevels->isEmpty() && $this->mTrxAutomaticAtomic ) {
3307 $this->commit( $fname, 'flush' );
3312 * Begin a transaction. If a transaction is already in progress, that transaction will be committed before the
3313 * new transaction is started.
3315 * Note that when the DBO_TRX flag is set (which is usually the case for web requests, but not for maintenance scripts),
3316 * any previous database query will have started a transaction automatically.
3318 * Nesting of transactions is not supported. Attempts to nest transactions will cause a warning, unless the current
3319 * transaction was started automatically because of the DBO_TRX flag.
3321 * @param $fname string
3322 * @throws DBError
3324 final public function begin( $fname = __METHOD__ ) {
3325 global $wgDebugDBTransactions;
3327 if ( $this->mTrxLevel ) { // implicit commit
3328 if ( !$this->mTrxAtomicLevels->isEmpty() ) {
3329 // If the current transaction was an automatic atomic one, then we definitely have
3330 // a problem. Same if there is any unclosed atomic level.
3331 throw new DBUnexpectedError( $this,
3332 "Attempted to start explicit transaction when atomic levels are still open."
3334 } elseif ( !$this->mTrxAutomatic ) {
3335 // We want to warn about inadvertently nested begin/commit pairs, but not about
3336 // auto-committing implicit transactions that were started by query() via DBO_TRX
3337 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3338 " performing implicit commit!";
3339 wfWarn( $msg );
3340 wfLogDBError( $msg );
3341 } else {
3342 // if the transaction was automatic and has done write operations,
3343 // log it if $wgDebugDBTransactions is enabled.
3344 if ( $this->mTrxDoneWrites && $wgDebugDBTransactions ) {
3345 wfDebug( "$fname: Automatic transaction with writes in progress" .
3346 " (from {$this->mTrxFname}), performing implicit commit!\n"
3351 $this->runOnTransactionPreCommitCallbacks();
3352 $this->doCommit( $fname );
3353 if ( $this->mTrxDoneWrites ) {
3354 Profiler::instance()->transactionWritingOut( $this->mServer, $this->mDBname );
3356 $this->runOnTransactionIdleCallbacks();
3359 $this->doBegin( $fname );
3360 $this->mTrxFname = $fname;
3361 $this->mTrxDoneWrites = false;
3362 $this->mTrxAutomatic = false;
3363 $this->mTrxAutomaticAtomic = false;
3364 $this->mTrxAtomicLevels = new SplStack;
3365 $this->mTrxIdleCallbacks = array();
3366 $this->mTrxPreCommitCallbacks = array();
3370 * Issues the BEGIN command to the database server.
3372 * @see DatabaseBase::begin()
3373 * @param type $fname
3375 protected function doBegin( $fname ) {
3376 $this->query( 'BEGIN', $fname );
3377 $this->mTrxLevel = 1;
3381 * Commits a transaction previously started using begin().
3382 * If no transaction is in progress, a warning is issued.
3384 * Nesting of transactions is not supported.
3386 * @param $fname string
3387 * @param string $flush Flush flag, set to 'flush' to disable warnings about explicitly committing implicit
3388 * transactions, or calling commit when no transaction is in progress.
3389 * This will silently break any ongoing explicit transaction. Only set the flush flag if you are sure
3390 * that it is safe to ignore these warnings in your context.
3392 final public function commit( $fname = __METHOD__, $flush = '' ) {
3393 if ( !$this->mTrxAtomicLevels->isEmpty() ) {
3394 // There are still atomic sections open. This cannot be ignored
3395 throw new DBUnexpectedError( $this, "Attempted to commit transaction while atomic sections are still open" );
3398 if ( $flush != 'flush' ) {
3399 if ( !$this->mTrxLevel ) {
3400 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3401 } elseif ( $this->mTrxAutomatic ) {
3402 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3404 } else {
3405 if ( !$this->mTrxLevel ) {
3406 return; // nothing to do
3407 } elseif ( !$this->mTrxAutomatic ) {
3408 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3412 $this->runOnTransactionPreCommitCallbacks();
3413 $this->doCommit( $fname );
3414 if ( $this->mTrxDoneWrites ) {
3415 Profiler::instance()->transactionWritingOut( $this->mServer, $this->mDBname );
3417 $this->runOnTransactionIdleCallbacks();
3421 * Issues the COMMIT command to the database server.
3423 * @see DatabaseBase::commit()
3424 * @param type $fname
3426 protected function doCommit( $fname ) {
3427 if ( $this->mTrxLevel ) {
3428 $this->query( 'COMMIT', $fname );
3429 $this->mTrxLevel = 0;
3434 * Rollback a transaction previously started using begin().
3435 * If no transaction is in progress, a warning is issued.
3437 * No-op on non-transactional databases.
3439 * @param $fname string
3441 final public function rollback( $fname = __METHOD__ ) {
3442 if ( !$this->mTrxLevel ) {
3443 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3445 $this->doRollback( $fname );
3446 $this->mTrxIdleCallbacks = array(); // cancel
3447 $this->mTrxPreCommitCallbacks = array(); // cancel
3448 $this->mTrxAtomicLevels = new SplStack;
3449 if ( $this->mTrxDoneWrites ) {
3450 Profiler::instance()->transactionWritingOut( $this->mServer, $this->mDBname );
3455 * Issues the ROLLBACK command to the database server.
3457 * @see DatabaseBase::rollback()
3458 * @param type $fname
3460 protected function doRollback( $fname ) {
3461 if ( $this->mTrxLevel ) {
3462 $this->query( 'ROLLBACK', $fname, true );
3463 $this->mTrxLevel = 0;
3468 * Creates a new table with structure copied from existing table
3469 * Note that unlike most database abstraction functions, this function does not
3470 * automatically append database prefix, because it works at a lower
3471 * abstraction level.
3472 * The table names passed to this function shall not be quoted (this
3473 * function calls addIdentifierQuotes when needed).
3475 * @param string $oldName name of table whose structure should be copied
3476 * @param string $newName name of table to be created
3477 * @param $temporary Boolean: whether the new table should be temporary
3478 * @param string $fname calling function name
3479 * @throws MWException
3480 * @return Boolean: true if operation was successful
3482 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3483 $fname = __METHOD__
3485 throw new MWException(
3486 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3490 * List all tables on the database
3492 * @param string $prefix Only show tables with this prefix, e.g. mw_
3493 * @param string $fname calling function name
3494 * @throws MWException
3496 function listTables( $prefix = null, $fname = __METHOD__ ) {
3497 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3501 * Reset the views process cache set by listViews()
3502 * @since 1.22
3504 final public function clearViewsCache() {
3505 $this->allViews = null;
3509 * Lists all the VIEWs in the database
3511 * For caching purposes the list of all views should be stored in
3512 * $this->allViews. The process cache can be cleared with clearViewsCache()
3514 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3515 * @param string $fname Name of calling function
3516 * @throws MWException
3517 * @since 1.22
3519 public function listViews( $prefix = null, $fname = __METHOD__ ) {
3520 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3524 * Differentiates between a TABLE and a VIEW
3526 * @param $name string: Name of the database-structure to test.
3527 * @throws MWException
3528 * @since 1.22
3530 public function isView( $name ) {
3531 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3535 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3536 * to the format used for inserting into timestamp fields in this DBMS.
3538 * The result is unquoted, and needs to be passed through addQuotes()
3539 * before it can be included in raw SQL.
3541 * @param $ts string|int
3543 * @return string
3545 public function timestamp( $ts = 0 ) {
3546 return wfTimestamp( TS_MW, $ts );
3550 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3551 * to the format used for inserting into timestamp fields in this DBMS. If
3552 * NULL is input, it is passed through, allowing NULL values to be inserted
3553 * into timestamp fields.
3555 * The result is unquoted, and needs to be passed through addQuotes()
3556 * before it can be included in raw SQL.
3558 * @param $ts string|int
3560 * @return string
3562 public function timestampOrNull( $ts = null ) {
3563 if ( is_null( $ts ) ) {
3564 return null;
3565 } else {
3566 return $this->timestamp( $ts );
3571 * Take the result from a query, and wrap it in a ResultWrapper if
3572 * necessary. Boolean values are passed through as is, to indicate success
3573 * of write queries or failure.
3575 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3576 * resource, and it was necessary to call this function to convert it to
3577 * a wrapper. Nowadays, raw database objects are never exposed to external
3578 * callers, so this is unnecessary in external code. For compatibility with
3579 * old code, ResultWrapper objects are passed through unaltered.
3581 * @param $result bool|ResultWrapper
3583 * @return bool|ResultWrapper
3585 public function resultObject( $result ) {
3586 if ( empty( $result ) ) {
3587 return false;
3588 } elseif ( $result instanceof ResultWrapper ) {
3589 return $result;
3590 } elseif ( $result === true ) {
3591 // Successful write query
3592 return $result;
3593 } else {
3594 return new ResultWrapper( $this, $result );
3599 * Ping the server and try to reconnect if it there is no connection
3601 * @return bool Success or failure
3603 public function ping() {
3604 # Stub. Not essential to override.
3605 return true;
3609 * Get slave lag. Currently supported only by MySQL.
3611 * Note that this function will generate a fatal error on many
3612 * installations. Most callers should use LoadBalancer::safeGetLag()
3613 * instead.
3615 * @return int Database replication lag in seconds
3617 public function getLag() {
3618 return intval( $this->mFakeSlaveLag );
3622 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3624 * @return int
3626 function maxListLen() {
3627 return 0;
3631 * Some DBMSs have a special format for inserting into blob fields, they
3632 * don't allow simple quoted strings to be inserted. To insert into such
3633 * a field, pass the data through this function before passing it to
3634 * DatabaseBase::insert().
3635 * @param $b string
3636 * @return string
3638 public function encodeBlob( $b ) {
3639 return $b;
3643 * Some DBMSs return a special placeholder object representing blob fields
3644 * in result objects. Pass the object through this function to return the
3645 * original string.
3646 * @param $b string
3647 * @return string
3649 public function decodeBlob( $b ) {
3650 return $b;
3654 * Override database's default behavior. $options include:
3655 * 'connTimeout' : Set the connection timeout value in seconds.
3656 * May be useful for very long batch queries such as
3657 * full-wiki dumps, where a single query reads out over
3658 * hours or days.
3660 * @param $options Array
3661 * @return void
3663 public function setSessionOptions( array $options ) {
3667 * Read and execute SQL commands from a file.
3669 * Returns true on success, error string or exception on failure (depending
3670 * on object's error ignore settings).
3672 * @param string $filename File name to open
3673 * @param bool|callable $lineCallback Optional function called before reading each line
3674 * @param bool|callable $resultCallback Optional function called for each MySQL result
3675 * @param bool|string $fname Calling function name or false if name should be
3676 * generated dynamically using $filename
3677 * @param bool|callable $inputCallback Callback: Optional function called for each complete line sent
3678 * @throws MWException
3679 * @throws Exception|MWException
3680 * @return bool|string
3682 public function sourceFile(
3683 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3685 wfSuppressWarnings();
3686 $fp = fopen( $filename, 'r' );
3687 wfRestoreWarnings();
3689 if ( false === $fp ) {
3690 throw new MWException( "Could not open \"{$filename}\".\n" );
3693 if ( !$fname ) {
3694 $fname = __METHOD__ . "( $filename )";
3697 try {
3698 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3700 catch ( MWException $e ) {
3701 fclose( $fp );
3702 throw $e;
3705 fclose( $fp );
3707 return $error;
3711 * Get the full path of a patch file. Originally based on archive()
3712 * from updaters.inc. Keep in mind this always returns a patch, as
3713 * it fails back to MySQL if no DB-specific patch can be found
3715 * @param string $patch The name of the patch, like patch-something.sql
3716 * @return String Full path to patch file
3718 public function patchPath( $patch ) {
3719 global $IP;
3721 $dbType = $this->getType();
3722 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3723 return "$IP/maintenance/$dbType/archives/$patch";
3724 } else {
3725 return "$IP/maintenance/archives/$patch";
3730 * Set variables to be used in sourceFile/sourceStream, in preference to the
3731 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3732 * all. If it's set to false, $GLOBALS will be used.
3734 * @param bool|array $vars mapping variable name to value.
3736 public function setSchemaVars( $vars ) {
3737 $this->mSchemaVars = $vars;
3741 * Read and execute commands from an open file handle.
3743 * Returns true on success, error string or exception on failure (depending
3744 * on object's error ignore settings).
3746 * @param $fp Resource: File handle
3747 * @param $lineCallback Callback: Optional function called before reading each query
3748 * @param $resultCallback Callback: Optional function called for each MySQL result
3749 * @param string $fname Calling function name
3750 * @param $inputCallback Callback: Optional function called for each complete query sent
3751 * @return bool|string
3753 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3754 $fname = __METHOD__, $inputCallback = false )
3756 $cmd = '';
3758 while ( !feof( $fp ) ) {
3759 if ( $lineCallback ) {
3760 call_user_func( $lineCallback );
3763 $line = trim( fgets( $fp ) );
3765 if ( $line == '' ) {
3766 continue;
3769 if ( '-' == $line[0] && '-' == $line[1] ) {
3770 continue;
3773 if ( $cmd != '' ) {
3774 $cmd .= ' ';
3777 $done = $this->streamStatementEnd( $cmd, $line );
3779 $cmd .= "$line\n";
3781 if ( $done || feof( $fp ) ) {
3782 $cmd = $this->replaceVars( $cmd );
3784 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) || !$inputCallback ) {
3785 $res = $this->query( $cmd, $fname );
3787 if ( $resultCallback ) {
3788 call_user_func( $resultCallback, $res, $this );
3791 if ( false === $res ) {
3792 $err = $this->lastError();
3793 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3796 $cmd = '';
3800 return true;
3804 * Called by sourceStream() to check if we've reached a statement end
3806 * @param string $sql SQL assembled so far
3807 * @param string $newLine New line about to be added to $sql
3808 * @return Bool Whether $newLine contains end of the statement
3810 public function streamStatementEnd( &$sql, &$newLine ) {
3811 if ( $this->delimiter ) {
3812 $prev = $newLine;
3813 $newLine = preg_replace( '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
3814 if ( $newLine != $prev ) {
3815 return true;
3818 return false;
3822 * Database independent variable replacement. Replaces a set of variables
3823 * in an SQL statement with their contents as given by $this->getSchemaVars().
3825 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3827 * - '{$var}' should be used for text and is passed through the database's
3828 * addQuotes method.
3829 * - `{$var}` should be used for identifiers (eg: table and database names),
3830 * it is passed through the database's addIdentifierQuotes method which
3831 * can be overridden if the database uses something other than backticks.
3832 * - / *$var* / is just encoded, besides traditional table prefix and
3833 * table options its use should be avoided.
3835 * @param string $ins SQL statement to replace variables in
3836 * @return String The new SQL statement with variables replaced
3838 protected function replaceSchemaVars( $ins ) {
3839 $vars = $this->getSchemaVars();
3840 foreach ( $vars as $var => $value ) {
3841 // replace '{$var}'
3842 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
3843 // replace `{$var}`
3844 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
3845 // replace /*$var*/
3846 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ), $ins );
3848 return $ins;
3852 * Replace variables in sourced SQL
3854 * @param $ins string
3856 * @return string
3858 protected function replaceVars( $ins ) {
3859 $ins = $this->replaceSchemaVars( $ins );
3861 // Table prefixes
3862 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3863 array( $this, 'tableNameCallback' ), $ins );
3865 // Index names
3866 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
3867 array( $this, 'indexNameCallback' ), $ins );
3869 return $ins;
3873 * Get schema variables. If none have been set via setSchemaVars(), then
3874 * use some defaults from the current object.
3876 * @return array
3878 protected function getSchemaVars() {
3879 if ( $this->mSchemaVars ) {
3880 return $this->mSchemaVars;
3881 } else {
3882 return $this->getDefaultSchemaVars();
3887 * Get schema variables to use if none have been set via setSchemaVars().
3889 * Override this in derived classes to provide variables for tables.sql
3890 * and SQL patch files.
3892 * @return array
3894 protected function getDefaultSchemaVars() {
3895 return array();
3899 * Table name callback
3901 * @param $matches array
3903 * @return string
3905 protected function tableNameCallback( $matches ) {
3906 return $this->tableName( $matches[1] );
3910 * Index name callback
3912 * @param $matches array
3914 * @return string
3916 protected function indexNameCallback( $matches ) {
3917 return $this->indexName( $matches[1] );
3921 * Check to see if a named lock is available. This is non-blocking.
3923 * @param string $lockName name of lock to poll
3924 * @param string $method name of method calling us
3925 * @return Boolean
3926 * @since 1.20
3928 public function lockIsFree( $lockName, $method ) {
3929 return true;
3933 * Acquire a named lock
3935 * Abstracted from Filestore::lock() so child classes can implement for
3936 * their own needs.
3938 * @param string $lockName name of lock to aquire
3939 * @param string $method name of method calling us
3940 * @param $timeout Integer: timeout
3941 * @return Boolean
3943 public function lock( $lockName, $method, $timeout = 5 ) {
3944 return true;
3948 * Release a lock.
3950 * @param string $lockName Name of lock to release
3951 * @param string $method Name of method calling us
3953 * @return int Returns 1 if the lock was released, 0 if the lock was not established
3954 * by this thread (in which case the lock is not released), and NULL if the named
3955 * lock did not exist
3957 public function unlock( $lockName, $method ) {
3958 return true;
3962 * Lock specific tables
3964 * @param array $read of tables to lock for read access
3965 * @param array $write of tables to lock for write access
3966 * @param string $method name of caller
3967 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3969 * @return bool
3971 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3972 return true;
3976 * Unlock specific tables
3978 * @param string $method the caller
3980 * @return bool
3982 public function unlockTables( $method ) {
3983 return true;
3987 * Delete a table
3988 * @param $tableName string
3989 * @param $fName string
3990 * @return bool|ResultWrapper
3991 * @since 1.18
3993 public function dropTable( $tableName, $fName = __METHOD__ ) {
3994 if ( !$this->tableExists( $tableName, $fName ) ) {
3995 return false;
3997 $sql = "DROP TABLE " . $this->tableName( $tableName );
3998 if ( $this->cascadingDeletes() ) {
3999 $sql .= " CASCADE";
4001 return $this->query( $sql, $fName );
4005 * Get search engine class. All subclasses of this need to implement this
4006 * if they wish to use searching.
4008 * @return String
4010 public function getSearchEngine() {
4011 return 'SearchEngineDummy';
4015 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4016 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4017 * because "i" sorts after all numbers.
4019 * @return String
4021 public function getInfinity() {
4022 return 'infinity';
4026 * Encode an expiry time into the DBMS dependent format
4028 * @param string $expiry timestamp for expiry, or the 'infinity' string
4029 * @return String
4031 public function encodeExpiry( $expiry ) {
4032 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4033 ? $this->getInfinity()
4034 : $this->timestamp( $expiry );
4038 * Decode an expiry time into a DBMS independent format
4040 * @param string $expiry DB timestamp field value for expiry
4041 * @param $format integer: TS_* constant, defaults to TS_MW
4042 * @return String
4044 public function decodeExpiry( $expiry, $format = TS_MW ) {
4045 return ( $expiry == '' || $expiry == $this->getInfinity() )
4046 ? 'infinity'
4047 : wfTimestamp( $format, $expiry );
4051 * Allow or deny "big selects" for this session only. This is done by setting
4052 * the sql_big_selects session variable.
4054 * This is a MySQL-specific feature.
4056 * @param $value Mixed: true for allow, false for deny, or "default" to
4057 * restore the initial value
4059 public function setBigSelects( $value = true ) {
4060 // no-op
4064 * @since 1.19
4066 public function __toString() {
4067 return (string)$this->mConn;
4071 * Run a few simple sanity checks
4073 public function __destruct() {
4074 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
4075 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4077 if ( count( $this->mTrxIdleCallbacks ) || count( $this->mTrxPreCommitCallbacks ) ) {
4078 $callers = array();
4079 foreach ( $this->mTrxIdleCallbacks as $callbackInfo ) {
4080 $callers[] = $callbackInfo[1];
4083 $callers = implode( ', ', $callers );
4084 trigger_error( "DB transaction callbacks still pending (from $callers)." );