4 * @defgroup Database Database
6 * This file deals with database interface functions
7 * and query specifics/optimisations.
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
29 * Database abstraction object
32 abstract class DatabaseBase
implements IDatabase
{
33 /** Number of times to re-try an operation in case of deadlock */
34 const DEADLOCK_TRIES
= 4;
36 /** Minimum time to wait before retry, in microseconds */
37 const DEADLOCK_DELAY_MIN
= 500000;
39 /** Maximum time to wait before retry */
40 const DEADLOCK_DELAY_MAX
= 1500000;
42 protected $mLastQuery = '';
43 protected $mDoneWrites = false;
44 protected $mPHPError = false;
46 protected $mServer, $mUser, $mPassword, $mDBname;
48 /** @var BagOStuff APC cache */
51 /** @var resource Database connection */
52 protected $mConn = null;
53 protected $mOpened = false;
55 /** @var callable[] */
56 protected $mTrxIdleCallbacks = array();
57 /** @var callable[] */
58 protected $mTrxPreCommitCallbacks = array();
60 protected $mTablePrefix;
64 protected $mLBInfo = array();
65 protected $mDefaultBigSelects = null;
66 protected $mSchemaVars = false;
68 protected $mSessionVars = array();
70 protected $preparedArgs;
72 protected $htmlErrors;
74 protected $delimiter = ';';
77 * Either 1 if a transaction is active or 0 otherwise.
78 * The other Trx fields may not be meaningfull if this is 0.
82 protected $mTrxLevel = 0;
85 * Either a short hexidecimal string if a transaction is active or ""
88 * @see DatabaseBase::mTrxLevel
90 protected $mTrxShortId = '';
93 * The UNIX time that the transaction started. Callers can assume that if
94 * snapshot isolation is used, then the data is *at least* up to date to that
95 * point (possibly more up-to-date since the first SELECT defines the snapshot).
98 * @see DatabaseBase::mTrxLevel
100 private $mTrxTimestamp = null;
102 /** @var float Lag estimate at the time of BEGIN */
103 private $mTrxSlaveLag = null;
106 * Remembers the function name given for starting the most recent transaction via begin().
107 * Used to provide additional context for error reporting.
110 * @see DatabaseBase::mTrxLevel
112 private $mTrxFname = null;
115 * Record if possible write queries were done in the last transaction started
118 * @see DatabaseBase::mTrxLevel
120 private $mTrxDoneWrites = false;
123 * Record if the current transaction was started implicitly due to DBO_TRX being set.
126 * @see DatabaseBase::mTrxLevel
128 private $mTrxAutomatic = false;
131 * Array of levels of atomicity within transactions
135 private $mTrxAtomicLevels = array();
138 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
142 private $mTrxAutomaticAtomic = false;
145 * Track the write query callers of the current transaction
149 private $mTrxWriteCallers = array();
152 * Track the seconds spent in write queries for the current transaction
156 private $mTrxWriteDuration = 0.0;
158 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
159 private $lazyMasterHandle;
163 * @var resource File handle for upgrade
165 protected $fileHandle = null;
169 * @var string[] Process cache of VIEWs names in the database
171 protected $allViews = null;
173 /** @var TransactionProfiler */
174 protected $trxProfiler;
176 public function getServerInfo() {
177 return $this->getServerVersion();
181 * @return string Command delimiter used by this database engine
183 public function getDelimiter() {
184 return $this->delimiter
;
188 * Boolean, controls output of large amounts of debug information.
189 * @param bool|null $debug
190 * - true to enable debugging
191 * - false to disable debugging
192 * - omitted or null to do nothing
194 * @return bool|null Previous value of the flag
196 public function debug( $debug = null ) {
197 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
200 public function bufferResults( $buffer = null ) {
201 if ( is_null( $buffer ) ) {
202 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
204 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
209 * Turns on (false) or off (true) the automatic generation and sending
210 * of a "we're sorry, but there has been a database error" page on
211 * database errors. Default is on (false). When turned off, the
212 * code should use lastErrno() and lastError() to handle the
213 * situation as appropriate.
215 * Do not use this function outside of the Database classes.
217 * @param null|bool $ignoreErrors
218 * @return bool The previous value of the flag.
220 protected function ignoreErrors( $ignoreErrors = null ) {
221 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
224 public function trxLevel() {
225 return $this->mTrxLevel
;
228 public function trxTimestamp() {
229 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
232 public function tablePrefix( $prefix = null ) {
233 return wfSetVar( $this->mTablePrefix
, $prefix );
236 public function dbSchema( $schema = null ) {
237 return wfSetVar( $this->mSchema
, $schema );
241 * Set the filehandle to copy write statements to.
243 * @param resource $fh File handle
245 public function setFileHandle( $fh ) {
246 $this->fileHandle
= $fh;
249 public function getLBInfo( $name = null ) {
250 if ( is_null( $name ) ) {
251 return $this->mLBInfo
;
253 if ( array_key_exists( $name, $this->mLBInfo
) ) {
254 return $this->mLBInfo
[$name];
261 public function setLBInfo( $name, $value = null ) {
262 if ( is_null( $value ) ) {
263 $this->mLBInfo
= $name;
265 $this->mLBInfo
[$name] = $value;
270 * Set a lazy-connecting DB handle to the master DB (for replication status purposes)
272 * @param IDatabase $conn
275 public function setLazyMasterHandle( IDatabase
$conn ) {
276 $this->lazyMasterHandle
= $conn;
280 * @return IDatabase|null
281 * @see setLazyMasterHandle()
284 public function getLazyMasterHandle() {
285 return $this->lazyMasterHandle
;
289 * @return TransactionProfiler
291 protected function getTransactionProfiler() {
292 if ( !$this->trxProfiler
) {
293 $this->trxProfiler
= new TransactionProfiler();
296 return $this->trxProfiler
;
300 * @param TransactionProfiler $profiler
303 public function setTransactionProfiler( TransactionProfiler
$profiler ) {
304 $this->trxProfiler
= $profiler;
308 * Returns true if this database supports (and uses) cascading deletes
312 public function cascadingDeletes() {
317 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
321 public function cleanupTriggers() {
326 * Returns true if this database is strict about what can be put into an IP field.
327 * Specifically, it uses a NULL value instead of an empty string.
331 public function strictIPs() {
336 * Returns true if this database uses timestamps rather than integers
340 public function realTimestamps() {
344 public function implicitGroupby() {
348 public function implicitOrderby() {
353 * Returns true if this database can do a native search on IP columns
354 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
358 public function searchableIPs() {
363 * Returns true if this database can use functional indexes
367 public function functionalIndexes() {
371 public function lastQuery() {
372 return $this->mLastQuery
;
375 public function doneWrites() {
376 return (bool)$this->mDoneWrites
;
379 public function lastDoneWrites() {
380 return $this->mDoneWrites ?
: false;
383 public function writesPending() {
384 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
387 public function writesOrCallbacksPending() {
388 return $this->mTrxLevel
&& (
389 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
393 public function pendingWriteQueryDuration() {
394 return $this->mTrxLevel ?
$this->mTrxWriteDuration
: false;
397 public function pendingWriteCallers() {
398 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: array();
401 public function isOpen() {
402 return $this->mOpened
;
405 public function setFlag( $flag ) {
406 $this->mFlags |
= $flag;
409 public function clearFlag( $flag ) {
410 $this->mFlags
&= ~
$flag;
413 public function getFlag( $flag ) {
414 return !!( $this->mFlags
& $flag );
417 public function getProperty( $name ) {
421 public function getWikiID() {
422 if ( $this->mTablePrefix
) {
423 return "{$this->mDBname}-{$this->mTablePrefix}";
425 return $this->mDBname
;
430 * Return a path to the DBMS-specific SQL file if it exists,
431 * otherwise default SQL file
433 * @param string $filename
436 private function getSqlFilePath( $filename ) {
438 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
439 if ( file_exists( $dbmsSpecificFilePath ) ) {
440 return $dbmsSpecificFilePath;
442 return "$IP/maintenance/$filename";
447 * Return a path to the DBMS-specific schema file,
448 * otherwise default to tables.sql
452 public function getSchemaPath() {
453 return $this->getSqlFilePath( 'tables.sql' );
457 * Return a path to the DBMS-specific update key file,
458 * otherwise default to update-keys.sql
462 public function getUpdateKeysPath() {
463 return $this->getSqlFilePath( 'update-keys.sql' );
467 * Get information about an index into an object
468 * @param string $table Table name
469 * @param string $index Index name
470 * @param string $fname Calling function name
471 * @return mixed Database-specific index description class or false if the index does not exist
473 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
476 * Wrapper for addslashes()
478 * @param string $s String to be slashed.
479 * @return string Slashed string.
481 abstract function strencode( $s );
486 * FIXME: It is possible to construct a Database object with no associated
487 * connection object, by specifying no parameters to __construct(). This
488 * feature is deprecated and should be removed.
490 * DatabaseBase subclasses should not be constructed directly in external
491 * code. DatabaseBase::factory() should be used instead.
493 * @param array $params Parameters passed from DatabaseBase::factory()
495 function __construct( array $params ) {
496 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode;
498 $this->srvCache
= ObjectCache
::getLocalServerInstance( 'hash' );
500 $server = $params['host'];
501 $user = $params['user'];
502 $password = $params['password'];
503 $dbName = $params['dbname'];
504 $flags = $params['flags'];
505 $tablePrefix = $params['tablePrefix'];
506 $schema = $params['schema'];
507 $foreign = $params['foreign'];
509 $this->mFlags
= $flags;
510 if ( $this->mFlags
& DBO_DEFAULT
) {
511 if ( $wgCommandLineMode ) {
512 $this->mFlags
&= ~DBO_TRX
;
514 $this->mFlags |
= DBO_TRX
;
518 $this->mSessionVars
= $params['variables'];
520 /** Get the default table prefix*/
521 if ( $tablePrefix === 'get from global' ) {
522 $this->mTablePrefix
= $wgDBprefix;
524 $this->mTablePrefix
= $tablePrefix;
527 /** Get the database schema*/
528 if ( $schema === 'get from global' ) {
529 $this->mSchema
= $wgDBmwschema;
531 $this->mSchema
= $schema;
534 $this->mForeign
= $foreign;
536 if ( isset( $params['trxProfiler'] ) ) {
537 $this->trxProfiler
= $params['trxProfiler']; // override
541 $this->open( $server, $user, $password, $dbName );
546 * Called by serialize. Throw an exception when DB connection is serialized.
547 * This causes problems on some database engines because the connection is
548 * not restored on unserialize.
550 public function __sleep() {
551 throw new MWException( 'Database serialization may cause problems, since ' .
552 'the connection is not restored on wakeup.' );
556 * Given a DB type, construct the name of the appropriate child class of
557 * DatabaseBase. This is designed to replace all of the manual stuff like:
558 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
559 * as well as validate against the canonical list of DB types we have
561 * This factory function is mostly useful for when you need to connect to a
562 * database other than the MediaWiki default (such as for external auth,
563 * an extension, et cetera). Do not use this to connect to the MediaWiki
564 * database. Example uses in core:
565 * @see LoadBalancer::reallyOpenConnection()
566 * @see ForeignDBRepo::getMasterDB()
567 * @see WebInstallerDBConnect::execute()
571 * @param string $dbType A possible DB type
572 * @param array $p An array of options to pass to the constructor.
573 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
574 * @throws MWException If the database driver or extension cannot be found
575 * @return DatabaseBase|null DatabaseBase subclass or null
577 final public static function factory( $dbType, $p = array() ) {
578 $canonicalDBTypes = array(
579 'mysql' => array( 'mysqli', 'mysql' ),
580 'postgres' => array(),
587 $dbType = strtolower( $dbType );
588 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
589 $possibleDrivers = $canonicalDBTypes[$dbType];
590 if ( !empty( $p['driver'] ) ) {
591 if ( in_array( $p['driver'], $possibleDrivers ) ) {
592 $driver = $p['driver'];
594 throw new MWException( __METHOD__
.
595 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
598 foreach ( $possibleDrivers as $posDriver ) {
599 if ( extension_loaded( $posDriver ) ) {
600 $driver = $posDriver;
608 if ( $driver === false ) {
609 throw new MWException( __METHOD__
.
610 " no viable database extension found for type '$dbType'" );
613 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
614 // and everything else doesn't use a schema (e.g. null)
615 // Although postgres and oracle support schemas, we don't use them (yet)
616 // to maintain backwards compatibility
617 $defaultSchemas = array(
618 'mssql' => 'get from global',
621 $class = 'Database' . ucfirst( $driver );
622 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
623 // Resolve some defaults for b/c
624 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
625 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
626 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
627 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
628 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
629 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : array();
630 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global';
631 if ( !isset( $p['schema'] ) ) {
632 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : null;
634 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
636 return new $class( $p );
642 protected function installErrorHandler() {
643 $this->mPHPError
= false;
644 $this->htmlErrors
= ini_set( 'html_errors', '0' );
645 set_error_handler( array( $this, 'connectionErrorHandler' ) );
649 * @return bool|string
651 protected function restoreErrorHandler() {
652 restore_error_handler();
653 if ( $this->htmlErrors
!== false ) {
654 ini_set( 'html_errors', $this->htmlErrors
);
656 if ( $this->mPHPError
) {
657 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
658 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
668 * @param string $errstr
670 public function connectionErrorHandler( $errno, $errstr ) {
671 $this->mPHPError
= $errstr;
675 * Create a log context to pass to wfLogDBError or other logging functions.
677 * @param array $extras Additional data to add to context
680 protected function getLogContext( array $extras = array() ) {
683 'db_server' => $this->mServer
,
684 'db_name' => $this->mDBname
,
685 'db_user' => $this->mUser
,
691 public function close() {
692 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
693 throw new MWException( "Transaction idle callbacks still pending." );
695 if ( $this->mConn
) {
696 if ( $this->trxLevel() ) {
697 if ( !$this->mTrxAutomatic
) {
698 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
699 " performing implicit commit before closing connection!" );
702 $this->commit( __METHOD__
, 'flush' );
705 $closed = $this->closeConnection();
706 $this->mConn
= false;
710 $this->mOpened
= false;
716 * Make sure isOpen() returns true as a sanity check
718 * @throws DBUnexpectedError
720 protected function assertOpen() {
721 if ( !$this->isOpen() ) {
722 throw new DBUnexpectedError( $this, "DB connection was already closed." );
727 * Closes underlying database connection
729 * @return bool Whether connection was closed successfully
731 abstract protected function closeConnection();
733 function reportConnectionError( $error = 'Unknown error' ) {
734 $myError = $this->lastError();
740 throw new DBConnectionError( $this, $error );
744 * The DBMS-dependent part of query()
746 * @param string $sql SQL query.
747 * @return ResultWrapper|bool Result object to feed to fetchObject,
748 * fetchRow, ...; or false on failure
750 abstract protected function doQuery( $sql );
753 * Determine whether a query writes to the DB.
754 * Should return true if unsure.
759 protected function isWriteQuery( $sql ) {
760 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
764 * Determine whether a SQL statement is sensitive to isolation level.
765 * A SQL statement is considered transactable if its result could vary
766 * depending on the transaction isolation level. Operational commands
767 * such as 'SET' and 'SHOW' are not considered to be transactable.
772 protected function isTransactableQuery( $sql ) {
773 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
774 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
777 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
780 $this->mLastQuery
= $sql;
782 $isWriteQuery = $this->isWriteQuery( $sql );
783 if ( $isWriteQuery ) {
784 $reason = $this->getReadOnlyReason();
785 if ( $reason !== false ) {
786 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
788 # Set a flag indicating that writes have been done
789 $this->mDoneWrites
= microtime( true );
792 # Add a comment for easy SHOW PROCESSLIST interpretation
793 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
794 $userName = $wgUser->getName();
795 if ( mb_strlen( $userName ) > 15 ) {
796 $userName = mb_substr( $userName, 0, 15 ) . '...';
798 $userName = str_replace( '/', '', $userName );
803 // Add trace comment to the begin of the sql string, right after the operator.
804 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
805 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
807 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
) && $this->isTransactableQuery( $sql ) ) {
808 $this->begin( __METHOD__
. " ($fname)" );
809 $this->mTrxAutomatic
= true;
812 # Keep track of whether the transaction has write queries pending
813 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWriteQuery ) {
814 $this->mTrxDoneWrites
= true;
815 $this->getTransactionProfiler()->transactionWritingIn(
816 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
819 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
820 # generalizeSQL will probably cut down the query to reasonable
821 # logging size most of the time. The substr is really just a sanity check.
823 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
824 $totalProf = 'DatabaseBase::query-master';
826 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
827 $totalProf = 'DatabaseBase::query';
829 # Include query transaction state
830 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
832 $profiler = Profiler
::instance();
833 if ( !$profiler instanceof ProfilerStub
) {
834 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
835 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
838 if ( $this->debug() ) {
839 wfDebugLog( 'queries', sprintf( "%s: %s", $this->mDBname
, $commentedSql ) );
842 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
844 # Avoid fatals if close() was called
847 # Do the query and handle errors
848 $startTime = microtime( true );
849 $ret = $this->doQuery( $commentedSql );
850 $queryRuntime = microtime( true ) - $startTime;
851 # Log the query time and feed it into the DB trx profiler
852 $this->getTransactionProfiler()->recordQueryCompletion(
853 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
855 MWDebug
::queryTime( $queryId );
857 # Try reconnecting if the connection was lost
858 if ( false === $ret && $this->wasErrorReissuable() ) {
859 # Transaction is gone, like it or not
860 $hadTrx = $this->mTrxLevel
; // possible lost transaction
861 $this->mTrxLevel
= 0;
862 $this->mTrxIdleCallbacks
= array(); // bug 65263
863 $this->mTrxPreCommitCallbacks
= array(); // bug 65263
864 wfDebug( "Connection lost, reconnecting...\n" );
865 # Stash the last error values since ping() might clear them
866 $lastError = $this->lastError();
867 $lastErrno = $this->lastErrno();
868 if ( $this->ping() ) {
869 wfDebug( "Reconnected\n" );
870 $server = $this->getServer();
871 $msg = __METHOD__
. ": lost connection to $server; reconnected";
872 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
875 # Leave $ret as false and let an error be reported.
876 # Callers may catch the exception and continue to use the DB.
877 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
879 # Should be safe to silently retry (no trx and thus no callbacks)
880 $startTime = microtime( true );
881 $ret = $this->doQuery( $commentedSql );
882 $queryRuntime = microtime( true ) - $startTime;
883 # Log the query time and feed it into the DB trx profiler
884 $this->getTransactionProfiler()->recordQueryCompletion(
885 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
888 wfDebug( "Failed\n" );
892 if ( false === $ret ) {
893 $this->reportQueryError(
894 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
897 $res = $this->resultObject( $ret );
899 // Destroy profile sections in the opposite order to their creation
900 ScopedCallback
::consume( $queryProfSection );
901 ScopedCallback
::consume( $totalProfSection );
903 if ( $isWriteQuery && $this->mTrxLevel
) {
904 $this->mTrxWriteDuration +
= $queryRuntime;
905 $this->mTrxWriteCallers
[] = $fname;
911 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
912 if ( $this->ignoreErrors() ||
$tempIgnore ) {
913 wfDebug( "SQL ERROR (ignored): $error\n" );
915 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
917 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
918 $this->getLogContext( array(
919 'method' => __METHOD__
,
922 'sql1line' => $sql1line,
926 wfDebug( "SQL ERROR: " . $error . "\n" );
927 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
932 * Intended to be compatible with the PEAR::DB wrapper functions.
933 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
935 * ? = scalar value, quoted as necessary
936 * ! = raw SQL bit (a function for instance)
937 * & = filename; reads the file and inserts as a blob
938 * (we don't use this though...)
941 * @param string $func
945 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
946 /* MySQL doesn't support prepared statements (yet), so just
947 * pack up the query for reference. We'll manually replace
950 return array( 'query' => $sql, 'func' => $func );
954 * Free a prepared query, generated by prepare().
955 * @param string $prepared
957 protected function freePrepared( $prepared ) {
958 /* No-op by default */
962 * Execute a prepared query with the various arguments
963 * @param string $prepared The prepared sql
964 * @param mixed $args Either an array here, or put scalars as varargs
966 * @return ResultWrapper
968 public function execute( $prepared, $args = null ) {
969 if ( !is_array( $args ) ) {
971 $args = func_get_args();
972 array_shift( $args );
975 $sql = $this->fillPrepared( $prepared['query'], $args );
977 return $this->query( $sql, $prepared['func'] );
981 * For faking prepared SQL statements on DBs that don't support it directly.
983 * @param string $preparedQuery A 'preparable' SQL statement
984 * @param array $args Array of Arguments to fill it with
985 * @return string Executable SQL
987 public function fillPrepared( $preparedQuery, $args ) {
989 $this->preparedArgs
=& $args;
991 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
992 array( &$this, 'fillPreparedArg' ), $preparedQuery );
996 * preg_callback func for fillPrepared()
997 * The arguments should be in $this->preparedArgs and must not be touched
998 * while we're doing this.
1000 * @param array $matches
1001 * @throws DBUnexpectedError
1004 protected function fillPreparedArg( $matches ) {
1005 switch ( $matches[1] ) {
1014 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1016 switch ( $matches[1] ) {
1018 return $this->addQuotes( $arg );
1022 # return $this->addQuotes( file_get_contents( $arg ) );
1023 throw new DBUnexpectedError(
1025 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1028 throw new DBUnexpectedError(
1030 'Received invalid match. This should never happen!'
1035 public function freeResult( $res ) {
1038 public function selectField(
1039 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1041 if ( $var === '*' ) { // sanity
1042 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1045 if ( !is_array( $options ) ) {
1046 $options = array( $options );
1049 $options['LIMIT'] = 1;
1051 $res = $this->select( $table, $var, $cond, $fname, $options );
1052 if ( $res === false ||
!$this->numRows( $res ) ) {
1056 $row = $this->fetchRow( $res );
1058 if ( $row !== false ) {
1059 return reset( $row );
1065 public function selectFieldValues(
1066 $table, $var, $cond = '', $fname = __METHOD__
, $options = array(), $join_conds = array()
1068 if ( $var === '*' ) { // sanity
1069 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1072 if ( !is_array( $options ) ) {
1073 $options = array( $options );
1076 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1077 if ( $res === false ) {
1082 foreach ( $res as $row ) {
1083 $values[] = $row->$var;
1090 * Returns an optional USE INDEX clause to go after the table, and a
1091 * string to go at the end of the query.
1093 * @param array $options Associative array of options to be turned into
1094 * an SQL query, valid keys are listed in the function.
1096 * @see DatabaseBase::select()
1098 public function makeSelectOptions( $options ) {
1099 $preLimitTail = $postLimitTail = '';
1102 $noKeyOptions = array();
1104 foreach ( $options as $key => $option ) {
1105 if ( is_numeric( $key ) ) {
1106 $noKeyOptions[$option] = true;
1110 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1112 $preLimitTail .= $this->makeOrderBy( $options );
1114 // if (isset($options['LIMIT'])) {
1115 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1116 // isset($options['OFFSET']) ? $options['OFFSET']
1120 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1121 $postLimitTail .= ' FOR UPDATE';
1124 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1125 $postLimitTail .= ' LOCK IN SHARE MODE';
1128 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1129 $startOpts .= 'DISTINCT';
1132 # Various MySQL extensions
1133 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1134 $startOpts .= ' /*! STRAIGHT_JOIN */';
1137 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1138 $startOpts .= ' HIGH_PRIORITY';
1141 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1142 $startOpts .= ' SQL_BIG_RESULT';
1145 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1146 $startOpts .= ' SQL_BUFFER_RESULT';
1149 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1150 $startOpts .= ' SQL_SMALL_RESULT';
1153 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1154 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1157 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1158 $startOpts .= ' SQL_CACHE';
1161 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1162 $startOpts .= ' SQL_NO_CACHE';
1165 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1166 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1171 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1175 * Returns an optional GROUP BY with an optional HAVING
1177 * @param array $options Associative array of options
1179 * @see DatabaseBase::select()
1182 public function makeGroupByWithHaving( $options ) {
1184 if ( isset( $options['GROUP BY'] ) ) {
1185 $gb = is_array( $options['GROUP BY'] )
1186 ?
implode( ',', $options['GROUP BY'] )
1187 : $options['GROUP BY'];
1188 $sql .= ' GROUP BY ' . $gb;
1190 if ( isset( $options['HAVING'] ) ) {
1191 $having = is_array( $options['HAVING'] )
1192 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1193 : $options['HAVING'];
1194 $sql .= ' HAVING ' . $having;
1201 * Returns an optional ORDER BY
1203 * @param array $options Associative array of options
1205 * @see DatabaseBase::select()
1208 public function makeOrderBy( $options ) {
1209 if ( isset( $options['ORDER BY'] ) ) {
1210 $ob = is_array( $options['ORDER BY'] )
1211 ?
implode( ',', $options['ORDER BY'] )
1212 : $options['ORDER BY'];
1214 return ' ORDER BY ' . $ob;
1220 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1221 $options = array(), $join_conds = array() ) {
1222 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1224 return $this->query( $sql, $fname );
1227 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1228 $options = array(), $join_conds = array()
1230 if ( is_array( $vars ) ) {
1231 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1234 $options = (array)$options;
1235 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1236 ?
$options['USE INDEX']
1239 if ( is_array( $table ) ) {
1241 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1242 } elseif ( $table != '' ) {
1243 if ( $table[0] == ' ' ) {
1244 $from = ' FROM ' . $table;
1247 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1253 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1254 $this->makeSelectOptions( $options );
1256 if ( !empty( $conds ) ) {
1257 if ( is_array( $conds ) ) {
1258 $conds = $this->makeList( $conds, LIST_AND
);
1260 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1262 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1265 if ( isset( $options['LIMIT'] ) ) {
1266 $sql = $this->limitResult( $sql, $options['LIMIT'],
1267 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1269 $sql = "$sql $postLimitTail";
1271 if ( isset( $options['EXPLAIN'] ) ) {
1272 $sql = 'EXPLAIN ' . $sql;
1278 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1279 $options = array(), $join_conds = array()
1281 $options = (array)$options;
1282 $options['LIMIT'] = 1;
1283 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1285 if ( $res === false ) {
1289 if ( !$this->numRows( $res ) ) {
1293 $obj = $this->fetchObject( $res );
1298 public function estimateRowCount(
1299 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1302 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1305 $row = $this->fetchRow( $res );
1306 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1312 public function selectRowCount(
1313 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array(), $join_conds = array()
1316 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1317 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1320 $row = $this->fetchRow( $res );
1321 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1328 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1329 * It's only slightly flawed. Don't use for anything important.
1331 * @param string $sql A SQL Query
1335 protected static function generalizeSQL( $sql ) {
1336 # This does the same as the regexp below would do, but in such a way
1337 # as to avoid crashing php on some large strings.
1338 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1340 $sql = str_replace( "\\\\", '', $sql );
1341 $sql = str_replace( "\\'", '', $sql );
1342 $sql = str_replace( "\\\"", '', $sql );
1343 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1344 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1346 # All newlines, tabs, etc replaced by single space
1347 $sql = preg_replace( '/\s+/', ' ', $sql );
1350 # except the ones surrounded by characters, e.g. l10n
1351 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1352 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1357 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1358 $info = $this->fieldInfo( $table, $field );
1363 public function indexExists( $table, $index, $fname = __METHOD__
) {
1364 if ( !$this->tableExists( $table ) ) {
1368 $info = $this->indexInfo( $table, $index, $fname );
1369 if ( is_null( $info ) ) {
1372 return $info !== false;
1376 public function tableExists( $table, $fname = __METHOD__
) {
1377 $table = $this->tableName( $table );
1378 $old = $this->ignoreErrors( true );
1379 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1380 $this->ignoreErrors( $old );
1385 public function indexUnique( $table, $index ) {
1386 $indexInfo = $this->indexInfo( $table, $index );
1388 if ( !$indexInfo ) {
1392 return !$indexInfo[0]->Non_unique
;
1396 * Helper for DatabaseBase::insert().
1398 * @param array $options
1401 protected function makeInsertOptions( $options ) {
1402 return implode( ' ', $options );
1405 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
1406 # No rows to insert, easy just return now
1407 if ( !count( $a ) ) {
1411 $table = $this->tableName( $table );
1413 if ( !is_array( $options ) ) {
1414 $options = array( $options );
1418 if ( isset( $options['fileHandle'] ) ) {
1419 $fh = $options['fileHandle'];
1421 $options = $this->makeInsertOptions( $options );
1423 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1425 $keys = array_keys( $a[0] );
1428 $keys = array_keys( $a );
1431 $sql = 'INSERT ' . $options .
1432 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1436 foreach ( $a as $row ) {
1442 $sql .= '(' . $this->makeList( $row ) . ')';
1445 $sql .= '(' . $this->makeList( $a ) . ')';
1448 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1450 } elseif ( $fh !== null ) {
1454 return (bool)$this->query( $sql, $fname );
1458 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1460 * @param array $options
1463 protected function makeUpdateOptionsArray( $options ) {
1464 if ( !is_array( $options ) ) {
1465 $options = array( $options );
1470 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1471 $opts[] = $this->lowPriorityOption();
1474 if ( in_array( 'IGNORE', $options ) ) {
1482 * Make UPDATE options for the DatabaseBase::update function
1484 * @param array $options The options passed to DatabaseBase::update
1487 protected function makeUpdateOptions( $options ) {
1488 $opts = $this->makeUpdateOptionsArray( $options );
1490 return implode( ' ', $opts );
1493 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
1494 $table = $this->tableName( $table );
1495 $opts = $this->makeUpdateOptions( $options );
1496 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1498 if ( $conds !== array() && $conds !== '*' ) {
1499 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1502 return $this->query( $sql, $fname );
1505 public function makeList( $a, $mode = LIST_COMMA
) {
1506 if ( !is_array( $a ) ) {
1507 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1513 foreach ( $a as $field => $value ) {
1515 if ( $mode == LIST_AND
) {
1517 } elseif ( $mode == LIST_OR
) {
1526 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1527 $list .= "($value)";
1528 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1530 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1531 // Remove null from array to be handled separately if found
1532 $includeNull = false;
1533 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1534 $includeNull = true;
1535 unset( $value[$nullKey] );
1537 if ( count( $value ) == 0 && !$includeNull ) {
1538 throw new MWException( __METHOD__
. ": empty input for field $field" );
1539 } elseif ( count( $value ) == 0 ) {
1540 // only check if $field is null
1541 $list .= "$field IS NULL";
1543 // IN clause contains at least one valid element
1544 if ( $includeNull ) {
1545 // Group subconditions to ensure correct precedence
1548 if ( count( $value ) == 1 ) {
1549 // Special-case single values, as IN isn't terribly efficient
1550 // Don't necessarily assume the single key is 0; we don't
1551 // enforce linear numeric ordering on other arrays here.
1552 $value = array_values( $value );
1553 $list .= $field . " = " . $this->addQuotes( $value[0] );
1555 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1557 // if null present in array, append IS NULL
1558 if ( $includeNull ) {
1559 $list .= " OR $field IS NULL)";
1562 } elseif ( $value === null ) {
1563 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1564 $list .= "$field IS ";
1565 } elseif ( $mode == LIST_SET
) {
1566 $list .= "$field = ";
1570 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1571 $list .= "$field = ";
1573 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1580 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1583 foreach ( $data as $base => $sub ) {
1584 if ( count( $sub ) ) {
1585 $conds[] = $this->makeList(
1586 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1592 return $this->makeList( $conds, LIST_OR
);
1594 // Nothing to search for...
1600 * Return aggregated value alias
1602 * @param array $valuedata
1603 * @param string $valuename
1607 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1611 public function bitNot( $field ) {
1615 public function bitAnd( $fieldLeft, $fieldRight ) {
1616 return "($fieldLeft & $fieldRight)";
1619 public function bitOr( $fieldLeft, $fieldRight ) {
1620 return "($fieldLeft | $fieldRight)";
1623 public function buildConcat( $stringList ) {
1624 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1627 public function buildGroupConcatField(
1628 $delim, $table, $field, $conds = '', $join_conds = array()
1630 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1632 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
1635 public function selectDB( $db ) {
1636 # Stub. Shouldn't cause serious problems if it's not overridden, but
1637 # if your database engine supports a concept similar to MySQL's
1638 # databases you may as well.
1639 $this->mDBname
= $db;
1644 public function getDBname() {
1645 return $this->mDBname
;
1648 public function getServer() {
1649 return $this->mServer
;
1653 * Format a table name ready for use in constructing an SQL query
1655 * This does two important things: it quotes the table names to clean them up,
1656 * and it adds a table prefix if only given a table name with no quotes.
1658 * All functions of this object which require a table name call this function
1659 * themselves. Pass the canonical name to such functions. This is only needed
1660 * when calling query() directly.
1662 * @param string $name Database table name
1663 * @param string $format One of:
1664 * quoted - Automatically pass the table name through addIdentifierQuotes()
1665 * so that it can be used in a query.
1666 * raw - Do not add identifier quotes to the table name
1667 * @return string Full database name
1669 public function tableName( $name, $format = 'quoted' ) {
1670 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
1671 # Skip the entire process when we have a string quoted on both ends.
1672 # Note that we check the end so that we will still quote any use of
1673 # use of `database`.table. But won't break things if someone wants
1674 # to query a database table with a dot in the name.
1675 if ( $this->isQuotedIdentifier( $name ) ) {
1679 # Lets test for any bits of text that should never show up in a table
1680 # name. Basically anything like JOIN or ON which are actually part of
1681 # SQL queries, but may end up inside of the table value to combine
1682 # sql. Such as how the API is doing.
1683 # Note that we use a whitespace test rather than a \b test to avoid
1684 # any remote case where a word like on may be inside of a table name
1685 # surrounded by symbols which may be considered word breaks.
1686 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1690 # Split database and table into proper variables.
1691 # We reverse the explode so that database.table and table both output
1692 # the correct table.
1693 $dbDetails = explode( '.', $name, 3 );
1694 if ( count( $dbDetails ) == 3 ) {
1695 list( $database, $schema, $table ) = $dbDetails;
1696 # We don't want any prefix added in this case
1698 } elseif ( count( $dbDetails ) == 2 ) {
1699 list( $database, $table ) = $dbDetails;
1700 # We don't want any prefix added in this case
1701 # In dbs that support it, $database may actually be the schema
1702 # but that doesn't affect any of the functionality here
1706 list( $table ) = $dbDetails;
1707 if ( $wgSharedDB !== null # We have a shared database
1708 && $this->mForeign
== false # We're not working on a foreign database
1709 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
1710 && in_array( $table, $wgSharedTables ) # A shared table is selected
1712 $database = $wgSharedDB;
1713 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
1714 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
1717 $schema = $this->mSchema
; # Default schema
1718 $prefix = $this->mTablePrefix
; # Default prefix
1722 # Quote $table and apply the prefix if not quoted.
1723 # $tableName might be empty if this is called from Database::replaceVars()
1724 $tableName = "{$prefix}{$table}";
1725 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
1726 $tableName = $this->addIdentifierQuotes( $tableName );
1729 # Quote $schema and merge it with the table name if needed
1730 if ( strlen( $schema ) ) {
1731 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1732 $schema = $this->addIdentifierQuotes( $schema );
1734 $tableName = $schema . '.' . $tableName;
1737 # Quote $database and merge it with the table name if needed
1738 if ( $database !== null ) {
1739 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1740 $database = $this->addIdentifierQuotes( $database );
1742 $tableName = $database . '.' . $tableName;
1749 * Fetch a number of table names into an array
1750 * This is handy when you need to construct SQL for joins
1753 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1754 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1755 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1759 public function tableNames() {
1760 $inArray = func_get_args();
1763 foreach ( $inArray as $name ) {
1764 $retVal[$name] = $this->tableName( $name );
1771 * Fetch a number of table names into an zero-indexed numerical array
1772 * This is handy when you need to construct SQL for joins
1775 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1776 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1777 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1781 public function tableNamesN() {
1782 $inArray = func_get_args();
1785 foreach ( $inArray as $name ) {
1786 $retVal[] = $this->tableName( $name );
1793 * Get an aliased table name
1794 * e.g. tableName AS newTableName
1796 * @param string $name Table name, see tableName()
1797 * @param string|bool $alias Alias (optional)
1798 * @return string SQL name for aliased table. Will not alias a table to its own name
1800 public function tableNameWithAlias( $name, $alias = false ) {
1801 if ( !$alias ||
$alias == $name ) {
1802 return $this->tableName( $name );
1804 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1809 * Gets an array of aliased table names
1811 * @param array $tables Array( [alias] => table )
1812 * @return string[] See tableNameWithAlias()
1814 public function tableNamesWithAlias( $tables ) {
1816 foreach ( $tables as $alias => $table ) {
1817 if ( is_numeric( $alias ) ) {
1820 $retval[] = $this->tableNameWithAlias( $table, $alias );
1827 * Get an aliased field name
1828 * e.g. fieldName AS newFieldName
1830 * @param string $name Field name
1831 * @param string|bool $alias Alias (optional)
1832 * @return string SQL name for aliased field. Will not alias a field to its own name
1834 public function fieldNameWithAlias( $name, $alias = false ) {
1835 if ( !$alias ||
(string)$alias === (string)$name ) {
1838 return $name . ' AS ' . $alias; // PostgreSQL needs AS
1843 * Gets an array of aliased field names
1845 * @param array $fields Array( [alias] => field )
1846 * @return string[] See fieldNameWithAlias()
1848 public function fieldNamesWithAlias( $fields ) {
1850 foreach ( $fields as $alias => $field ) {
1851 if ( is_numeric( $alias ) ) {
1854 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1861 * Get the aliased table name clause for a FROM clause
1862 * which might have a JOIN and/or USE INDEX clause
1864 * @param array $tables ( [alias] => table )
1865 * @param array $use_index Same as for select()
1866 * @param array $join_conds Same as for select()
1869 protected function tableNamesWithUseIndexOrJOIN(
1870 $tables, $use_index = array(), $join_conds = array()
1874 $use_index = (array)$use_index;
1875 $join_conds = (array)$join_conds;
1877 foreach ( $tables as $alias => $table ) {
1878 if ( !is_string( $alias ) ) {
1879 // No alias? Set it equal to the table name
1882 // Is there a JOIN clause for this table?
1883 if ( isset( $join_conds[$alias] ) ) {
1884 list( $joinType, $conds ) = $join_conds[$alias];
1885 $tableClause = $joinType;
1886 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1887 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1888 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1890 $tableClause .= ' ' . $use;
1893 $on = $this->makeList( (array)$conds, LIST_AND
);
1895 $tableClause .= ' ON (' . $on . ')';
1898 $retJOIN[] = $tableClause;
1899 } elseif ( isset( $use_index[$alias] ) ) {
1900 // Is there an INDEX clause for this table?
1901 $tableClause = $this->tableNameWithAlias( $table, $alias );
1902 $tableClause .= ' ' . $this->useIndexClause(
1903 implode( ',', (array)$use_index[$alias] )
1906 $ret[] = $tableClause;
1908 $tableClause = $this->tableNameWithAlias( $table, $alias );
1910 $ret[] = $tableClause;
1914 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1915 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1916 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1918 // Compile our final table clause
1919 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
1923 * Get the name of an index in a given table.
1925 * @protected Don't use outside of DatabaseBase and childs
1926 * @param string $index
1929 public function indexName( $index ) {
1930 // @FIXME: Make this protected once we move away from PHP 5.3
1931 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
1933 // Backwards-compatibility hack
1935 'ar_usertext_timestamp' => 'usertext_timestamp',
1936 'un_user_id' => 'user_id',
1937 'un_user_ip' => 'user_ip',
1940 if ( isset( $renamed[$index] ) ) {
1941 return $renamed[$index];
1947 public function addQuotes( $s ) {
1948 if ( $s instanceof Blob
) {
1951 if ( $s === null ) {
1954 # This will also quote numeric values. This should be harmless,
1955 # and protects against weird problems that occur when they really
1956 # _are_ strings such as article titles and string->number->string
1957 # conversion is not 1:1.
1958 return "'" . $this->strencode( $s ) . "'";
1963 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1964 * MySQL uses `backticks` while basically everything else uses double quotes.
1965 * Since MySQL is the odd one out here the double quotes are our generic
1966 * and we implement backticks in DatabaseMysql.
1971 public function addIdentifierQuotes( $s ) {
1972 return '"' . str_replace( '"', '""', $s ) . '"';
1976 * Returns if the given identifier looks quoted or not according to
1977 * the database convention for quoting identifiers .
1979 * @param string $name
1982 public function isQuotedIdentifier( $name ) {
1983 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
1990 protected function escapeLikeInternal( $s ) {
1991 return addcslashes( $s, '\%_' );
1994 public function buildLike() {
1995 $params = func_get_args();
1997 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1998 $params = $params[0];
2003 foreach ( $params as $value ) {
2004 if ( $value instanceof LikeMatch
) {
2005 $s .= $value->toString();
2007 $s .= $this->escapeLikeInternal( $value );
2011 return " LIKE {$this->addQuotes( $s )} ";
2014 public function anyChar() {
2015 return new LikeMatch( '_' );
2018 public function anyString() {
2019 return new LikeMatch( '%' );
2022 public function nextSequenceValue( $seqName ) {
2027 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2028 * is only needed because a) MySQL must be as efficient as possible due to
2029 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2030 * which index to pick. Anyway, other databases might have different
2031 * indexes on a given table. So don't bother overriding this unless you're
2033 * @param string $index
2036 public function useIndexClause( $index ) {
2040 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2041 $quotedTable = $this->tableName( $table );
2043 if ( count( $rows ) == 0 ) {
2048 if ( !is_array( reset( $rows ) ) ) {
2049 $rows = array( $rows );
2052 // @FXIME: this is not atomic, but a trx would break affectedRows()
2053 foreach ( $rows as $row ) {
2054 # Delete rows which collide
2055 if ( $uniqueIndexes ) {
2056 $sql = "DELETE FROM $quotedTable WHERE ";
2058 foreach ( $uniqueIndexes as $index ) {
2065 if ( is_array( $index ) ) {
2067 foreach ( $index as $col ) {
2073 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2076 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2080 $this->query( $sql, $fname );
2083 # Now insert the row
2084 $this->insert( $table, $row, $fname );
2089 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2092 * @param string $table Table name
2093 * @param array|string $rows Row(s) to insert
2094 * @param string $fname Caller function name
2096 * @return ResultWrapper
2098 protected function nativeReplace( $table, $rows, $fname ) {
2099 $table = $this->tableName( $table );
2102 if ( !is_array( reset( $rows ) ) ) {
2103 $rows = array( $rows );
2106 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2109 foreach ( $rows as $row ) {
2116 $sql .= '(' . $this->makeList( $row ) . ')';
2119 return $this->query( $sql, $fname );
2122 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2125 if ( !count( $rows ) ) {
2126 return true; // nothing to do
2129 if ( !is_array( reset( $rows ) ) ) {
2130 $rows = array( $rows );
2133 if ( count( $uniqueIndexes ) ) {
2134 $clauses = array(); // list WHERE clauses that each identify a single row
2135 foreach ( $rows as $row ) {
2136 foreach ( $uniqueIndexes as $index ) {
2137 $index = is_array( $index ) ?
$index : array( $index ); // columns
2138 $rowKey = array(); // unique key to this row
2139 foreach ( $index as $column ) {
2140 $rowKey[$column] = $row[$column];
2142 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2145 $where = array( $this->makeList( $clauses, LIST_OR
) );
2150 $useTrx = !$this->mTrxLevel
;
2152 $this->begin( $fname );
2155 # Update any existing conflicting row(s)
2156 if ( $where !== false ) {
2157 $ok = $this->update( $table, $set, $where, $fname );
2161 # Now insert any non-conflicting row(s)
2162 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2163 } catch ( Exception
$e ) {
2165 $this->rollback( $fname );
2170 $this->commit( $fname );
2176 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2180 throw new DBUnexpectedError( $this,
2181 'DatabaseBase::deleteJoin() called with empty $conds' );
2184 $delTable = $this->tableName( $delTable );
2185 $joinTable = $this->tableName( $joinTable );
2186 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2187 if ( $conds != '*' ) {
2188 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2192 $this->query( $sql, $fname );
2196 * Returns the size of a text field, or -1 for "unlimited"
2198 * @param string $table
2199 * @param string $field
2202 public function textFieldSize( $table, $field ) {
2203 $table = $this->tableName( $table );
2204 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2205 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2206 $row = $this->fetchObject( $res );
2210 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2220 * A string to insert into queries to show that they're low-priority, like
2221 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2222 * string and nothing bad should happen.
2224 * @return string Returns the text of the low priority option if it is
2225 * supported, or a blank string otherwise
2227 public function lowPriorityOption() {
2231 public function delete( $table, $conds, $fname = __METHOD__
) {
2233 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2236 $table = $this->tableName( $table );
2237 $sql = "DELETE FROM $table";
2239 if ( $conds != '*' ) {
2240 if ( is_array( $conds ) ) {
2241 $conds = $this->makeList( $conds, LIST_AND
);
2243 $sql .= ' WHERE ' . $conds;
2246 return $this->query( $sql, $fname );
2249 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2250 $fname = __METHOD__
,
2251 $insertOptions = array(), $selectOptions = array()
2253 $destTable = $this->tableName( $destTable );
2255 if ( !is_array( $insertOptions ) ) {
2256 $insertOptions = array( $insertOptions );
2259 $insertOptions = $this->makeInsertOptions( $insertOptions );
2261 if ( !is_array( $selectOptions ) ) {
2262 $selectOptions = array( $selectOptions );
2265 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2267 if ( is_array( $srcTable ) ) {
2268 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2270 $srcTable = $this->tableName( $srcTable );
2273 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2274 " SELECT $startOpts " . implode( ',', $varMap ) .
2275 " FROM $srcTable $useIndex ";
2277 if ( $conds != '*' ) {
2278 if ( is_array( $conds ) ) {
2279 $conds = $this->makeList( $conds, LIST_AND
);
2281 $sql .= " WHERE $conds";
2284 $sql .= " $tailOpts";
2286 return $this->query( $sql, $fname );
2290 * Construct a LIMIT query with optional offset. This is used for query
2291 * pages. The SQL should be adjusted so that only the first $limit rows
2292 * are returned. If $offset is provided as well, then the first $offset
2293 * rows should be discarded, and the next $limit rows should be returned.
2294 * If the result of the query is not ordered, then the rows to be returned
2295 * are theoretically arbitrary.
2297 * $sql is expected to be a SELECT, if that makes a difference.
2299 * The version provided by default works in MySQL and SQLite. It will very
2300 * likely need to be overridden for most other DBMSes.
2302 * @param string $sql SQL query we will append the limit too
2303 * @param int $limit The SQL limit
2304 * @param int|bool $offset The SQL offset (default false)
2305 * @throws DBUnexpectedError
2308 public function limitResult( $sql, $limit, $offset = false ) {
2309 if ( !is_numeric( $limit ) ) {
2310 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2313 return "$sql LIMIT "
2314 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2318 public function unionSupportsOrderAndLimit() {
2319 return true; // True for almost every DB supported
2322 public function unionQueries( $sqls, $all ) {
2323 $glue = $all ?
') UNION ALL (' : ') UNION (';
2325 return '(' . implode( $glue, $sqls ) . ')';
2328 public function conditional( $cond, $trueVal, $falseVal ) {
2329 if ( is_array( $cond ) ) {
2330 $cond = $this->makeList( $cond, LIST_AND
);
2333 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2336 public function strreplace( $orig, $old, $new ) {
2337 return "REPLACE({$orig}, {$old}, {$new})";
2340 public function getServerUptime() {
2344 public function wasDeadlock() {
2348 public function wasLockTimeout() {
2352 public function wasErrorReissuable() {
2356 public function wasReadOnlyError() {
2361 * Determines if the given query error was a connection drop
2364 * @param integer|string $errno
2367 public function wasConnectionError( $errno ) {
2372 * Perform a deadlock-prone transaction.
2374 * This function invokes a callback function to perform a set of write
2375 * queries. If a deadlock occurs during the processing, the transaction
2376 * will be rolled back and the callback function will be called again.
2379 * $dbw->deadlockLoop( callback, ... );
2381 * Extra arguments are passed through to the specified callback function.
2383 * Returns whatever the callback function returned on its successful,
2384 * iteration, or false on error, for example if the retry limit was
2387 * @throws DBUnexpectedError
2390 public function deadlockLoop() {
2391 $args = func_get_args();
2392 $function = array_shift( $args );
2393 $tries = self
::DEADLOCK_TRIES
;
2395 $this->begin( __METHOD__
);
2398 /** @var Exception $e */
2402 $retVal = call_user_func_array( $function, $args );
2404 } catch ( DBQueryError
$e ) {
2405 if ( $this->wasDeadlock() ) {
2406 // Retry after a randomized delay
2407 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2409 // Throw the error back up
2413 } while ( --$tries > 0 );
2415 if ( $tries <= 0 ) {
2416 // Too many deadlocks; give up
2417 $this->rollback( __METHOD__
);
2420 $this->commit( __METHOD__
);
2426 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2427 # Real waits are implemented in the subclass.
2431 public function getSlavePos() {
2436 public function getMasterPos() {
2441 final public function onTransactionIdle( $callback ) {
2442 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
2443 if ( !$this->mTrxLevel
) {
2444 $this->runOnTransactionIdleCallbacks();
2448 final public function onTransactionPreCommitOrIdle( $callback ) {
2449 if ( $this->mTrxLevel
) {
2450 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
2452 $this->onTransactionIdle( $callback ); // this will trigger immediately
2457 * Actually any "on transaction idle" callbacks.
2461 protected function runOnTransactionIdleCallbacks() {
2462 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2464 $e = $ePrior = null; // last exception
2465 do { // callbacks may add callbacks :)
2466 $callbacks = $this->mTrxIdleCallbacks
;
2467 $this->mTrxIdleCallbacks
= array(); // recursion guard
2468 foreach ( $callbacks as $callback ) {
2470 list( $phpCallback ) = $callback;
2471 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2472 call_user_func( $phpCallback );
2474 $this->setFlag( DBO_TRX
); // restore automatic begin()
2476 $this->clearFlag( DBO_TRX
); // restore auto-commit
2478 } catch ( Exception
$e ) {
2480 MWExceptionHandler
::logException( $ePrior );
2483 // Some callbacks may use startAtomic/endAtomic, so make sure
2484 // their transactions are ended so other callbacks don't fail
2485 if ( $this->trxLevel() ) {
2486 $this->rollback( __METHOD__
);
2490 } while ( count( $this->mTrxIdleCallbacks
) );
2492 if ( $e instanceof Exception
) {
2493 throw $e; // re-throw any last exception
2498 * Actually any "on transaction pre-commit" callbacks.
2502 protected function runOnTransactionPreCommitCallbacks() {
2503 $e = $ePrior = null; // last exception
2504 do { // callbacks may add callbacks :)
2505 $callbacks = $this->mTrxPreCommitCallbacks
;
2506 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
2507 foreach ( $callbacks as $callback ) {
2509 list( $phpCallback ) = $callback;
2510 call_user_func( $phpCallback );
2511 } catch ( Exception
$e ) {
2513 MWExceptionHandler
::logException( $ePrior );
2518 } while ( count( $this->mTrxPreCommitCallbacks
) );
2520 if ( $e instanceof Exception
) {
2521 throw $e; // re-throw any last exception
2525 final public function startAtomic( $fname = __METHOD__
) {
2526 if ( !$this->mTrxLevel
) {
2527 $this->begin( $fname );
2528 $this->mTrxAutomatic
= true;
2529 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2530 // in all changes being in one transaction to keep requests transactional.
2531 if ( !$this->getFlag( DBO_TRX
) ) {
2532 $this->mTrxAutomaticAtomic
= true;
2536 $this->mTrxAtomicLevels
[] = $fname;
2539 final public function endAtomic( $fname = __METHOD__
) {
2540 if ( !$this->mTrxLevel
) {
2541 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
2543 if ( !$this->mTrxAtomicLevels ||
2544 array_pop( $this->mTrxAtomicLevels
) !== $fname
2546 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
2549 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2550 $this->commit( $fname, 'flush' );
2554 final public function doAtomicSection( $fname, $callback ) {
2555 if ( !is_callable( $callback ) ) {
2556 throw new UnexpectedValueException( "Invalid callback." );
2559 $this->startAtomic( $fname );
2561 call_user_func_array( $callback, array( $this, $fname ) );
2562 } catch ( Exception
$e ) {
2563 $this->rollback( $fname );
2566 $this->endAtomic( $fname );
2569 final public function begin( $fname = __METHOD__
) {
2570 if ( $this->mTrxLevel
) { // implicit commit
2571 if ( $this->mTrxAtomicLevels
) {
2572 // If the current transaction was an automatic atomic one, then we definitely have
2573 // a problem. Same if there is any unclosed atomic level.
2574 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2575 throw new DBUnexpectedError(
2577 "Got explicit BEGIN from $fname while atomic section(s) $levels are open."
2579 } elseif ( !$this->mTrxAutomatic
) {
2580 // We want to warn about inadvertently nested begin/commit pairs, but not about
2581 // auto-committing implicit transactions that were started by query() via DBO_TRX
2582 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
2583 " performing implicit commit!";
2586 $this->getLogContext( array(
2587 'method' => __METHOD__
,
2592 // if the transaction was automatic and has done write operations
2593 if ( $this->mTrxDoneWrites
) {
2594 wfDebug( "$fname: Automatic transaction with writes in progress" .
2595 " (from {$this->mTrxFname}), performing implicit commit!\n"
2600 $this->runOnTransactionPreCommitCallbacks();
2601 $writeTime = $this->pendingWriteQueryDuration();
2602 $this->doCommit( $fname );
2603 if ( $this->mTrxDoneWrites
) {
2604 $this->mDoneWrites
= microtime( true );
2605 $this->getTransactionProfiler()->transactionWritingOut(
2606 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2608 $this->runOnTransactionIdleCallbacks();
2611 # Avoid fatals if close() was called
2612 $this->assertOpen();
2614 $this->doBegin( $fname );
2615 $this->mTrxTimestamp
= microtime( true );
2616 $this->mTrxFname
= $fname;
2617 $this->mTrxDoneWrites
= false;
2618 $this->mTrxAutomatic
= false;
2619 $this->mTrxAutomaticAtomic
= false;
2620 $this->mTrxAtomicLevels
= array();
2621 $this->mTrxIdleCallbacks
= array();
2622 $this->mTrxPreCommitCallbacks
= array();
2623 $this->mTrxShortId
= wfRandomString( 12 );
2624 $this->mTrxWriteDuration
= 0.0;
2625 $this->mTrxWriteCallers
= array();
2626 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2627 // Get an estimate of the slave lag before then, treating estimate staleness
2628 // as lag itself just to be safe
2629 $status = $this->getApproximateLagStatus();
2630 $this->mTrxSlaveLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2634 * Issues the BEGIN command to the database server.
2636 * @see DatabaseBase::begin()
2637 * @param string $fname
2639 protected function doBegin( $fname ) {
2640 $this->query( 'BEGIN', $fname );
2641 $this->mTrxLevel
= 1;
2644 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2645 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2646 // There are still atomic sections open. This cannot be ignored
2647 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2648 throw new DBUnexpectedError(
2650 "Got COMMIT while atomic sections $levels are still open"
2654 if ( $flush === 'flush' ) {
2655 if ( !$this->mTrxLevel
) {
2656 return; // nothing to do
2657 } elseif ( !$this->mTrxAutomatic
) {
2658 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
2661 if ( !$this->mTrxLevel
) {
2662 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
2663 return; // nothing to do
2664 } elseif ( $this->mTrxAutomatic
) {
2665 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
2669 # Avoid fatals if close() was called
2670 $this->assertOpen();
2672 $this->runOnTransactionPreCommitCallbacks();
2673 $writeTime = $this->pendingWriteQueryDuration();
2674 $this->doCommit( $fname );
2675 if ( $this->mTrxDoneWrites
) {
2676 $this->mDoneWrites
= microtime( true );
2677 $this->getTransactionProfiler()->transactionWritingOut(
2678 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2680 $this->runOnTransactionIdleCallbacks();
2684 * Issues the COMMIT command to the database server.
2686 * @see DatabaseBase::commit()
2687 * @param string $fname
2689 protected function doCommit( $fname ) {
2690 if ( $this->mTrxLevel
) {
2691 $this->query( 'COMMIT', $fname );
2692 $this->mTrxLevel
= 0;
2696 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2697 if ( $flush !== 'flush' ) {
2698 if ( !$this->mTrxLevel
) {
2699 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
2700 return; // nothing to do
2703 if ( !$this->mTrxLevel
) {
2704 return; // nothing to do
2708 # Avoid fatals if close() was called
2709 $this->assertOpen();
2711 $this->doRollback( $fname );
2712 $this->mTrxIdleCallbacks
= array(); // cancel
2713 $this->mTrxPreCommitCallbacks
= array(); // cancel
2714 $this->mTrxAtomicLevels
= array();
2715 if ( $this->mTrxDoneWrites
) {
2716 $this->getTransactionProfiler()->transactionWritingOut(
2717 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
2722 * Issues the ROLLBACK command to the database server.
2724 * @see DatabaseBase::rollback()
2725 * @param string $fname
2727 protected function doRollback( $fname ) {
2728 if ( $this->mTrxLevel
) {
2729 $this->query( 'ROLLBACK', $fname, true );
2730 $this->mTrxLevel
= 0;
2735 * Creates a new table with structure copied from existing table
2736 * Note that unlike most database abstraction functions, this function does not
2737 * automatically append database prefix, because it works at a lower
2738 * abstraction level.
2739 * The table names passed to this function shall not be quoted (this
2740 * function calls addIdentifierQuotes when needed).
2742 * @param string $oldName Name of table whose structure should be copied
2743 * @param string $newName Name of table to be created
2744 * @param bool $temporary Whether the new table should be temporary
2745 * @param string $fname Calling function name
2746 * @throws MWException
2747 * @return bool True if operation was successful
2749 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
2752 throw new MWException(
2753 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2756 function listTables( $prefix = null, $fname = __METHOD__
) {
2757 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2761 * Reset the views process cache set by listViews()
2764 final public function clearViewsCache() {
2765 $this->allViews
= null;
2769 * Lists all the VIEWs in the database
2771 * For caching purposes the list of all views should be stored in
2772 * $this->allViews. The process cache can be cleared with clearViewsCache()
2774 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
2775 * @param string $fname Name of calling function
2776 * @throws MWException
2780 public function listViews( $prefix = null, $fname = __METHOD__
) {
2781 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
2785 * Differentiates between a TABLE and a VIEW
2787 * @param string $name Name of the database-structure to test.
2788 * @throws MWException
2792 public function isView( $name ) {
2793 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
2796 public function timestamp( $ts = 0 ) {
2797 return wfTimestamp( TS_MW
, $ts );
2800 public function timestampOrNull( $ts = null ) {
2801 if ( is_null( $ts ) ) {
2804 return $this->timestamp( $ts );
2809 * Take the result from a query, and wrap it in a ResultWrapper if
2810 * necessary. Boolean values are passed through as is, to indicate success
2811 * of write queries or failure.
2813 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2814 * resource, and it was necessary to call this function to convert it to
2815 * a wrapper. Nowadays, raw database objects are never exposed to external
2816 * callers, so this is unnecessary in external code.
2818 * @param bool|ResultWrapper|resource|object $result
2819 * @return bool|ResultWrapper
2821 protected function resultObject( $result ) {
2824 } elseif ( $result instanceof ResultWrapper
) {
2826 } elseif ( $result === true ) {
2827 // Successful write query
2830 return new ResultWrapper( $this, $result );
2834 public function ping() {
2835 # Stub. Not essential to override.
2839 public function getSessionLagStatus() {
2840 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
2844 * Get the slave lag when the current transaction started
2846 * This is useful when transactions might use snapshot isolation
2847 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
2848 * is this lag plus transaction duration. If they don't, it is still
2849 * safe to be pessimistic. This returns null if there is no transaction.
2851 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
2854 public function getTransactionLagStatus() {
2855 return $this->mTrxLevel
2856 ?
array( 'lag' => $this->mTrxSlaveLag
, 'since' => $this->trxTimestamp() )
2861 * Get a slave lag estimate for this server
2863 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
2866 public function getApproximateLagStatus() {
2868 'lag' => $this->getLBInfo( 'slave' ) ?
$this->getLag() : 0,
2869 'since' => microtime( true )
2874 * Merge the result of getSessionLagStatus() for several DBs
2875 * using the most pessimistic values to estimate the lag of
2876 * any data derived from them in combination
2878 * This is information is useful for caching modules
2880 * @see WANObjectCache::set()
2881 * @see WANObjectCache::getWithSetCallback()
2883 * @param IDatabase $db1
2884 * @param IDatabase ...
2885 * @return array Map of values:
2886 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
2887 * - since: oldest UNIX timestamp of any of the DB lag estimates
2888 * - pending: whether any of the DBs have uncommitted changes
2891 public static function getCacheSetOptions( IDatabase
$db1 ) {
2892 $res = array( 'lag' => 0, 'since' => INF
, 'pending' => false );
2893 foreach ( func_get_args() as $db ) {
2894 /** @var IDatabase $db */
2895 $status = $db->getSessionLagStatus();
2896 if ( $status['lag'] === false ) {
2897 $res['lag'] = false;
2898 } elseif ( $res['lag'] !== false ) {
2899 $res['lag'] = max( $res['lag'], $status['lag'] );
2901 $res['since'] = min( $res['since'], $status['since'] );
2902 $res['pending'] = $res['pending'] ?
: $db->writesPending();
2908 public function getLag() {
2912 function maxListLen() {
2916 public function encodeBlob( $b ) {
2920 public function decodeBlob( $b ) {
2921 if ( $b instanceof Blob
) {
2927 public function setSessionOptions( array $options ) {
2931 * Read and execute SQL commands from a file.
2933 * Returns true on success, error string or exception on failure (depending
2934 * on object's error ignore settings).
2936 * @param string $filename File name to open
2937 * @param bool|callable $lineCallback Optional function called before reading each line
2938 * @param bool|callable $resultCallback Optional function called for each MySQL result
2939 * @param bool|string $fname Calling function name or false if name should be
2940 * generated dynamically using $filename
2941 * @param bool|callable $inputCallback Optional function called for each
2942 * complete line sent
2943 * @throws Exception|MWException
2944 * @return bool|string
2946 public function sourceFile(
2947 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
2949 MediaWiki\
suppressWarnings();
2950 $fp = fopen( $filename, 'r' );
2951 MediaWiki\restoreWarnings
();
2953 if ( false === $fp ) {
2954 throw new MWException( "Could not open \"{$filename}\".\n" );
2958 $fname = __METHOD__
. "( $filename )";
2962 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
2963 } catch ( Exception
$e ) {
2974 * Get the full path of a patch file. Originally based on archive()
2975 * from updaters.inc. Keep in mind this always returns a patch, as
2976 * it fails back to MySQL if no DB-specific patch can be found
2978 * @param string $patch The name of the patch, like patch-something.sql
2979 * @return string Full path to patch file
2981 public function patchPath( $patch ) {
2984 $dbType = $this->getType();
2985 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
2986 return "$IP/maintenance/$dbType/archives/$patch";
2988 return "$IP/maintenance/archives/$patch";
2992 public function setSchemaVars( $vars ) {
2993 $this->mSchemaVars
= $vars;
2997 * Read and execute commands from an open file handle.
2999 * Returns true on success, error string or exception on failure (depending
3000 * on object's error ignore settings).
3002 * @param resource $fp File handle
3003 * @param bool|callable $lineCallback Optional function called before reading each query
3004 * @param bool|callable $resultCallback Optional function called for each MySQL result
3005 * @param string $fname Calling function name
3006 * @param bool|callable $inputCallback Optional function called for each complete query sent
3007 * @return bool|string
3009 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3010 $fname = __METHOD__
, $inputCallback = false
3014 while ( !feof( $fp ) ) {
3015 if ( $lineCallback ) {
3016 call_user_func( $lineCallback );
3019 $line = trim( fgets( $fp ) );
3021 if ( $line == '' ) {
3025 if ( '-' == $line[0] && '-' == $line[1] ) {
3033 $done = $this->streamStatementEnd( $cmd, $line );
3037 if ( $done ||
feof( $fp ) ) {
3038 $cmd = $this->replaceVars( $cmd );
3040 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3041 $res = $this->query( $cmd, $fname );
3043 if ( $resultCallback ) {
3044 call_user_func( $resultCallback, $res, $this );
3047 if ( false === $res ) {
3048 $err = $this->lastError();
3050 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3061 * Called by sourceStream() to check if we've reached a statement end
3063 * @param string $sql SQL assembled so far
3064 * @param string $newLine New line about to be added to $sql
3065 * @return bool Whether $newLine contains end of the statement
3067 public function streamStatementEnd( &$sql, &$newLine ) {
3068 if ( $this->delimiter
) {
3070 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3071 if ( $newLine != $prev ) {
3080 * Database independent variable replacement. Replaces a set of variables
3081 * in an SQL statement with their contents as given by $this->getSchemaVars().
3083 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3085 * - '{$var}' should be used for text and is passed through the database's
3087 * - `{$var}` should be used for identifiers (e.g. table and database names).
3088 * It is passed through the database's addIdentifierQuotes method which
3089 * can be overridden if the database uses something other than backticks.
3090 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3091 * database's tableName method.
3092 * - / *i* / passes the name that follows through the database's indexName method.
3093 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3094 * its use should be avoided. In 1.24 and older, string encoding was applied.
3096 * @param string $ins SQL statement to replace variables in
3097 * @return string The new SQL statement with variables replaced
3099 protected function replaceVars( $ins ) {
3101 $vars = $this->getSchemaVars();
3102 return preg_replace_callback(
3104 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3105 \'\{\$ (\w+) }\' | # 3. addQuotes
3106 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3107 /\*\$ (\w+) \*/ # 5. leave unencoded
3109 function ( $m ) use ( $that, $vars ) {
3110 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3111 // check for both nonexistent keys *and* the empty string.
3112 if ( isset( $m[1] ) && $m[1] !== '' ) {
3113 if ( $m[1] === 'i' ) {
3114 return $that->indexName( $m[2] );
3116 return $that->tableName( $m[2] );
3118 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3119 return $that->addQuotes( $vars[$m[3]] );
3120 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3121 return $that->addIdentifierQuotes( $vars[$m[4]] );
3122 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3123 return $vars[$m[5]];
3133 * Get schema variables. If none have been set via setSchemaVars(), then
3134 * use some defaults from the current object.
3138 protected function getSchemaVars() {
3139 if ( $this->mSchemaVars
) {
3140 return $this->mSchemaVars
;
3142 return $this->getDefaultSchemaVars();
3147 * Get schema variables to use if none have been set via setSchemaVars().
3149 * Override this in derived classes to provide variables for tables.sql
3150 * and SQL patch files.
3154 protected function getDefaultSchemaVars() {
3158 public function lockIsFree( $lockName, $method ) {
3162 public function lock( $lockName, $method, $timeout = 5 ) {
3166 public function unlock( $lockName, $method ) {
3170 public function namedLocksEnqueue() {
3175 * Lock specific tables
3177 * @param array $read Array of tables to lock for read access
3178 * @param array $write Array of tables to lock for write access
3179 * @param string $method Name of caller
3180 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3183 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3188 * Unlock specific tables
3190 * @param string $method The caller
3193 public function unlockTables( $method ) {
3199 * @param string $tableName
3200 * @param string $fName
3201 * @return bool|ResultWrapper
3204 public function dropTable( $tableName, $fName = __METHOD__
) {
3205 if ( !$this->tableExists( $tableName, $fName ) ) {
3208 $sql = "DROP TABLE " . $this->tableName( $tableName );
3209 if ( $this->cascadingDeletes() ) {
3213 return $this->query( $sql, $fName );
3217 * Get search engine class. All subclasses of this need to implement this
3218 * if they wish to use searching.
3222 public function getSearchEngine() {
3223 return 'SearchEngineDummy';
3226 public function getInfinity() {
3230 public function encodeExpiry( $expiry ) {
3231 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3232 ?
$this->getInfinity()
3233 : $this->timestamp( $expiry );
3236 public function decodeExpiry( $expiry, $format = TS_MW
) {
3237 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3239 : wfTimestamp( $format, $expiry );
3242 public function setBigSelects( $value = true ) {
3246 public function isReadOnly() {
3247 return ( $this->getReadOnlyReason() !== false );
3251 * @return string|bool Reason this DB is read-only or false if it is not
3253 protected function getReadOnlyReason() {
3254 $reason = $this->getLBInfo( 'readOnlyReason' );
3256 return is_string( $reason ) ?
$reason : false;
3263 public function __toString() {
3264 return (string)$this->mConn
;
3268 * Run a few simple sanity checks
3270 public function __destruct() {
3271 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3272 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3274 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
3276 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
3277 $callers[] = $callbackInfo[1];
3279 $callers = implode( ', ', $callers );
3280 trigger_error( "DB transaction callbacks still pending (from $callers)." );
3288 abstract class Database
extends DatabaseBase
{
3289 // B/C until nothing type hints for DatabaseBase
3290 // @TODO: finish renaming DatabaseBase => Database