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
26 use Psr\Log\LoggerAwareInterface
;
27 use Psr\Log\LoggerInterface
;
30 * Database abstraction object
33 abstract class DatabaseBase
implements IDatabase
, LoggerAwareInterface
{
34 /** Number of times to re-try an operation in case of deadlock */
35 const DEADLOCK_TRIES
= 4;
36 /** Minimum time to wait before retry, in microseconds */
37 const DEADLOCK_DELAY_MIN
= 500000;
38 /** Maximum time to wait before retry */
39 const DEADLOCK_DELAY_MAX
= 1500000;
41 /** How long before it is worth doing a dummy query to test the connection */
43 const PING_QUERY
= 'SELECT 1 AS ping';
45 const TINY_WRITE_SEC
= .010;
46 const SLOW_WRITE_SEC
= .500;
47 const SMALL_WRITE_ROWS
= 100;
49 /** @var string SQL query */
50 protected $mLastQuery = '';
52 protected $mDoneWrites = false;
53 /** @var string|bool */
54 protected $mPHPError = false;
66 /** @var BagOStuff APC cache */
68 /** @var LoggerInterface */
69 protected $connLogger;
70 /** @var LoggerInterface */
71 protected $queryLogger;
73 /** @var resource Database connection */
74 protected $mConn = null;
76 protected $mOpened = false;
78 /** @var array[] List of (callable, method name) */
79 protected $mTrxIdleCallbacks = [];
80 /** @var array[] List of (callable, method name) */
81 protected $mTrxPreCommitCallbacks = [];
82 /** @var array[] List of (callable, method name) */
83 protected $mTrxEndCallbacks = [];
84 /** @var array[] Map of (name => (callable, method name)) */
85 protected $mTrxRecurringCallbacks = [];
86 /** @var bool Whether to suppress triggering of transaction end callbacks */
87 protected $mTrxEndCallbacksSuppressed = false;
90 protected $mTablePrefix;
98 protected $mLBInfo = [];
100 protected $mDefaultBigSelects = null;
101 /** @var array|bool */
102 protected $mSchemaVars = false;
104 protected $mSessionVars = [];
105 /** @var array|null */
106 protected $preparedArgs;
107 /** @var string|bool|null Stashed value of html_errors INI setting */
108 protected $htmlErrors;
110 protected $delimiter = ';';
113 * Either 1 if a transaction is active or 0 otherwise.
114 * The other Trx fields may not be meaningfull if this is 0.
118 protected $mTrxLevel = 0;
120 * Either a short hexidecimal string if a transaction is active or ""
123 * @see DatabaseBase::mTrxLevel
125 protected $mTrxShortId = '';
127 * The UNIX time that the transaction started. Callers can assume that if
128 * snapshot isolation is used, then the data is *at least* up to date to that
129 * point (possibly more up-to-date since the first SELECT defines the snapshot).
132 * @see DatabaseBase::mTrxLevel
134 private $mTrxTimestamp = null;
135 /** @var float Lag estimate at the time of BEGIN */
136 private $mTrxReplicaLag = null;
138 * Remembers the function name given for starting the most recent transaction via begin().
139 * Used to provide additional context for error reporting.
142 * @see DatabaseBase::mTrxLevel
144 private $mTrxFname = null;
146 * Record if possible write queries were done in the last transaction started
149 * @see DatabaseBase::mTrxLevel
151 private $mTrxDoneWrites = false;
153 * Record if the current transaction was started implicitly due to DBO_TRX being set.
156 * @see DatabaseBase::mTrxLevel
158 private $mTrxAutomatic = false;
160 * Array of levels of atomicity within transactions
164 private $mTrxAtomicLevels = [];
166 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
170 private $mTrxAutomaticAtomic = false;
172 * Track the write query callers of the current transaction
176 private $mTrxWriteCallers = [];
178 * @var float Seconds spent in write queries for the current transaction
180 private $mTrxWriteDuration = 0.0;
182 * @var integer Number of write queries for the current transaction
184 private $mTrxWriteQueryCount = 0;
186 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
188 private $mTrxWriteAdjDuration = 0.0;
190 * @var integer Number of write queries counted in mTrxWriteAdjDuration
192 private $mTrxWriteAdjQueryCount = 0;
194 * @var float RTT time estimate
196 private $mRTTEstimate = 0.0;
198 /** @var array Map of (name => 1) for locks obtained via lock() */
199 private $mNamedLocksHeld = [];
201 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
202 private $lazyMasterHandle;
206 * @var resource File handle for upgrade
208 protected $fileHandle = null;
212 * @var string[] Process cache of VIEWs names in the database
214 protected $allViews = null;
216 /** @var float UNIX timestamp */
217 protected $lastPing = 0.0;
219 /** @var int[] Prior mFlags values */
220 private $priorFlags = [];
224 /** @var TransactionProfiler */
225 protected $trxProfiler;
230 * FIXME: It is possible to construct a Database object with no associated
231 * connection object, by specifying no parameters to __construct(). This
232 * feature is deprecated and should be removed.
234 * IDatabase classes should not be constructed directly in external
235 * code. DatabaseBase::factory() should be used instead.
237 * @param array $params Parameters passed from DatabaseBase::factory()
239 function __construct( array $params ) {
240 global $wgDBprefix, $wgDBmwschema;
242 $this->srvCache
= ObjectCache
::getLocalServerInstance( 'hash' );
244 $server = $params['host'];
245 $user = $params['user'];
246 $password = $params['password'];
247 $dbName = $params['dbname'];
248 $flags = $params['flags'];
249 $tablePrefix = $params['tablePrefix'];
250 $schema = $params['schema'];
251 $foreign = $params['foreign'];
253 $this->cliMode
= isset( $params['cliMode'] )
255 : ( PHP_SAPI
=== 'cli' );
257 $this->mFlags
= $flags;
258 if ( $this->mFlags
& DBO_DEFAULT
) {
259 if ( $this->cliMode
) {
260 $this->mFlags
&= ~DBO_TRX
;
262 $this->mFlags |
= DBO_TRX
;
266 $this->mSessionVars
= $params['variables'];
268 /** Get the default table prefix*/
269 if ( $tablePrefix === 'get from global' ) {
270 $this->mTablePrefix
= $wgDBprefix;
272 $this->mTablePrefix
= $tablePrefix;
275 /** Get the database schema*/
276 if ( $schema === 'get from global' ) {
277 $this->mSchema
= $wgDBmwschema;
279 $this->mSchema
= $schema;
282 $this->mForeign
= $foreign;
284 $this->profiler
= isset( $params['profiler'] )
285 ?
$params['profiler']
286 : Profiler
::instance(); // @TODO: remove global state
287 $this->trxProfiler
= isset( $params['trxProfiler'] )
288 ?
$params['trxProfiler']
289 : new TransactionProfiler();
290 $this->connLogger
= isset( $params['connLogger'] )
291 ?
$params['connLogger']
292 : new \Psr\Log\
NullLogger();
293 $this->queryLogger
= isset( $params['queryLogger'] )
294 ?
$params['queryLogger']
295 : new \Psr\Log\
NullLogger();
298 $this->open( $server, $user, $password, $dbName );
303 * Given a DB type, construct the name of the appropriate child class of
304 * IDatabase. This is designed to replace all of the manual stuff like:
305 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
306 * as well as validate against the canonical list of DB types we have
308 * This factory function is mostly useful for when you need to connect to a
309 * database other than the MediaWiki default (such as for external auth,
310 * an extension, et cetera). Do not use this to connect to the MediaWiki
311 * database. Example uses in core:
312 * @see LoadBalancer::reallyOpenConnection()
313 * @see ForeignDBRepo::getMasterDB()
314 * @see WebInstallerDBConnect::execute()
318 * @param string $dbType A possible DB type
319 * @param array $p An array of options to pass to the constructor.
320 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
321 * @return IDatabase|null If the database driver or extension cannot be found
322 * @throws MWException
324 final public static function factory( $dbType, $p = [] ) {
325 global $wgCommandLineMode;
327 $canonicalDBTypes = [
328 'mysql' => [ 'mysqli', 'mysql' ],
336 $dbType = strtolower( $dbType );
337 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
338 $possibleDrivers = $canonicalDBTypes[$dbType];
339 if ( !empty( $p['driver'] ) ) {
340 if ( in_array( $p['driver'], $possibleDrivers ) ) {
341 $driver = $p['driver'];
343 throw new InvalidArgumentException( __METHOD__
.
344 " type '$dbType' does not support driver '{$p['driver']}'" );
347 foreach ( $possibleDrivers as $posDriver ) {
348 if ( extension_loaded( $posDriver ) ) {
349 $driver = $posDriver;
357 if ( $driver === false ) {
358 throw new MWException( __METHOD__
.
359 " no viable database extension found for type '$dbType'" );
362 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
363 // and everything else doesn't use a schema (e.g. null)
364 // Although postgres and oracle support schemas, we don't use them (yet)
365 // to maintain backwards compatibility
367 'mssql' => 'get from global',
370 $class = 'Database' . ucfirst( $driver );
371 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
372 // Resolve some defaults for b/c
373 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
374 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
375 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
376 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
377 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
378 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
379 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global';
380 if ( !isset( $p['schema'] ) ) {
381 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : null;
383 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
384 $p['cliMode'] = $wgCommandLineMode;
386 $conn = new $class( $p );
387 if ( isset( $p['connLogger'] ) ) {
388 $conn->connLogger
= $p['connLogger'];
390 if ( isset( $p['queryLogger'] ) ) {
391 $conn->queryLogger
= $p['queryLogger'];
400 public function setLogger( LoggerInterface
$logger ) {
401 $this->queryLogger
= $logger;
404 public function getServerInfo() {
405 return $this->getServerVersion();
409 * @return string Command delimiter used by this database engine
411 public function getDelimiter() {
412 return $this->delimiter
;
416 * Boolean, controls output of large amounts of debug information.
417 * @param bool|null $debug
418 * - true to enable debugging
419 * - false to disable debugging
420 * - omitted or null to do nothing
422 * @return bool|null Previous value of the flag
424 public function debug( $debug = null ) {
425 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
428 public function bufferResults( $buffer = null ) {
429 if ( is_null( $buffer ) ) {
430 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
432 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
437 * Turns on (false) or off (true) the automatic generation and sending
438 * of a "we're sorry, but there has been a database error" page on
439 * database errors. Default is on (false). When turned off, the
440 * code should use lastErrno() and lastError() to handle the
441 * situation as appropriate.
443 * Do not use this function outside of the Database classes.
445 * @param null|bool $ignoreErrors
446 * @return bool The previous value of the flag.
448 protected function ignoreErrors( $ignoreErrors = null ) {
449 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
452 public function trxLevel() {
453 return $this->mTrxLevel
;
456 public function trxTimestamp() {
457 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
460 public function tablePrefix( $prefix = null ) {
461 return wfSetVar( $this->mTablePrefix
, $prefix );
464 public function dbSchema( $schema = null ) {
465 return wfSetVar( $this->mSchema
, $schema );
469 * Set the filehandle to copy write statements to.
471 * @param resource $fh File handle
473 public function setFileHandle( $fh ) {
474 $this->fileHandle
= $fh;
477 public function getLBInfo( $name = null ) {
478 if ( is_null( $name ) ) {
479 return $this->mLBInfo
;
481 if ( array_key_exists( $name, $this->mLBInfo
) ) {
482 return $this->mLBInfo
[$name];
489 public function setLBInfo( $name, $value = null ) {
490 if ( is_null( $value ) ) {
491 $this->mLBInfo
= $name;
493 $this->mLBInfo
[$name] = $value;
497 public function setLazyMasterHandle( IDatabase
$conn ) {
498 $this->lazyMasterHandle
= $conn;
502 * @return IDatabase|null
503 * @see setLazyMasterHandle()
506 public function getLazyMasterHandle() {
507 return $this->lazyMasterHandle
;
511 * @param TransactionProfiler $profiler
514 public function setTransactionProfiler( TransactionProfiler
$profiler ) {
515 $this->trxProfiler
= $profiler;
519 * Returns true if this database supports (and uses) cascading deletes
523 public function cascadingDeletes() {
528 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
532 public function cleanupTriggers() {
537 * Returns true if this database is strict about what can be put into an IP field.
538 * Specifically, it uses a NULL value instead of an empty string.
542 public function strictIPs() {
547 * Returns true if this database uses timestamps rather than integers
551 public function realTimestamps() {
555 public function implicitGroupby() {
559 public function implicitOrderby() {
564 * Returns true if this database can do a native search on IP columns
565 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
569 public function searchableIPs() {
574 * Returns true if this database can use functional indexes
578 public function functionalIndexes() {
582 public function lastQuery() {
583 return $this->mLastQuery
;
586 public function doneWrites() {
587 return (bool)$this->mDoneWrites
;
590 public function lastDoneWrites() {
591 return $this->mDoneWrites ?
: false;
594 public function writesPending() {
595 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
598 public function writesOrCallbacksPending() {
599 return $this->mTrxLevel
&& (
600 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
604 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
605 if ( !$this->mTrxLevel
) {
607 } elseif ( !$this->mTrxDoneWrites
) {
612 case self
::ESTIMATE_DB_APPLY
:
614 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
615 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
616 // For omitted queries, make them count as something at least
617 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
618 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
621 default: // everything
622 return $this->mTrxWriteDuration
;
626 public function pendingWriteCallers() {
627 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
630 public function isOpen() {
631 return $this->mOpened
;
634 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
635 if ( $remember === self
::REMEMBER_PRIOR
) {
636 array_push( $this->priorFlags
, $this->mFlags
);
638 $this->mFlags |
= $flag;
641 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
642 if ( $remember === self
::REMEMBER_PRIOR
) {
643 array_push( $this->priorFlags
, $this->mFlags
);
645 $this->mFlags
&= ~
$flag;
648 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
649 if ( !$this->priorFlags
) {
653 if ( $state === self
::RESTORE_INITIAL
) {
654 $this->mFlags
= reset( $this->priorFlags
);
655 $this->priorFlags
= [];
657 $this->mFlags
= array_pop( $this->priorFlags
);
661 public function getFlag( $flag ) {
662 return !!( $this->mFlags
& $flag );
665 public function getProperty( $name ) {
669 public function getWikiID() {
670 if ( $this->mTablePrefix
) {
671 return "{$this->mDBname}-{$this->mTablePrefix}";
673 return $this->mDBname
;
678 * Return a path to the DBMS-specific SQL file if it exists,
679 * otherwise default SQL file
681 * @param string $filename
684 private function getSqlFilePath( $filename ) {
686 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
687 if ( file_exists( $dbmsSpecificFilePath ) ) {
688 return $dbmsSpecificFilePath;
690 return "$IP/maintenance/$filename";
695 * Return a path to the DBMS-specific schema file,
696 * otherwise default to tables.sql
700 public function getSchemaPath() {
701 return $this->getSqlFilePath( 'tables.sql' );
705 * Return a path to the DBMS-specific update key file,
706 * otherwise default to update-keys.sql
710 public function getUpdateKeysPath() {
711 return $this->getSqlFilePath( 'update-keys.sql' );
715 * Get information about an index into an object
716 * @param string $table Table name
717 * @param string $index Index name
718 * @param string $fname Calling function name
719 * @return mixed Database-specific index description class or false if the index does not exist
721 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
724 * Wrapper for addslashes()
726 * @param string $s String to be slashed.
727 * @return string Slashed string.
729 abstract function strencode( $s );
732 * Called by serialize. Throw an exception when DB connection is serialized.
733 * This causes problems on some database engines because the connection is
734 * not restored on unserialize.
736 public function __sleep() {
737 throw new RuntimeException( 'Database serialization may cause problems, since ' .
738 'the connection is not restored on wakeup.' );
741 protected function installErrorHandler() {
742 $this->mPHPError
= false;
743 $this->htmlErrors
= ini_set( 'html_errors', '0' );
744 set_error_handler( [ $this, 'connectionErrorHandler' ] );
748 * @return bool|string
750 protected function restoreErrorHandler() {
751 restore_error_handler();
752 if ( $this->htmlErrors
!== false ) {
753 ini_set( 'html_errors', $this->htmlErrors
);
755 if ( $this->mPHPError
) {
756 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
757 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
767 * @param string $errstr
769 public function connectionErrorHandler( $errno, $errstr ) {
770 $this->mPHPError
= $errstr;
774 * Create a log context to pass to wfLogDBError or other logging functions.
776 * @param array $extras Additional data to add to context
779 protected function getLogContext( array $extras = [] ) {
782 'db_server' => $this->mServer
,
783 'db_name' => $this->mDBname
,
784 'db_user' => $this->mUser
,
790 public function close() {
791 if ( $this->mConn
) {
792 if ( $this->trxLevel() ) {
793 if ( !$this->mTrxAutomatic
) {
794 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
795 " performing implicit commit before closing connection!" );
798 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
801 $closed = $this->closeConnection();
802 $this->mConn
= false;
803 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
804 throw new RuntimeException( "Transaction callbacks still pending." );
808 $this->mOpened
= false;
814 * Make sure isOpen() returns true as a sanity check
816 * @throws DBUnexpectedError
818 protected function assertOpen() {
819 if ( !$this->isOpen() ) {
820 throw new DBUnexpectedError( $this, "DB connection was already closed." );
825 * Closes underlying database connection
827 * @return bool Whether connection was closed successfully
829 abstract protected function closeConnection();
831 function reportConnectionError( $error = 'Unknown error' ) {
832 $myError = $this->lastError();
838 throw new DBConnectionError( $this, $error );
842 * The DBMS-dependent part of query()
844 * @param string $sql SQL query.
845 * @return ResultWrapper|bool Result object to feed to fetchObject,
846 * fetchRow, ...; or false on failure
848 abstract protected function doQuery( $sql );
851 * Determine whether a query writes to the DB.
852 * Should return true if unsure.
857 protected function isWriteQuery( $sql ) {
859 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
864 * @return string|null
866 protected function getQueryVerb( $sql ) {
867 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
871 * Determine whether a SQL statement is sensitive to isolation level.
872 * A SQL statement is considered transactable if its result could vary
873 * depending on the transaction isolation level. Operational commands
874 * such as 'SET' and 'SHOW' are not considered to be transactable.
879 protected function isTransactableQuery( $sql ) {
880 $verb = $this->getQueryVerb( $sql );
881 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
884 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
887 $priorWritesPending = $this->writesOrCallbacksPending();
888 $this->mLastQuery
= $sql;
890 $isWrite = $this->isWriteQuery( $sql );
892 $reason = $this->getReadOnlyReason();
893 if ( $reason !== false ) {
894 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
896 # Set a flag indicating that writes have been done
897 $this->mDoneWrites
= microtime( true );
900 # Add a comment for easy SHOW PROCESSLIST interpretation
901 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
902 $userName = $wgUser->getName();
903 if ( mb_strlen( $userName ) > 15 ) {
904 $userName = mb_substr( $userName, 0, 15 ) . '...';
906 $userName = str_replace( '/', '', $userName );
911 // Add trace comment to the begin of the sql string, right after the operator.
912 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
913 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
915 # Start implicit transactions that wrap the request if DBO_TRX is enabled
916 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
)
917 && $this->isTransactableQuery( $sql )
919 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
920 $this->mTrxAutomatic
= true;
923 # Keep track of whether the transaction has write queries pending
924 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
925 $this->mTrxDoneWrites
= true;
926 $this->trxProfiler
->transactionWritingIn(
927 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
930 if ( $this->debug() ) {
931 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
934 # Avoid fatals if close() was called
937 # Send the query to the server
938 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
940 # Try reconnecting if the connection was lost
941 if ( false === $ret && $this->wasErrorReissuable() ) {
942 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
943 # Stash the last error values before anything might clear them
944 $lastError = $this->lastError();
945 $lastErrno = $this->lastErrno();
946 # Update state tracking to reflect transaction loss due to disconnection
947 $this->handleTransactionLoss();
948 if ( $this->reconnect() ) {
949 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
950 $this->connLogger
->warning( $msg );
951 $this->queryLogger
->warning( "$msg:\n" . wfBacktrace( true ) );
953 if ( !$recoverable ) {
954 # Callers may catch the exception and continue to use the DB
955 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
957 # Should be safe to silently retry the query
958 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
961 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
962 $this->connLogger
->error( $msg );
966 if ( false === $ret ) {
967 # Deadlocks cause the entire transaction to abort, not just the statement.
968 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
969 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
970 if ( $this->wasDeadlock() ) {
971 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
972 $tempIgnore = false; // not recoverable
974 # Update state tracking to reflect transaction loss
975 $this->handleTransactionLoss();
978 $this->reportQueryError(
979 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
982 $res = $this->resultObject( $ret );
987 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
988 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
989 # generalizeSQL() will probably cut down the query to reasonable
990 # logging size most of the time. The substr is really just a sanity check.
992 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
994 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
997 # Include query transaction state
998 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
1000 $startTime = microtime( true );
1001 $this->profiler
->profileIn( $queryProf );
1002 $ret = $this->doQuery( $commentedSql );
1003 $this->profiler
->profileOut( $queryProf );
1004 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1006 unset( $queryProfSection ); // profile out (if set)
1008 if ( $ret !== false ) {
1009 $this->lastPing
= $startTime;
1010 if ( $isWrite && $this->mTrxLevel
) {
1011 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
1012 $this->mTrxWriteCallers
[] = $fname;
1016 if ( $sql === self
::PING_QUERY
) {
1017 $this->mRTTEstimate
= $queryRuntime;
1020 $this->trxProfiler
->recordQueryCompletion(
1021 $queryProf, $startTime, $isWrite, $this->affectedRows()
1023 MWDebug
::query( $sql, $fname, $isMaster, $queryRuntime );
1029 * Update the estimated run-time of a query, not counting large row lock times
1031 * LoadBalancer can be set to rollback transactions that will create huge replication
1032 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1033 * queries, like inserting a row can take a long time due to row locking. This method
1034 * uses some simple heuristics to discount those cases.
1036 * @param string $sql A SQL write query
1037 * @param float $runtime Total runtime, including RTT
1039 private function updateTrxWriteQueryTime( $sql, $runtime ) {
1040 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1041 $indicativeOfReplicaRuntime = true;
1042 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1043 $verb = $this->getQueryVerb( $sql );
1044 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1045 if ( $verb === 'INSERT' ) {
1046 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1047 } elseif ( $verb === 'REPLACE' ) {
1048 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1052 $this->mTrxWriteDuration +
= $runtime;
1053 $this->mTrxWriteQueryCount +
= 1;
1054 if ( $indicativeOfReplicaRuntime ) {
1055 $this->mTrxWriteAdjDuration +
= $runtime;
1056 $this->mTrxWriteAdjQueryCount +
= 1;
1060 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1061 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1062 # Dropped connections also mean that named locks are automatically released.
1063 # Only allow error suppression in autocommit mode or when the lost transaction
1064 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1065 if ( $this->mNamedLocksHeld
) {
1066 return false; // possible critical section violation
1067 } elseif ( $sql === 'COMMIT' ) {
1068 return !$priorWritesPending; // nothing written anyway? (T127428)
1069 } elseif ( $sql === 'ROLLBACK' ) {
1070 return true; // transaction lost...which is also what was requested :)
1071 } elseif ( $this->explicitTrxActive() ) {
1072 return false; // don't drop atomocity
1073 } elseif ( $priorWritesPending ) {
1074 return false; // prior writes lost from implicit transaction
1080 private function handleTransactionLoss() {
1081 $this->mTrxLevel
= 0;
1082 $this->mTrxIdleCallbacks
= []; // bug 65263
1083 $this->mTrxPreCommitCallbacks
= []; // bug 65263
1085 // Handle callbacks in mTrxEndCallbacks
1086 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1087 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1089 } catch ( Exception
$e ) {
1090 // Already logged; move on...
1095 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1096 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1097 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1099 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1101 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1102 $this->getLogContext( [
1103 'method' => __METHOD__
,
1106 'sql1line' => $sql1line,
1110 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1111 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1116 * Intended to be compatible with the PEAR::DB wrapper functions.
1117 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1119 * ? = scalar value, quoted as necessary
1120 * ! = raw SQL bit (a function for instance)
1121 * & = filename; reads the file and inserts as a blob
1122 * (we don't use this though...)
1124 * @param string $sql
1125 * @param string $func
1129 protected function prepare( $sql, $func = __METHOD__
) {
1130 /* MySQL doesn't support prepared statements (yet), so just
1131 * pack up the query for reference. We'll manually replace
1134 return [ 'query' => $sql, 'func' => $func ];
1138 * Free a prepared query, generated by prepare().
1139 * @param string $prepared
1141 protected function freePrepared( $prepared ) {
1142 /* No-op by default */
1146 * Execute a prepared query with the various arguments
1147 * @param string $prepared The prepared sql
1148 * @param mixed $args Either an array here, or put scalars as varargs
1150 * @return ResultWrapper
1152 public function execute( $prepared, $args = null ) {
1153 if ( !is_array( $args ) ) {
1155 $args = func_get_args();
1156 array_shift( $args );
1159 $sql = $this->fillPrepared( $prepared['query'], $args );
1161 return $this->query( $sql, $prepared['func'] );
1165 * For faking prepared SQL statements on DBs that don't support it directly.
1167 * @param string $preparedQuery A 'preparable' SQL statement
1168 * @param array $args Array of Arguments to fill it with
1169 * @return string Executable SQL
1171 public function fillPrepared( $preparedQuery, $args ) {
1173 $this->preparedArgs
=& $args;
1175 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1176 [ &$this, 'fillPreparedArg' ], $preparedQuery );
1180 * preg_callback func for fillPrepared()
1181 * The arguments should be in $this->preparedArgs and must not be touched
1182 * while we're doing this.
1184 * @param array $matches
1185 * @throws DBUnexpectedError
1188 protected function fillPreparedArg( $matches ) {
1189 switch ( $matches[1] ) {
1198 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1200 switch ( $matches[1] ) {
1202 return $this->addQuotes( $arg );
1206 # return $this->addQuotes( file_get_contents( $arg ) );
1207 throw new DBUnexpectedError(
1209 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1212 throw new DBUnexpectedError(
1214 'Received invalid match. This should never happen!'
1219 public function freeResult( $res ) {
1222 public function selectField(
1223 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1225 if ( $var === '*' ) { // sanity
1226 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1229 if ( !is_array( $options ) ) {
1230 $options = [ $options ];
1233 $options['LIMIT'] = 1;
1235 $res = $this->select( $table, $var, $cond, $fname, $options );
1236 if ( $res === false ||
!$this->numRows( $res ) ) {
1240 $row = $this->fetchRow( $res );
1242 if ( $row !== false ) {
1243 return reset( $row );
1249 public function selectFieldValues(
1250 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1252 if ( $var === '*' ) { // sanity
1253 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1254 } elseif ( !is_string( $var ) ) { // sanity
1255 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1258 if ( !is_array( $options ) ) {
1259 $options = [ $options ];
1262 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1263 if ( $res === false ) {
1268 foreach ( $res as $row ) {
1269 $values[] = $row->$var;
1276 * Returns an optional USE INDEX clause to go after the table, and a
1277 * string to go at the end of the query.
1279 * @param array $options Associative array of options to be turned into
1280 * an SQL query, valid keys are listed in the function.
1282 * @see DatabaseBase::select()
1284 public function makeSelectOptions( $options ) {
1285 $preLimitTail = $postLimitTail = '';
1290 foreach ( $options as $key => $option ) {
1291 if ( is_numeric( $key ) ) {
1292 $noKeyOptions[$option] = true;
1296 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1298 $preLimitTail .= $this->makeOrderBy( $options );
1300 // if (isset($options['LIMIT'])) {
1301 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1302 // isset($options['OFFSET']) ? $options['OFFSET']
1306 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1307 $postLimitTail .= ' FOR UPDATE';
1310 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1311 $postLimitTail .= ' LOCK IN SHARE MODE';
1314 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1315 $startOpts .= 'DISTINCT';
1318 # Various MySQL extensions
1319 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1320 $startOpts .= ' /*! STRAIGHT_JOIN */';
1323 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1324 $startOpts .= ' HIGH_PRIORITY';
1327 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1328 $startOpts .= ' SQL_BIG_RESULT';
1331 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1332 $startOpts .= ' SQL_BUFFER_RESULT';
1335 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1336 $startOpts .= ' SQL_SMALL_RESULT';
1339 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1340 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1343 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1344 $startOpts .= ' SQL_CACHE';
1347 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1348 $startOpts .= ' SQL_NO_CACHE';
1351 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1352 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1356 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1357 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1362 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1366 * Returns an optional GROUP BY with an optional HAVING
1368 * @param array $options Associative array of options
1370 * @see DatabaseBase::select()
1373 public function makeGroupByWithHaving( $options ) {
1375 if ( isset( $options['GROUP BY'] ) ) {
1376 $gb = is_array( $options['GROUP BY'] )
1377 ?
implode( ',', $options['GROUP BY'] )
1378 : $options['GROUP BY'];
1379 $sql .= ' GROUP BY ' . $gb;
1381 if ( isset( $options['HAVING'] ) ) {
1382 $having = is_array( $options['HAVING'] )
1383 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1384 : $options['HAVING'];
1385 $sql .= ' HAVING ' . $having;
1392 * Returns an optional ORDER BY
1394 * @param array $options Associative array of options
1396 * @see DatabaseBase::select()
1399 public function makeOrderBy( $options ) {
1400 if ( isset( $options['ORDER BY'] ) ) {
1401 $ob = is_array( $options['ORDER BY'] )
1402 ?
implode( ',', $options['ORDER BY'] )
1403 : $options['ORDER BY'];
1405 return ' ORDER BY ' . $ob;
1411 // See IDatabase::select for the docs for this function
1412 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1413 $options = [], $join_conds = [] ) {
1414 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1416 return $this->query( $sql, $fname );
1419 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1420 $options = [], $join_conds = []
1422 if ( is_array( $vars ) ) {
1423 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1426 $options = (array)$options;
1427 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1428 ?
$options['USE INDEX']
1430 $ignoreIndexes = ( isset( $options['IGNORE INDEX'] ) && is_array( $options['IGNORE INDEX'] ) )
1431 ?
$options['IGNORE INDEX']
1434 if ( is_array( $table ) ) {
1436 $this->tableNamesWithIndexClauseOrJOIN( $table, $useIndexes, $ignoreIndexes, $join_conds );
1437 } elseif ( $table != '' ) {
1438 if ( $table[0] == ' ' ) {
1439 $from = ' FROM ' . $table;
1442 $this->tableNamesWithIndexClauseOrJOIN( [ $table ], $useIndexes, $ignoreIndexes, [] );
1448 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1449 $this->makeSelectOptions( $options );
1451 if ( !empty( $conds ) ) {
1452 if ( is_array( $conds ) ) {
1453 $conds = $this->makeList( $conds, LIST_AND
);
1455 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex WHERE $conds $preLimitTail";
1457 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1460 if ( isset( $options['LIMIT'] ) ) {
1461 $sql = $this->limitResult( $sql, $options['LIMIT'],
1462 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1464 $sql = "$sql $postLimitTail";
1466 if ( isset( $options['EXPLAIN'] ) ) {
1467 $sql = 'EXPLAIN ' . $sql;
1473 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1474 $options = [], $join_conds = []
1476 $options = (array)$options;
1477 $options['LIMIT'] = 1;
1478 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1480 if ( $res === false ) {
1484 if ( !$this->numRows( $res ) ) {
1488 $obj = $this->fetchObject( $res );
1493 public function estimateRowCount(
1494 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1497 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1500 $row = $this->fetchRow( $res );
1501 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1507 public function selectRowCount(
1508 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1511 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1512 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1515 $row = $this->fetchRow( $res );
1516 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1523 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1524 * It's only slightly flawed. Don't use for anything important.
1526 * @param string $sql A SQL Query
1530 protected static function generalizeSQL( $sql ) {
1531 # This does the same as the regexp below would do, but in such a way
1532 # as to avoid crashing php on some large strings.
1533 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1535 $sql = str_replace( "\\\\", '', $sql );
1536 $sql = str_replace( "\\'", '', $sql );
1537 $sql = str_replace( "\\\"", '', $sql );
1538 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1539 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1541 # All newlines, tabs, etc replaced by single space
1542 $sql = preg_replace( '/\s+/', ' ', $sql );
1545 # except the ones surrounded by characters, e.g. l10n
1546 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1547 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1552 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1553 $info = $this->fieldInfo( $table, $field );
1558 public function indexExists( $table, $index, $fname = __METHOD__
) {
1559 if ( !$this->tableExists( $table ) ) {
1563 $info = $this->indexInfo( $table, $index, $fname );
1564 if ( is_null( $info ) ) {
1567 return $info !== false;
1571 public function tableExists( $table, $fname = __METHOD__
) {
1572 $table = $this->tableName( $table );
1573 $old = $this->ignoreErrors( true );
1574 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1575 $this->ignoreErrors( $old );
1580 public function indexUnique( $table, $index ) {
1581 $indexInfo = $this->indexInfo( $table, $index );
1583 if ( !$indexInfo ) {
1587 return !$indexInfo[0]->Non_unique
;
1591 * Helper for DatabaseBase::insert().
1593 * @param array $options
1596 protected function makeInsertOptions( $options ) {
1597 return implode( ' ', $options );
1600 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1601 # No rows to insert, easy just return now
1602 if ( !count( $a ) ) {
1606 $table = $this->tableName( $table );
1608 if ( !is_array( $options ) ) {
1609 $options = [ $options ];
1613 if ( isset( $options['fileHandle'] ) ) {
1614 $fh = $options['fileHandle'];
1616 $options = $this->makeInsertOptions( $options );
1618 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1620 $keys = array_keys( $a[0] );
1623 $keys = array_keys( $a );
1626 $sql = 'INSERT ' . $options .
1627 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1631 foreach ( $a as $row ) {
1637 $sql .= '(' . $this->makeList( $row ) . ')';
1640 $sql .= '(' . $this->makeList( $a ) . ')';
1643 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1645 } elseif ( $fh !== null ) {
1649 return (bool)$this->query( $sql, $fname );
1653 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1655 * @param array $options
1658 protected function makeUpdateOptionsArray( $options ) {
1659 if ( !is_array( $options ) ) {
1660 $options = [ $options ];
1665 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1666 $opts[] = $this->lowPriorityOption();
1669 if ( in_array( 'IGNORE', $options ) ) {
1677 * Make UPDATE options for the DatabaseBase::update function
1679 * @param array $options The options passed to DatabaseBase::update
1682 protected function makeUpdateOptions( $options ) {
1683 $opts = $this->makeUpdateOptionsArray( $options );
1685 return implode( ' ', $opts );
1688 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1689 $table = $this->tableName( $table );
1690 $opts = $this->makeUpdateOptions( $options );
1691 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1693 if ( $conds !== [] && $conds !== '*' ) {
1694 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1697 return $this->query( $sql, $fname );
1700 public function makeList( $a, $mode = LIST_COMMA
) {
1701 if ( !is_array( $a ) ) {
1702 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1708 foreach ( $a as $field => $value ) {
1710 if ( $mode == LIST_AND
) {
1712 } elseif ( $mode == LIST_OR
) {
1721 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1722 $list .= "($value)";
1723 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1725 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1726 // Remove null from array to be handled separately if found
1727 $includeNull = false;
1728 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1729 $includeNull = true;
1730 unset( $value[$nullKey] );
1732 if ( count( $value ) == 0 && !$includeNull ) {
1733 throw new InvalidArgumentException( __METHOD__
. ": empty input for field $field" );
1734 } elseif ( count( $value ) == 0 ) {
1735 // only check if $field is null
1736 $list .= "$field IS NULL";
1738 // IN clause contains at least one valid element
1739 if ( $includeNull ) {
1740 // Group subconditions to ensure correct precedence
1743 if ( count( $value ) == 1 ) {
1744 // Special-case single values, as IN isn't terribly efficient
1745 // Don't necessarily assume the single key is 0; we don't
1746 // enforce linear numeric ordering on other arrays here.
1747 $value = array_values( $value )[0];
1748 $list .= $field . " = " . $this->addQuotes( $value );
1750 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1752 // if null present in array, append IS NULL
1753 if ( $includeNull ) {
1754 $list .= " OR $field IS NULL)";
1757 } elseif ( $value === null ) {
1758 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1759 $list .= "$field IS ";
1760 } elseif ( $mode == LIST_SET
) {
1761 $list .= "$field = ";
1765 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1766 $list .= "$field = ";
1768 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1775 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1778 foreach ( $data as $base => $sub ) {
1779 if ( count( $sub ) ) {
1780 $conds[] = $this->makeList(
1781 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1787 return $this->makeList( $conds, LIST_OR
);
1789 // Nothing to search for...
1795 * Return aggregated value alias
1797 * @param array $valuedata
1798 * @param string $valuename
1802 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1806 public function bitNot( $field ) {
1810 public function bitAnd( $fieldLeft, $fieldRight ) {
1811 return "($fieldLeft & $fieldRight)";
1814 public function bitOr( $fieldLeft, $fieldRight ) {
1815 return "($fieldLeft | $fieldRight)";
1818 public function buildConcat( $stringList ) {
1819 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1822 public function buildGroupConcatField(
1823 $delim, $table, $field, $conds = '', $join_conds = []
1825 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1827 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1831 * @param string $field Field or column to cast
1835 public function buildStringCast( $field ) {
1839 public function selectDB( $db ) {
1840 # Stub. Shouldn't cause serious problems if it's not overridden, but
1841 # if your database engine supports a concept similar to MySQL's
1842 # databases you may as well.
1843 $this->mDBname
= $db;
1848 public function getDBname() {
1849 return $this->mDBname
;
1852 public function getServer() {
1853 return $this->mServer
;
1857 * Format a table name ready for use in constructing an SQL query
1859 * This does two important things: it quotes the table names to clean them up,
1860 * and it adds a table prefix if only given a table name with no quotes.
1862 * All functions of this object which require a table name call this function
1863 * themselves. Pass the canonical name to such functions. This is only needed
1864 * when calling query() directly.
1866 * @note This function does not sanitize user input. It is not safe to use
1867 * this function to escape user input.
1868 * @param string $name Database table name
1869 * @param string $format One of:
1870 * quoted - Automatically pass the table name through addIdentifierQuotes()
1871 * so that it can be used in a query.
1872 * raw - Do not add identifier quotes to the table name
1873 * @return string Full database name
1875 public function tableName( $name, $format = 'quoted' ) {
1876 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
1877 # Skip the entire process when we have a string quoted on both ends.
1878 # Note that we check the end so that we will still quote any use of
1879 # use of `database`.table. But won't break things if someone wants
1880 # to query a database table with a dot in the name.
1881 if ( $this->isQuotedIdentifier( $name ) ) {
1885 # Lets test for any bits of text that should never show up in a table
1886 # name. Basically anything like JOIN or ON which are actually part of
1887 # SQL queries, but may end up inside of the table value to combine
1888 # sql. Such as how the API is doing.
1889 # Note that we use a whitespace test rather than a \b test to avoid
1890 # any remote case where a word like on may be inside of a table name
1891 # surrounded by symbols which may be considered word breaks.
1892 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1896 # Split database and table into proper variables.
1897 # We reverse the explode so that database.table and table both output
1898 # the correct table.
1899 $dbDetails = explode( '.', $name, 3 );
1900 if ( count( $dbDetails ) == 3 ) {
1901 list( $database, $schema, $table ) = $dbDetails;
1902 # We don't want any prefix added in this case
1904 } elseif ( count( $dbDetails ) == 2 ) {
1905 list( $database, $table ) = $dbDetails;
1906 # We don't want any prefix added in this case
1907 # In dbs that support it, $database may actually be the schema
1908 # but that doesn't affect any of the functionality here
1912 list( $table ) = $dbDetails;
1913 if ( $wgSharedDB !== null # We have a shared database
1914 && $this->mForeign
== false # We're not working on a foreign database
1915 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
1916 && in_array( $table, $wgSharedTables ) # A shared table is selected
1918 $database = $wgSharedDB;
1919 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
1920 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
1923 $schema = $this->mSchema
; # Default schema
1924 $prefix = $this->mTablePrefix
; # Default prefix
1928 # Quote $table and apply the prefix if not quoted.
1929 # $tableName might be empty if this is called from Database::replaceVars()
1930 $tableName = "{$prefix}{$table}";
1931 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
1932 $tableName = $this->addIdentifierQuotes( $tableName );
1935 # Quote $schema and merge it with the table name if needed
1936 if ( strlen( $schema ) ) {
1937 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1938 $schema = $this->addIdentifierQuotes( $schema );
1940 $tableName = $schema . '.' . $tableName;
1943 # Quote $database and merge it with the table name if needed
1944 if ( $database !== null ) {
1945 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1946 $database = $this->addIdentifierQuotes( $database );
1948 $tableName = $database . '.' . $tableName;
1955 * Fetch a number of table names into an array
1956 * This is handy when you need to construct SQL for joins
1959 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1960 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1961 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1965 public function tableNames() {
1966 $inArray = func_get_args();
1969 foreach ( $inArray as $name ) {
1970 $retVal[$name] = $this->tableName( $name );
1977 * Fetch a number of table names into an zero-indexed numerical array
1978 * This is handy when you need to construct SQL for joins
1981 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1982 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1983 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1987 public function tableNamesN() {
1988 $inArray = func_get_args();
1991 foreach ( $inArray as $name ) {
1992 $retVal[] = $this->tableName( $name );
1999 * Get an aliased table name
2000 * e.g. tableName AS newTableName
2002 * @param string $name Table name, see tableName()
2003 * @param string|bool $alias Alias (optional)
2004 * @return string SQL name for aliased table. Will not alias a table to its own name
2006 public function tableNameWithAlias( $name, $alias = false ) {
2007 if ( !$alias ||
$alias == $name ) {
2008 return $this->tableName( $name );
2010 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2015 * Gets an array of aliased table names
2017 * @param array $tables [ [alias] => table ]
2018 * @return string[] See tableNameWithAlias()
2020 public function tableNamesWithAlias( $tables ) {
2022 foreach ( $tables as $alias => $table ) {
2023 if ( is_numeric( $alias ) ) {
2026 $retval[] = $this->tableNameWithAlias( $table, $alias );
2033 * Get an aliased field name
2034 * e.g. fieldName AS newFieldName
2036 * @param string $name Field name
2037 * @param string|bool $alias Alias (optional)
2038 * @return string SQL name for aliased field. Will not alias a field to its own name
2040 public function fieldNameWithAlias( $name, $alias = false ) {
2041 if ( !$alias ||
(string)$alias === (string)$name ) {
2044 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2049 * Gets an array of aliased field names
2051 * @param array $fields [ [alias] => field ]
2052 * @return string[] See fieldNameWithAlias()
2054 public function fieldNamesWithAlias( $fields ) {
2056 foreach ( $fields as $alias => $field ) {
2057 if ( is_numeric( $alias ) ) {
2060 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2067 * Get the aliased table name clause for a FROM clause
2068 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2070 * @param array $tables ( [alias] => table )
2071 * @param array $use_index Same as for select()
2072 * @param array $ignore_index Same as for select()
2073 * @param array $join_conds Same as for select()
2076 protected function tableNamesWithIndexClauseOrJOIN(
2077 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2081 $use_index = (array)$use_index;
2082 $ignore_index = (array)$ignore_index;
2083 $join_conds = (array)$join_conds;
2085 foreach ( $tables as $alias => $table ) {
2086 if ( !is_string( $alias ) ) {
2087 // No alias? Set it equal to the table name
2090 // Is there a JOIN clause for this table?
2091 if ( isset( $join_conds[$alias] ) ) {
2092 list( $joinType, $conds ) = $join_conds[$alias];
2093 $tableClause = $joinType;
2094 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2095 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2096 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2098 $tableClause .= ' ' . $use;
2101 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2102 $ignore = $this->ignoreIndexClause( implode( ',', (array)$ignore_index[$alias] ) );
2103 if ( $ignore != '' ) {
2104 $tableClause .= ' ' . $ignore;
2107 $on = $this->makeList( (array)$conds, LIST_AND
);
2109 $tableClause .= ' ON (' . $on . ')';
2112 $retJOIN[] = $tableClause;
2113 } elseif ( isset( $use_index[$alias] ) ) {
2114 // Is there an INDEX clause for this table?
2115 $tableClause = $this->tableNameWithAlias( $table, $alias );
2116 $tableClause .= ' ' . $this->useIndexClause(
2117 implode( ',', (array)$use_index[$alias] )
2120 $ret[] = $tableClause;
2121 } elseif ( isset( $ignore_index[$alias] ) ) {
2122 // Is there an INDEX clause for this table?
2123 $tableClause = $this->tableNameWithAlias( $table, $alias );
2124 $tableClause .= ' ' . $this->ignoreIndexClause(
2125 implode( ',', (array)$ignore_index[$alias] )
2128 $ret[] = $tableClause;
2130 $tableClause = $this->tableNameWithAlias( $table, $alias );
2132 $ret[] = $tableClause;
2136 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2137 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2138 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2140 // Compile our final table clause
2141 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2145 * Get the name of an index in a given table.
2147 * @param string $index
2150 protected function indexName( $index ) {
2151 // Backwards-compatibility hack
2153 'ar_usertext_timestamp' => 'usertext_timestamp',
2154 'un_user_id' => 'user_id',
2155 'un_user_ip' => 'user_ip',
2158 if ( isset( $renamed[$index] ) ) {
2159 return $renamed[$index];
2165 public function addQuotes( $s ) {
2166 if ( $s instanceof Blob
) {
2169 if ( $s === null ) {
2172 # This will also quote numeric values. This should be harmless,
2173 # and protects against weird problems that occur when they really
2174 # _are_ strings such as article titles and string->number->string
2175 # conversion is not 1:1.
2176 return "'" . $this->strencode( $s ) . "'";
2181 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2182 * MySQL uses `backticks` while basically everything else uses double quotes.
2183 * Since MySQL is the odd one out here the double quotes are our generic
2184 * and we implement backticks in DatabaseMysql.
2189 public function addIdentifierQuotes( $s ) {
2190 return '"' . str_replace( '"', '""', $s ) . '"';
2194 * Returns if the given identifier looks quoted or not according to
2195 * the database convention for quoting identifiers .
2197 * @note Do not use this to determine if untrusted input is safe.
2198 * A malicious user can trick this function.
2199 * @param string $name
2202 public function isQuotedIdentifier( $name ) {
2203 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2210 protected function escapeLikeInternal( $s ) {
2211 return addcslashes( $s, '\%_' );
2214 public function buildLike() {
2215 $params = func_get_args();
2217 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2218 $params = $params[0];
2223 foreach ( $params as $value ) {
2224 if ( $value instanceof LikeMatch
) {
2225 $s .= $value->toString();
2227 $s .= $this->escapeLikeInternal( $value );
2231 return " LIKE {$this->addQuotes( $s )} ";
2234 public function anyChar() {
2235 return new LikeMatch( '_' );
2238 public function anyString() {
2239 return new LikeMatch( '%' );
2242 public function nextSequenceValue( $seqName ) {
2247 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2248 * is only needed because a) MySQL must be as efficient as possible due to
2249 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2250 * which index to pick. Anyway, other databases might have different
2251 * indexes on a given table. So don't bother overriding this unless you're
2253 * @param string $index
2256 public function useIndexClause( $index ) {
2261 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2262 * is only needed because a) MySQL must be as efficient as possible due to
2263 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2264 * which index to pick. Anyway, other databases might have different
2265 * indexes on a given table. So don't bother overriding this unless you're
2267 * @param string $index
2270 public function ignoreIndexClause( $index ) {
2274 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2275 $quotedTable = $this->tableName( $table );
2277 if ( count( $rows ) == 0 ) {
2282 if ( !is_array( reset( $rows ) ) ) {
2286 // @FXIME: this is not atomic, but a trx would break affectedRows()
2287 foreach ( $rows as $row ) {
2288 # Delete rows which collide
2289 if ( $uniqueIndexes ) {
2290 $sql = "DELETE FROM $quotedTable WHERE ";
2292 foreach ( $uniqueIndexes as $index ) {
2299 if ( is_array( $index ) ) {
2301 foreach ( $index as $col ) {
2307 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2310 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2314 $this->query( $sql, $fname );
2317 # Now insert the row
2318 $this->insert( $table, $row, $fname );
2323 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2326 * @param string $table Table name
2327 * @param array|string $rows Row(s) to insert
2328 * @param string $fname Caller function name
2330 * @return ResultWrapper
2332 protected function nativeReplace( $table, $rows, $fname ) {
2333 $table = $this->tableName( $table );
2336 if ( !is_array( reset( $rows ) ) ) {
2340 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2343 foreach ( $rows as $row ) {
2350 $sql .= '(' . $this->makeList( $row ) . ')';
2353 return $this->query( $sql, $fname );
2356 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2359 if ( !count( $rows ) ) {
2360 return true; // nothing to do
2363 if ( !is_array( reset( $rows ) ) ) {
2367 if ( count( $uniqueIndexes ) ) {
2368 $clauses = []; // list WHERE clauses that each identify a single row
2369 foreach ( $rows as $row ) {
2370 foreach ( $uniqueIndexes as $index ) {
2371 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2372 $rowKey = []; // unique key to this row
2373 foreach ( $index as $column ) {
2374 $rowKey[$column] = $row[$column];
2376 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2379 $where = [ $this->makeList( $clauses, LIST_OR
) ];
2384 $useTrx = !$this->mTrxLevel
;
2386 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2389 # Update any existing conflicting row(s)
2390 if ( $where !== false ) {
2391 $ok = $this->update( $table, $set, $where, $fname );
2395 # Now insert any non-conflicting row(s)
2396 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2397 } catch ( Exception
$e ) {
2399 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2404 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2410 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2414 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2417 $delTable = $this->tableName( $delTable );
2418 $joinTable = $this->tableName( $joinTable );
2419 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2420 if ( $conds != '*' ) {
2421 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2425 $this->query( $sql, $fname );
2429 * Returns the size of a text field, or -1 for "unlimited"
2431 * @param string $table
2432 * @param string $field
2435 public function textFieldSize( $table, $field ) {
2436 $table = $this->tableName( $table );
2437 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2438 $res = $this->query( $sql, __METHOD__
);
2439 $row = $this->fetchObject( $res );
2443 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2453 * A string to insert into queries to show that they're low-priority, like
2454 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2455 * string and nothing bad should happen.
2457 * @return string Returns the text of the low priority option if it is
2458 * supported, or a blank string otherwise
2460 public function lowPriorityOption() {
2464 public function delete( $table, $conds, $fname = __METHOD__
) {
2466 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2469 $table = $this->tableName( $table );
2470 $sql = "DELETE FROM $table";
2472 if ( $conds != '*' ) {
2473 if ( is_array( $conds ) ) {
2474 $conds = $this->makeList( $conds, LIST_AND
);
2476 $sql .= ' WHERE ' . $conds;
2479 return $this->query( $sql, $fname );
2482 public function insertSelect(
2483 $destTable, $srcTable, $varMap, $conds,
2484 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2486 if ( $this->cliMode
) {
2487 // For massive migrations with downtime, we don't want to select everything
2488 // into memory and OOM, so do all this native on the server side if possible.
2489 return $this->nativeInsertSelect(
2500 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2501 // on only the master (without needing row-based-replication). It also makes it easy to
2502 // know how big the INSERT is going to be.
2504 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2505 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2507 $selectOptions[] = 'FOR UPDATE';
2508 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2514 foreach ( $res as $row ) {
2515 $rows[] = (array)$row;
2518 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2521 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2522 $fname = __METHOD__
,
2523 $insertOptions = [], $selectOptions = []
2525 $destTable = $this->tableName( $destTable );
2527 if ( !is_array( $insertOptions ) ) {
2528 $insertOptions = [ $insertOptions ];
2531 $insertOptions = $this->makeInsertOptions( $insertOptions );
2533 if ( !is_array( $selectOptions ) ) {
2534 $selectOptions = [ $selectOptions ];
2537 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2540 if ( is_array( $srcTable ) ) {
2541 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2543 $srcTable = $this->tableName( $srcTable );
2546 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2547 " SELECT $startOpts " . implode( ',', $varMap ) .
2548 " FROM $srcTable $useIndex $ignoreIndex ";
2550 if ( $conds != '*' ) {
2551 if ( is_array( $conds ) ) {
2552 $conds = $this->makeList( $conds, LIST_AND
);
2554 $sql .= " WHERE $conds";
2557 $sql .= " $tailOpts";
2559 return $this->query( $sql, $fname );
2563 * Construct a LIMIT query with optional offset. This is used for query
2564 * pages. The SQL should be adjusted so that only the first $limit rows
2565 * are returned. If $offset is provided as well, then the first $offset
2566 * rows should be discarded, and the next $limit rows should be returned.
2567 * If the result of the query is not ordered, then the rows to be returned
2568 * are theoretically arbitrary.
2570 * $sql is expected to be a SELECT, if that makes a difference.
2572 * The version provided by default works in MySQL and SQLite. It will very
2573 * likely need to be overridden for most other DBMSes.
2575 * @param string $sql SQL query we will append the limit too
2576 * @param int $limit The SQL limit
2577 * @param int|bool $offset The SQL offset (default false)
2578 * @throws DBUnexpectedError
2581 public function limitResult( $sql, $limit, $offset = false ) {
2582 if ( !is_numeric( $limit ) ) {
2583 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2586 return "$sql LIMIT "
2587 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2591 public function unionSupportsOrderAndLimit() {
2592 return true; // True for almost every DB supported
2595 public function unionQueries( $sqls, $all ) {
2596 $glue = $all ?
') UNION ALL (' : ') UNION (';
2598 return '(' . implode( $glue, $sqls ) . ')';
2601 public function conditional( $cond, $trueVal, $falseVal ) {
2602 if ( is_array( $cond ) ) {
2603 $cond = $this->makeList( $cond, LIST_AND
);
2606 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2609 public function strreplace( $orig, $old, $new ) {
2610 return "REPLACE({$orig}, {$old}, {$new})";
2613 public function getServerUptime() {
2617 public function wasDeadlock() {
2621 public function wasLockTimeout() {
2625 public function wasErrorReissuable() {
2629 public function wasReadOnlyError() {
2634 * Determines if the given query error was a connection drop
2637 * @param integer|string $errno
2640 public function wasConnectionError( $errno ) {
2645 * Perform a deadlock-prone transaction.
2647 * This function invokes a callback function to perform a set of write
2648 * queries. If a deadlock occurs during the processing, the transaction
2649 * will be rolled back and the callback function will be called again.
2651 * Avoid using this method outside of Job or Maintenance classes.
2654 * $dbw->deadlockLoop( callback, ... );
2656 * Extra arguments are passed through to the specified callback function.
2657 * This method requires that no transactions are already active to avoid
2658 * causing premature commits or exceptions.
2660 * Returns whatever the callback function returned on its successful,
2661 * iteration, or false on error, for example if the retry limit was
2665 * @throws DBUnexpectedError
2668 public function deadlockLoop() {
2669 $args = func_get_args();
2670 $function = array_shift( $args );
2671 $tries = self
::DEADLOCK_TRIES
;
2673 $this->begin( __METHOD__
);
2676 /** @var Exception $e */
2680 $retVal = call_user_func_array( $function, $args );
2682 } catch ( DBQueryError
$e ) {
2683 if ( $this->wasDeadlock() ) {
2684 // Retry after a randomized delay
2685 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2687 // Throw the error back up
2691 } while ( --$tries > 0 );
2693 if ( $tries <= 0 ) {
2694 // Too many deadlocks; give up
2695 $this->rollback( __METHOD__
);
2698 $this->commit( __METHOD__
);
2704 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2705 # Real waits are implemented in the subclass.
2709 public function getSlavePos() {
2714 public function getMasterPos() {
2719 public function serverIsReadOnly() {
2723 final public function onTransactionResolution( callable
$callback ) {
2724 if ( !$this->mTrxLevel
) {
2725 throw new DBUnexpectedError( $this, "No transaction is active." );
2727 $this->mTrxEndCallbacks
[] = [ $callback, wfGetCaller() ];
2730 final public function onTransactionIdle( callable
$callback ) {
2731 $this->mTrxIdleCallbacks
[] = [ $callback, wfGetCaller() ];
2732 if ( !$this->mTrxLevel
) {
2733 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2737 final public function onTransactionPreCommitOrIdle( callable
$callback ) {
2738 if ( $this->mTrxLevel
) {
2739 $this->mTrxPreCommitCallbacks
[] = [ $callback, wfGetCaller() ];
2741 // If no transaction is active, then make one for this callback
2742 $this->startAtomic( __METHOD__
);
2744 call_user_func( $callback );
2745 $this->endAtomic( __METHOD__
);
2746 } catch ( Exception
$e ) {
2747 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2753 final public function setTransactionListener( $name, callable
$callback = null ) {
2755 $this->mTrxRecurringCallbacks
[$name] = [ $callback, wfGetCaller() ];
2757 unset( $this->mTrxRecurringCallbacks
[$name] );
2762 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2764 * This method should not be used outside of Database/LoadBalancer
2766 * @param bool $suppress
2769 final public function setTrxEndCallbackSuppression( $suppress ) {
2770 $this->mTrxEndCallbacksSuppressed
= $suppress;
2774 * Actually run and consume any "on transaction idle/resolution" callbacks.
2776 * This method should not be used outside of Database/LoadBalancer
2778 * @param integer $trigger IDatabase::TRIGGER_* constant
2782 public function runOnTransactionIdleCallbacks( $trigger ) {
2783 if ( $this->mTrxEndCallbacksSuppressed
) {
2787 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2788 /** @var Exception $e */
2789 $e = null; // first exception
2790 do { // callbacks may add callbacks :)
2791 $callbacks = array_merge(
2792 $this->mTrxIdleCallbacks
,
2793 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2795 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2796 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2797 foreach ( $callbacks as $callback ) {
2799 list( $phpCallback ) = $callback;
2800 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2801 call_user_func_array( $phpCallback, [ $trigger ] );
2803 $this->setFlag( DBO_TRX
); // restore automatic begin()
2805 $this->clearFlag( DBO_TRX
); // restore auto-commit
2807 } catch ( Exception
$ex ) {
2808 MWExceptionHandler
::logException( $ex );
2810 // Some callbacks may use startAtomic/endAtomic, so make sure
2811 // their transactions are ended so other callbacks don't fail
2812 if ( $this->trxLevel() ) {
2813 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2817 } while ( count( $this->mTrxIdleCallbacks
) );
2819 if ( $e instanceof Exception
) {
2820 throw $e; // re-throw any first exception
2825 * Actually run and consume any "on transaction pre-commit" callbacks.
2827 * This method should not be used outside of Database/LoadBalancer
2832 public function runOnTransactionPreCommitCallbacks() {
2833 $e = null; // first exception
2834 do { // callbacks may add callbacks :)
2835 $callbacks = $this->mTrxPreCommitCallbacks
;
2836 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2837 foreach ( $callbacks as $callback ) {
2839 list( $phpCallback ) = $callback;
2840 call_user_func( $phpCallback );
2841 } catch ( Exception
$ex ) {
2842 MWExceptionHandler
::logException( $ex );
2846 } while ( count( $this->mTrxPreCommitCallbacks
) );
2848 if ( $e instanceof Exception
) {
2849 throw $e; // re-throw any first exception
2854 * Actually run any "transaction listener" callbacks.
2856 * This method should not be used outside of Database/LoadBalancer
2858 * @param integer $trigger IDatabase::TRIGGER_* constant
2862 public function runTransactionListenerCallbacks( $trigger ) {
2863 if ( $this->mTrxEndCallbacksSuppressed
) {
2867 /** @var Exception $e */
2868 $e = null; // first exception
2870 foreach ( $this->mTrxRecurringCallbacks
as $callback ) {
2872 list( $phpCallback ) = $callback;
2873 $phpCallback( $trigger, $this );
2874 } catch ( Exception
$ex ) {
2875 MWExceptionHandler
::logException( $ex );
2880 if ( $e instanceof Exception
) {
2881 throw $e; // re-throw any first exception
2885 final public function startAtomic( $fname = __METHOD__
) {
2886 if ( !$this->mTrxLevel
) {
2887 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2888 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2889 // in all changes being in one transaction to keep requests transactional.
2890 if ( !$this->getFlag( DBO_TRX
) ) {
2891 $this->mTrxAutomaticAtomic
= true;
2895 $this->mTrxAtomicLevels
[] = $fname;
2898 final public function endAtomic( $fname = __METHOD__
) {
2899 if ( !$this->mTrxLevel
) {
2900 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2902 if ( !$this->mTrxAtomicLevels ||
2903 array_pop( $this->mTrxAtomicLevels
) !== $fname
2905 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2908 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2909 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2913 final public function doAtomicSection( $fname, callable
$callback ) {
2914 $this->startAtomic( $fname );
2916 $res = call_user_func_array( $callback, [ $this, $fname ] );
2917 } catch ( Exception
$e ) {
2918 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2921 $this->endAtomic( $fname );
2926 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2927 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2928 if ( $this->mTrxLevel
) {
2929 if ( $this->mTrxAtomicLevels
) {
2930 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2931 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2932 throw new DBUnexpectedError( $this, $msg );
2933 } elseif ( !$this->mTrxAutomatic
) {
2934 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2935 throw new DBUnexpectedError( $this, $msg );
2937 // @TODO: make this an exception at some point
2938 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2939 wfLogDBError( $msg );
2941 return; // join the main transaction set
2943 } elseif ( $this->getFlag( DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2944 // @TODO: make this an exception at some point
2945 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2946 wfLogDBError( $msg );
2948 return; // let any writes be in the main transaction
2951 // Avoid fatals if close() was called
2952 $this->assertOpen();
2954 $this->doBegin( $fname );
2955 $this->mTrxTimestamp
= microtime( true );
2956 $this->mTrxFname
= $fname;
2957 $this->mTrxDoneWrites
= false;
2958 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2959 $this->mTrxAutomaticAtomic
= false;
2960 $this->mTrxAtomicLevels
= [];
2961 $this->mTrxShortId
= wfRandomString( 12 );
2962 $this->mTrxWriteDuration
= 0.0;
2963 $this->mTrxWriteQueryCount
= 0;
2964 $this->mTrxWriteAdjDuration
= 0.0;
2965 $this->mTrxWriteAdjQueryCount
= 0;
2966 $this->mTrxWriteCallers
= [];
2967 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2968 // Get an estimate of the replica DB lag before then, treating estimate staleness
2969 // as lag itself just to be safe
2970 $status = $this->getApproximateLagStatus();
2971 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2975 * Issues the BEGIN command to the database server.
2977 * @see DatabaseBase::begin()
2978 * @param string $fname
2980 protected function doBegin( $fname ) {
2981 $this->query( 'BEGIN', $fname );
2982 $this->mTrxLevel
= 1;
2985 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2986 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2987 // There are still atomic sections open. This cannot be ignored
2988 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2989 throw new DBUnexpectedError(
2991 "$fname: Got COMMIT while atomic sections $levels are still open."
2995 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2996 if ( !$this->mTrxLevel
) {
2997 return; // nothing to do
2998 } elseif ( !$this->mTrxAutomatic
) {
2999 throw new DBUnexpectedError(
3001 "$fname: Flushing an explicit transaction, getting out of sync."
3005 if ( !$this->mTrxLevel
) {
3006 wfWarn( "$fname: No transaction to commit, something got out of sync." );
3007 return; // nothing to do
3008 } elseif ( $this->mTrxAutomatic
) {
3009 // @TODO: make this an exception at some point
3010 $msg = "$fname: Explicit commit of implicit transaction.";
3011 wfLogDBError( $msg );
3013 return; // wait for the main transaction set commit round
3017 // Avoid fatals if close() was called
3018 $this->assertOpen();
3020 $this->runOnTransactionPreCommitCallbacks();
3021 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3022 $this->doCommit( $fname );
3023 if ( $this->mTrxDoneWrites
) {
3024 $this->mDoneWrites
= microtime( true );
3025 $this->trxProfiler
->transactionWritingOut(
3026 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
3029 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3030 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3034 * Issues the COMMIT command to the database server.
3036 * @see DatabaseBase::commit()
3037 * @param string $fname
3039 protected function doCommit( $fname ) {
3040 if ( $this->mTrxLevel
) {
3041 $this->query( 'COMMIT', $fname );
3042 $this->mTrxLevel
= 0;
3046 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3047 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3048 if ( !$this->mTrxLevel
) {
3049 return; // nothing to do
3052 if ( !$this->mTrxLevel
) {
3053 wfWarn( "$fname: No transaction to rollback, something got out of sync." );
3054 return; // nothing to do
3055 } elseif ( $this->getFlag( DBO_TRX
) ) {
3056 throw new DBUnexpectedError(
3058 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3063 // Avoid fatals if close() was called
3064 $this->assertOpen();
3066 $this->doRollback( $fname );
3067 $this->mTrxAtomicLevels
= [];
3068 if ( $this->mTrxDoneWrites
) {
3069 $this->trxProfiler
->transactionWritingOut(
3070 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3073 $this->mTrxIdleCallbacks
= []; // clear
3074 $this->mTrxPreCommitCallbacks
= []; // clear
3075 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3076 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3080 * Issues the ROLLBACK command to the database server.
3082 * @see DatabaseBase::rollback()
3083 * @param string $fname
3085 protected function doRollback( $fname ) {
3086 if ( $this->mTrxLevel
) {
3087 # Disconnects cause rollback anyway, so ignore those errors
3088 $ignoreErrors = true;
3089 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3090 $this->mTrxLevel
= 0;
3094 public function flushSnapshot( $fname = __METHOD__
) {
3095 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3096 // This only flushes transactions to clear snapshots, not to write data
3097 throw new DBUnexpectedError(
3099 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3103 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3106 public function explicitTrxActive() {
3107 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
3111 * Creates a new table with structure copied from existing table
3112 * Note that unlike most database abstraction functions, this function does not
3113 * automatically append database prefix, because it works at a lower
3114 * abstraction level.
3115 * The table names passed to this function shall not be quoted (this
3116 * function calls addIdentifierQuotes when needed).
3118 * @param string $oldName Name of table whose structure should be copied
3119 * @param string $newName Name of table to be created
3120 * @param bool $temporary Whether the new table should be temporary
3121 * @param string $fname Calling function name
3122 * @throws MWException
3123 * @return bool True if operation was successful
3125 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3128 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3131 function listTables( $prefix = null, $fname = __METHOD__
) {
3132 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3136 * Reset the views process cache set by listViews()
3139 final public function clearViewsCache() {
3140 $this->allViews
= null;
3144 * Lists all the VIEWs in the database
3146 * For caching purposes the list of all views should be stored in
3147 * $this->allViews. The process cache can be cleared with clearViewsCache()
3149 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3150 * @param string $fname Name of calling function
3151 * @throws MWException
3155 public function listViews( $prefix = null, $fname = __METHOD__
) {
3156 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3160 * Differentiates between a TABLE and a VIEW
3162 * @param string $name Name of the database-structure to test.
3163 * @throws MWException
3167 public function isView( $name ) {
3168 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3171 public function timestamp( $ts = 0 ) {
3172 return wfTimestamp( TS_MW
, $ts );
3175 public function timestampOrNull( $ts = null ) {
3176 if ( is_null( $ts ) ) {
3179 return $this->timestamp( $ts );
3184 * Take the result from a query, and wrap it in a ResultWrapper if
3185 * necessary. Boolean values are passed through as is, to indicate success
3186 * of write queries or failure.
3188 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3189 * resource, and it was necessary to call this function to convert it to
3190 * a wrapper. Nowadays, raw database objects are never exposed to external
3191 * callers, so this is unnecessary in external code.
3193 * @param bool|ResultWrapper|resource|object $result
3194 * @return bool|ResultWrapper
3196 protected function resultObject( $result ) {
3199 } elseif ( $result instanceof ResultWrapper
) {
3201 } elseif ( $result === true ) {
3202 // Successful write query
3205 return new ResultWrapper( $this, $result );
3209 public function ping( &$rtt = null ) {
3210 // Avoid hitting the server if it was hit recently
3211 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3212 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
3213 $rtt = $this->mRTTEstimate
;
3214 return true; // don't care about $rtt
3218 // This will reconnect if possible or return false if not
3219 $this->clearFlag( DBO_TRX
, self
::REMEMBER_PRIOR
);
3220 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3221 $this->restoreFlags( self
::RESTORE_PRIOR
);
3224 $rtt = $this->mRTTEstimate
;
3233 protected function reconnect() {
3234 $this->closeConnection();
3235 $this->mOpened
= false;
3236 $this->mConn
= false;
3238 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3239 $this->lastPing
= microtime( true );
3241 } catch ( DBConnectionError
$e ) {
3248 public function getSessionLagStatus() {
3249 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3253 * Get the replica DB lag when the current transaction started
3255 * This is useful when transactions might use snapshot isolation
3256 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3257 * is this lag plus transaction duration. If they don't, it is still
3258 * safe to be pessimistic. This returns null if there is no transaction.
3260 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3263 public function getTransactionLagStatus() {
3264 return $this->mTrxLevel
3265 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3270 * Get a replica DB lag estimate for this server
3272 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3275 public function getApproximateLagStatus() {
3277 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3278 'since' => microtime( true )
3283 * Merge the result of getSessionLagStatus() for several DBs
3284 * using the most pessimistic values to estimate the lag of
3285 * any data derived from them in combination
3287 * This is information is useful for caching modules
3289 * @see WANObjectCache::set()
3290 * @see WANObjectCache::getWithSetCallback()
3292 * @param IDatabase $db1
3293 * @param IDatabase ...
3294 * @return array Map of values:
3295 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3296 * - since: oldest UNIX timestamp of any of the DB lag estimates
3297 * - pending: whether any of the DBs have uncommitted changes
3300 public static function getCacheSetOptions( IDatabase
$db1 ) {
3301 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3302 foreach ( func_get_args() as $db ) {
3303 /** @var IDatabase $db */
3304 $status = $db->getSessionLagStatus();
3305 if ( $status['lag'] === false ) {
3306 $res['lag'] = false;
3307 } elseif ( $res['lag'] !== false ) {
3308 $res['lag'] = max( $res['lag'], $status['lag'] );
3310 $res['since'] = min( $res['since'], $status['since'] );
3311 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3317 public function getLag() {
3321 function maxListLen() {
3325 public function encodeBlob( $b ) {
3329 public function decodeBlob( $b ) {
3330 if ( $b instanceof Blob
) {
3336 public function setSessionOptions( array $options ) {
3340 * Read and execute SQL commands from a file.
3342 * Returns true on success, error string or exception on failure (depending
3343 * on object's error ignore settings).
3345 * @param string $filename File name to open
3346 * @param bool|callable $lineCallback Optional function called before reading each line
3347 * @param bool|callable $resultCallback Optional function called for each MySQL result
3348 * @param bool|string $fname Calling function name or false if name should be
3349 * generated dynamically using $filename
3350 * @param bool|callable $inputCallback Optional function called for each
3351 * complete line sent
3352 * @throws Exception|MWException
3353 * @return bool|string
3355 public function sourceFile(
3356 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3358 MediaWiki\
suppressWarnings();
3359 $fp = fopen( $filename, 'r' );
3360 MediaWiki\restoreWarnings
();
3362 if ( false === $fp ) {
3363 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3367 $fname = __METHOD__
. "( $filename )";
3371 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3372 } catch ( Exception
$e ) {
3383 * Get the full path of a patch file. Originally based on archive()
3384 * from updaters.inc. Keep in mind this always returns a patch, as
3385 * it fails back to MySQL if no DB-specific patch can be found
3387 * @param string $patch The name of the patch, like patch-something.sql
3388 * @return string Full path to patch file
3390 public function patchPath( $patch ) {
3393 $dbType = $this->getType();
3394 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3395 return "$IP/maintenance/$dbType/archives/$patch";
3397 return "$IP/maintenance/archives/$patch";
3401 public function setSchemaVars( $vars ) {
3402 $this->mSchemaVars
= $vars;
3406 * Read and execute commands from an open file handle.
3408 * Returns true on success, error string or exception on failure (depending
3409 * on object's error ignore settings).
3411 * @param resource $fp File handle
3412 * @param bool|callable $lineCallback Optional function called before reading each query
3413 * @param bool|callable $resultCallback Optional function called for each MySQL result
3414 * @param string $fname Calling function name
3415 * @param bool|callable $inputCallback Optional function called for each complete query sent
3416 * @return bool|string
3418 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3419 $fname = __METHOD__
, $inputCallback = false
3423 while ( !feof( $fp ) ) {
3424 if ( $lineCallback ) {
3425 call_user_func( $lineCallback );
3428 $line = trim( fgets( $fp ) );
3430 if ( $line == '' ) {
3434 if ( '-' == $line[0] && '-' == $line[1] ) {
3442 $done = $this->streamStatementEnd( $cmd, $line );
3446 if ( $done ||
feof( $fp ) ) {
3447 $cmd = $this->replaceVars( $cmd );
3449 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3450 $res = $this->query( $cmd, $fname );
3452 if ( $resultCallback ) {
3453 call_user_func( $resultCallback, $res, $this );
3456 if ( false === $res ) {
3457 $err = $this->lastError();
3459 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3470 * Called by sourceStream() to check if we've reached a statement end
3472 * @param string $sql SQL assembled so far
3473 * @param string $newLine New line about to be added to $sql
3474 * @return bool Whether $newLine contains end of the statement
3476 public function streamStatementEnd( &$sql, &$newLine ) {
3477 if ( $this->delimiter
) {
3479 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3480 if ( $newLine != $prev ) {
3489 * Database independent variable replacement. Replaces a set of variables
3490 * in an SQL statement with their contents as given by $this->getSchemaVars().
3492 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3494 * - '{$var}' should be used for text and is passed through the database's
3496 * - `{$var}` should be used for identifiers (e.g. table and database names).
3497 * It is passed through the database's addIdentifierQuotes method which
3498 * can be overridden if the database uses something other than backticks.
3499 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3500 * database's tableName method.
3501 * - / *i* / passes the name that follows through the database's indexName method.
3502 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3503 * its use should be avoided. In 1.24 and older, string encoding was applied.
3505 * @param string $ins SQL statement to replace variables in
3506 * @return string The new SQL statement with variables replaced
3508 protected function replaceVars( $ins ) {
3509 $vars = $this->getSchemaVars();
3510 return preg_replace_callback(
3512 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3513 \'\{\$ (\w+) }\' | # 3. addQuotes
3514 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3515 /\*\$ (\w+) \*/ # 5. leave unencoded
3517 function ( $m ) use ( $vars ) {
3518 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3519 // check for both nonexistent keys *and* the empty string.
3520 if ( isset( $m[1] ) && $m[1] !== '' ) {
3521 if ( $m[1] === 'i' ) {
3522 return $this->indexName( $m[2] );
3524 return $this->tableName( $m[2] );
3526 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3527 return $this->addQuotes( $vars[$m[3]] );
3528 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3529 return $this->addIdentifierQuotes( $vars[$m[4]] );
3530 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3531 return $vars[$m[5]];
3541 * Get schema variables. If none have been set via setSchemaVars(), then
3542 * use some defaults from the current object.
3546 protected function getSchemaVars() {
3547 if ( $this->mSchemaVars
) {
3548 return $this->mSchemaVars
;
3550 return $this->getDefaultSchemaVars();
3555 * Get schema variables to use if none have been set via setSchemaVars().
3557 * Override this in derived classes to provide variables for tables.sql
3558 * and SQL patch files.
3562 protected function getDefaultSchemaVars() {
3566 public function lockIsFree( $lockName, $method ) {
3570 public function lock( $lockName, $method, $timeout = 5 ) {
3571 $this->mNamedLocksHeld
[$lockName] = 1;
3576 public function unlock( $lockName, $method ) {
3577 unset( $this->mNamedLocksHeld
[$lockName] );
3582 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3583 if ( $this->writesOrCallbacksPending() ) {
3584 // This only flushes transactions to clear snapshots, not to write data
3585 throw new DBUnexpectedError(
3587 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3591 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3595 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3596 if ( $this->trxLevel() ) {
3597 // There is a good chance an exception was thrown, causing any early return
3598 // from the caller. Let any error handler get a chance to issue rollback().
3599 // If there isn't one, let the error bubble up and trigger server-side rollback.
3600 $this->onTransactionResolution( function () use ( $lockKey, $fname ) {
3601 $this->unlock( $lockKey, $fname );
3604 $this->unlock( $lockKey, $fname );
3608 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
3613 public function namedLocksEnqueue() {
3618 * Lock specific tables
3620 * @param array $read Array of tables to lock for read access
3621 * @param array $write Array of tables to lock for write access
3622 * @param string $method Name of caller
3623 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3626 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3631 * Unlock specific tables
3633 * @param string $method The caller
3636 public function unlockTables( $method ) {
3642 * @param string $tableName
3643 * @param string $fName
3644 * @return bool|ResultWrapper
3647 public function dropTable( $tableName, $fName = __METHOD__
) {
3648 if ( !$this->tableExists( $tableName, $fName ) ) {
3651 $sql = "DROP TABLE " . $this->tableName( $tableName );
3652 if ( $this->cascadingDeletes() ) {
3656 return $this->query( $sql, $fName );
3660 * Get search engine class. All subclasses of this need to implement this
3661 * if they wish to use searching.
3665 public function getSearchEngine() {
3666 return 'SearchEngineDummy';
3669 public function getInfinity() {
3673 public function encodeExpiry( $expiry ) {
3674 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3675 ?
$this->getInfinity()
3676 : $this->timestamp( $expiry );
3679 public function decodeExpiry( $expiry, $format = TS_MW
) {
3680 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3682 : wfTimestamp( $format, $expiry );
3685 public function setBigSelects( $value = true ) {
3689 public function isReadOnly() {
3690 return ( $this->getReadOnlyReason() !== false );
3694 * @return string|bool Reason this DB is read-only or false if it is not
3696 protected function getReadOnlyReason() {
3697 $reason = $this->getLBInfo( 'readOnlyReason' );
3699 return is_string( $reason ) ?
$reason : false;
3706 public function __toString() {
3707 return (string)$this->mConn
;
3711 * Run a few simple sanity checks
3713 public function __destruct() {
3714 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3715 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3717 $danglingCallbacks = array_merge(
3718 $this->mTrxIdleCallbacks
,
3719 $this->mTrxPreCommitCallbacks
,
3720 $this->mTrxEndCallbacks
3722 if ( $danglingCallbacks ) {
3724 foreach ( $danglingCallbacks as $callbackInfo ) {
3725 $callers[] = $callbackInfo[1];
3727 $callers = implode( ', ', $callers );
3728 trigger_error( "DB transaction callbacks still pending (from $callers)." );
3736 abstract class Database
extends DatabaseBase
{
3737 // B/C until nothing type hints for DatabaseBase
3738 // @TODO: finish renaming DatabaseBase => Database