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;
63 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
64 protected $tableAliases = [];
68 /** @var BagOStuff APC cache */
70 /** @var LoggerInterface */
71 protected $connLogger;
72 /** @var LoggerInterface */
73 protected $queryLogger;
74 /** @var callback Error logging callback */
75 protected $errorLogger;
77 /** @var resource Database connection */
78 protected $mConn = null;
80 protected $mOpened = false;
82 /** @var array[] List of (callable, method name) */
83 protected $mTrxIdleCallbacks = [];
84 /** @var array[] List of (callable, method name) */
85 protected $mTrxPreCommitCallbacks = [];
86 /** @var array[] List of (callable, method name) */
87 protected $mTrxEndCallbacks = [];
88 /** @var array[] Map of (name => (callable, method name)) */
89 protected $mTrxRecurringCallbacks = [];
90 /** @var bool Whether to suppress triggering of transaction end callbacks */
91 protected $mTrxEndCallbacksSuppressed = false;
94 protected $mTablePrefix;
100 protected $mLBInfo = [];
101 /** @var bool|null */
102 protected $mDefaultBigSelects = null;
103 /** @var array|bool */
104 protected $mSchemaVars = false;
106 protected $mSessionVars = [];
107 /** @var array|null */
108 protected $preparedArgs;
109 /** @var string|bool|null Stashed value of html_errors INI setting */
110 protected $htmlErrors;
112 protected $delimiter = ';';
115 * Either 1 if a transaction is active or 0 otherwise.
116 * The other Trx fields may not be meaningfull if this is 0.
120 protected $mTrxLevel = 0;
122 * Either a short hexidecimal string if a transaction is active or ""
125 * @see DatabaseBase::mTrxLevel
127 protected $mTrxShortId = '';
129 * The UNIX time that the transaction started. Callers can assume that if
130 * snapshot isolation is used, then the data is *at least* up to date to that
131 * point (possibly more up-to-date since the first SELECT defines the snapshot).
134 * @see DatabaseBase::mTrxLevel
136 private $mTrxTimestamp = null;
137 /** @var float Lag estimate at the time of BEGIN */
138 private $mTrxReplicaLag = null;
140 * Remembers the function name given for starting the most recent transaction via begin().
141 * Used to provide additional context for error reporting.
144 * @see DatabaseBase::mTrxLevel
146 private $mTrxFname = null;
148 * Record if possible write queries were done in the last transaction started
151 * @see DatabaseBase::mTrxLevel
153 private $mTrxDoneWrites = false;
155 * Record if the current transaction was started implicitly due to DBO_TRX being set.
158 * @see DatabaseBase::mTrxLevel
160 private $mTrxAutomatic = false;
162 * Array of levels of atomicity within transactions
166 private $mTrxAtomicLevels = [];
168 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
172 private $mTrxAutomaticAtomic = false;
174 * Track the write query callers of the current transaction
178 private $mTrxWriteCallers = [];
180 * @var float Seconds spent in write queries for the current transaction
182 private $mTrxWriteDuration = 0.0;
184 * @var integer Number of write queries for the current transaction
186 private $mTrxWriteQueryCount = 0;
188 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
190 private $mTrxWriteAdjDuration = 0.0;
192 * @var integer Number of write queries counted in mTrxWriteAdjDuration
194 private $mTrxWriteAdjQueryCount = 0;
196 * @var float RTT time estimate
198 private $mRTTEstimate = 0.0;
200 /** @var array Map of (name => 1) for locks obtained via lock() */
201 private $mNamedLocksHeld = [];
203 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
204 private $lazyMasterHandle;
208 * @var resource File handle for upgrade
210 protected $fileHandle = null;
214 * @var string[] Process cache of VIEWs names in the database
216 protected $allViews = null;
218 /** @var float UNIX timestamp */
219 protected $lastPing = 0.0;
221 /** @var int[] Prior mFlags values */
222 private $priorFlags = [];
226 /** @var TransactionProfiler */
227 protected $trxProfiler;
232 * FIXME: It is possible to construct a Database object with no associated
233 * connection object, by specifying no parameters to __construct(). This
234 * feature is deprecated and should be removed.
236 * IDatabase classes should not be constructed directly in external
237 * code. DatabaseBase::factory() should be used instead.
239 * @param array $params Parameters passed from DatabaseBase::factory()
241 function __construct( array $params ) {
242 $server = $params['host'];
243 $user = $params['user'];
244 $password = $params['password'];
245 $dbName = $params['dbname'];
246 $flags = $params['flags'];
248 $this->mSchema
= $params['schema'];
249 $this->mTablePrefix
= $params['tablePrefix'];
251 $this->cliMode
= isset( $params['cliMode'] )
253 : ( PHP_SAPI
=== 'cli' );
255 $this->mFlags
= $flags;
256 if ( $this->mFlags
& DBO_DEFAULT
) {
257 if ( $this->cliMode
) {
258 $this->mFlags
&= ~DBO_TRX
;
260 $this->mFlags |
= DBO_TRX
;
264 $this->mSessionVars
= $params['variables'];
266 $this->srvCache
= isset( $params['srvCache'] )
267 ?
$params['srvCache']
268 : new HashBagOStuff();
270 $this->profiler
= isset( $params['profiler'] )
271 ?
$params['profiler']
272 : Profiler
::instance(); // @TODO: remove global state
273 $this->trxProfiler
= isset( $params['trxProfiler'] )
274 ?
$params['trxProfiler']
275 : new TransactionProfiler();
276 $this->connLogger
= isset( $params['connLogger'] )
277 ?
$params['connLogger']
278 : new \Psr\Log\
NullLogger();
279 $this->queryLogger
= isset( $params['queryLogger'] )
280 ?
$params['queryLogger']
281 : new \Psr\Log\
NullLogger();
284 $this->open( $server, $user, $password, $dbName );
289 * Given a DB type, construct the name of the appropriate child class of
290 * IDatabase. This is designed to replace all of the manual stuff like:
291 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
292 * as well as validate against the canonical list of DB types we have
294 * This factory function is mostly useful for when you need to connect to a
295 * database other than the MediaWiki default (such as for external auth,
296 * an extension, et cetera). Do not use this to connect to the MediaWiki
297 * database. Example uses in core:
298 * @see LoadBalancer::reallyOpenConnection()
299 * @see ForeignDBRepo::getMasterDB()
300 * @see WebInstallerDBConnect::execute()
304 * @param string $dbType A possible DB type
305 * @param array $p An array of options to pass to the constructor.
306 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
307 * @return IDatabase|null If the database driver or extension cannot be found
308 * @throws InvalidArgumentException If the database driver or extension cannot be found
310 final public static function factory( $dbType, $p = [] ) {
311 global $wgCommandLineMode;
313 $canonicalDBTypes = [
314 'mysql' => [ 'mysqli', 'mysql' ],
322 $dbType = strtolower( $dbType );
323 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
324 $possibleDrivers = $canonicalDBTypes[$dbType];
325 if ( !empty( $p['driver'] ) ) {
326 if ( in_array( $p['driver'], $possibleDrivers ) ) {
327 $driver = $p['driver'];
329 throw new InvalidArgumentException( __METHOD__
.
330 " type '$dbType' does not support driver '{$p['driver']}'" );
333 foreach ( $possibleDrivers as $posDriver ) {
334 if ( extension_loaded( $posDriver ) ) {
335 $driver = $posDriver;
343 if ( $driver === false ) {
344 throw new InvalidArgumentException( __METHOD__
.
345 " no viable database extension found for type '$dbType'" );
348 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
349 // and everything else doesn't use a schema (e.g. null)
350 // Although postgres and oracle support schemas, we don't use them (yet)
351 // to maintain backwards compatibility
353 'mssql' => 'get from global',
356 $class = 'Database' . ucfirst( $driver );
357 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
358 // Resolve some defaults for b/c
359 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
360 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
361 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
362 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
363 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
364 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
365 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
366 if ( !isset( $p['schema'] ) ) {
367 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : null;
369 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
370 $p['cliMode'] = $wgCommandLineMode;
372 $conn = new $class( $p );
373 if ( isset( $p['connLogger'] ) ) {
374 $conn->connLogger
= $p['connLogger'];
376 if ( isset( $p['queryLogger'] ) ) {
377 $conn->queryLogger
= $p['queryLogger'];
379 if ( isset( $p['errorLogger'] ) ) {
380 $conn->errorLogger
= $p['errorLogger'];
382 $conn->errorLogger
= [ MWExceptionHandler
::class, 'logException' ];
391 public function setLogger( LoggerInterface
$logger ) {
392 $this->queryLogger
= $logger;
395 public function getServerInfo() {
396 return $this->getServerVersion();
400 * @return string Command delimiter used by this database engine
402 public function getDelimiter() {
403 return $this->delimiter
;
407 * Boolean, controls output of large amounts of debug information.
408 * @param bool|null $debug
409 * - true to enable debugging
410 * - false to disable debugging
411 * - omitted or null to do nothing
413 * @return bool|null Previous value of the flag
415 public function debug( $debug = null ) {
416 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
419 public function bufferResults( $buffer = null ) {
420 if ( is_null( $buffer ) ) {
421 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
423 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
428 * Turns on (false) or off (true) the automatic generation and sending
429 * of a "we're sorry, but there has been a database error" page on
430 * database errors. Default is on (false). When turned off, the
431 * code should use lastErrno() and lastError() to handle the
432 * situation as appropriate.
434 * Do not use this function outside of the Database classes.
436 * @param null|bool $ignoreErrors
437 * @return bool The previous value of the flag.
439 protected function ignoreErrors( $ignoreErrors = null ) {
440 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
443 public function trxLevel() {
444 return $this->mTrxLevel
;
447 public function trxTimestamp() {
448 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
451 public function tablePrefix( $prefix = null ) {
452 return wfSetVar( $this->mTablePrefix
, $prefix );
455 public function dbSchema( $schema = null ) {
456 return wfSetVar( $this->mSchema
, $schema );
460 * Set the filehandle to copy write statements to.
462 * @param resource $fh File handle
464 public function setFileHandle( $fh ) {
465 $this->fileHandle
= $fh;
468 public function getLBInfo( $name = null ) {
469 if ( is_null( $name ) ) {
470 return $this->mLBInfo
;
472 if ( array_key_exists( $name, $this->mLBInfo
) ) {
473 return $this->mLBInfo
[$name];
480 public function setLBInfo( $name, $value = null ) {
481 if ( is_null( $value ) ) {
482 $this->mLBInfo
= $name;
484 $this->mLBInfo
[$name] = $value;
488 public function setLazyMasterHandle( IDatabase
$conn ) {
489 $this->lazyMasterHandle
= $conn;
493 * @return IDatabase|null
494 * @see setLazyMasterHandle()
497 public function getLazyMasterHandle() {
498 return $this->lazyMasterHandle
;
502 * @param TransactionProfiler $profiler
505 public function setTransactionProfiler( TransactionProfiler
$profiler ) {
506 $this->trxProfiler
= $profiler;
510 * Returns true if this database supports (and uses) cascading deletes
514 public function cascadingDeletes() {
519 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
523 public function cleanupTriggers() {
528 * Returns true if this database is strict about what can be put into an IP field.
529 * Specifically, it uses a NULL value instead of an empty string.
533 public function strictIPs() {
538 * Returns true if this database uses timestamps rather than integers
542 public function realTimestamps() {
546 public function implicitGroupby() {
550 public function implicitOrderby() {
555 * Returns true if this database can do a native search on IP columns
556 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
560 public function searchableIPs() {
565 * Returns true if this database can use functional indexes
569 public function functionalIndexes() {
573 public function lastQuery() {
574 return $this->mLastQuery
;
577 public function doneWrites() {
578 return (bool)$this->mDoneWrites
;
581 public function lastDoneWrites() {
582 return $this->mDoneWrites ?
: false;
585 public function writesPending() {
586 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
589 public function writesOrCallbacksPending() {
590 return $this->mTrxLevel
&& (
591 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
595 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
596 if ( !$this->mTrxLevel
) {
598 } elseif ( !$this->mTrxDoneWrites
) {
603 case self
::ESTIMATE_DB_APPLY
:
605 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
606 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
607 // For omitted queries, make them count as something at least
608 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
609 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
612 default: // everything
613 return $this->mTrxWriteDuration
;
617 public function pendingWriteCallers() {
618 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
621 public function isOpen() {
622 return $this->mOpened
;
625 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
626 if ( $remember === self
::REMEMBER_PRIOR
) {
627 array_push( $this->priorFlags
, $this->mFlags
);
629 $this->mFlags |
= $flag;
632 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
633 if ( $remember === self
::REMEMBER_PRIOR
) {
634 array_push( $this->priorFlags
, $this->mFlags
);
636 $this->mFlags
&= ~
$flag;
639 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
640 if ( !$this->priorFlags
) {
644 if ( $state === self
::RESTORE_INITIAL
) {
645 $this->mFlags
= reset( $this->priorFlags
);
646 $this->priorFlags
= [];
648 $this->mFlags
= array_pop( $this->priorFlags
);
652 public function getFlag( $flag ) {
653 return !!( $this->mFlags
& $flag );
656 public function getProperty( $name ) {
660 public function getWikiID() {
661 if ( $this->mTablePrefix
) {
662 return "{$this->mDBname}-{$this->mTablePrefix}";
664 return $this->mDBname
;
669 * Get information about an index into an object
670 * @param string $table Table name
671 * @param string $index Index name
672 * @param string $fname Calling function name
673 * @return mixed Database-specific index description class or false if the index does not exist
675 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
678 * Wrapper for addslashes()
680 * @param string $s String to be slashed.
681 * @return string Slashed string.
683 abstract function strencode( $s );
686 * Called by serialize. Throw an exception when DB connection is serialized.
687 * This causes problems on some database engines because the connection is
688 * not restored on unserialize.
690 public function __sleep() {
691 throw new RuntimeException( 'Database serialization may cause problems, since ' .
692 'the connection is not restored on wakeup.' );
695 protected function installErrorHandler() {
696 $this->mPHPError
= false;
697 $this->htmlErrors
= ini_set( 'html_errors', '0' );
698 set_error_handler( [ $this, 'connectionerrorLogger' ] );
702 * @return bool|string
704 protected function restoreErrorHandler() {
705 restore_error_handler();
706 if ( $this->htmlErrors
!== false ) {
707 ini_set( 'html_errors', $this->htmlErrors
);
709 if ( $this->mPHPError
) {
710 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
711 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
721 * @param string $errstr
723 public function connectionerrorLogger( $errno, $errstr ) {
724 $this->mPHPError
= $errstr;
728 * Create a log context to pass to PSR logging functions.
730 * @param array $extras Additional data to add to context
733 protected function getLogContext( array $extras = [] ) {
736 'db_server' => $this->mServer
,
737 'db_name' => $this->mDBname
,
738 'db_user' => $this->mUser
,
744 public function close() {
745 if ( $this->mConn
) {
746 if ( $this->trxLevel() ) {
747 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
750 $closed = $this->closeConnection();
751 $this->mConn
= false;
752 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
753 throw new RuntimeException( "Transaction callbacks still pending." );
757 $this->mOpened
= false;
763 * Make sure isOpen() returns true as a sanity check
765 * @throws DBUnexpectedError
767 protected function assertOpen() {
768 if ( !$this->isOpen() ) {
769 throw new DBUnexpectedError( $this, "DB connection was already closed." );
774 * Closes underlying database connection
776 * @return bool Whether connection was closed successfully
778 abstract protected function closeConnection();
780 function reportConnectionError( $error = 'Unknown error' ) {
781 $myError = $this->lastError();
787 throw new DBConnectionError( $this, $error );
791 * The DBMS-dependent part of query()
793 * @param string $sql SQL query.
794 * @return ResultWrapper|bool Result object to feed to fetchObject,
795 * fetchRow, ...; or false on failure
797 abstract protected function doQuery( $sql );
800 * Determine whether a query writes to the DB.
801 * Should return true if unsure.
806 protected function isWriteQuery( $sql ) {
808 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
813 * @return string|null
815 protected function getQueryVerb( $sql ) {
816 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
820 * Determine whether a SQL statement is sensitive to isolation level.
821 * A SQL statement is considered transactable if its result could vary
822 * depending on the transaction isolation level. Operational commands
823 * such as 'SET' and 'SHOW' are not considered to be transactable.
828 protected function isTransactableQuery( $sql ) {
829 $verb = $this->getQueryVerb( $sql );
830 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
833 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
836 $priorWritesPending = $this->writesOrCallbacksPending();
837 $this->mLastQuery
= $sql;
839 $isWrite = $this->isWriteQuery( $sql );
841 $reason = $this->getReadOnlyReason();
842 if ( $reason !== false ) {
843 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
845 # Set a flag indicating that writes have been done
846 $this->mDoneWrites
= microtime( true );
849 # Add a comment for easy SHOW PROCESSLIST interpretation
850 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
851 $userName = $wgUser->getName();
852 if ( mb_strlen( $userName ) > 15 ) {
853 $userName = mb_substr( $userName, 0, 15 ) . '...';
855 $userName = str_replace( '/', '', $userName );
860 // Add trace comment to the begin of the sql string, right after the operator.
861 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
862 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
864 # Start implicit transactions that wrap the request if DBO_TRX is enabled
865 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
)
866 && $this->isTransactableQuery( $sql )
868 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
869 $this->mTrxAutomatic
= true;
872 # Keep track of whether the transaction has write queries pending
873 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
874 $this->mTrxDoneWrites
= true;
875 $this->trxProfiler
->transactionWritingIn(
876 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
879 if ( $this->debug() ) {
880 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
883 # Avoid fatals if close() was called
886 # Send the query to the server
887 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
889 # Try reconnecting if the connection was lost
890 if ( false === $ret && $this->wasErrorReissuable() ) {
891 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
892 # Stash the last error values before anything might clear them
893 $lastError = $this->lastError();
894 $lastErrno = $this->lastErrno();
895 # Update state tracking to reflect transaction loss due to disconnection
896 $this->handleTransactionLoss();
897 if ( $this->reconnect() ) {
898 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
899 $this->connLogger
->warning( $msg );
900 $this->queryLogger
->warning(
901 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
903 if ( !$recoverable ) {
904 # Callers may catch the exception and continue to use the DB
905 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
907 # Should be safe to silently retry the query
908 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
911 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
912 $this->connLogger
->error( $msg );
916 if ( false === $ret ) {
917 # Deadlocks cause the entire transaction to abort, not just the statement.
918 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
919 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
920 if ( $this->wasDeadlock() ) {
921 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
922 $tempIgnore = false; // not recoverable
924 # Update state tracking to reflect transaction loss
925 $this->handleTransactionLoss();
928 $this->reportQueryError(
929 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
932 $res = $this->resultObject( $ret );
937 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
938 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
939 # generalizeSQL() will probably cut down the query to reasonable
940 # logging size most of the time. The substr is really just a sanity check.
942 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
944 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
947 # Include query transaction state
948 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
950 $startTime = microtime( true );
951 $this->profiler
->profileIn( $queryProf );
952 $ret = $this->doQuery( $commentedSql );
953 $this->profiler
->profileOut( $queryProf );
954 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
956 unset( $queryProfSection ); // profile out (if set)
958 if ( $ret !== false ) {
959 $this->lastPing
= $startTime;
960 if ( $isWrite && $this->mTrxLevel
) {
961 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
962 $this->mTrxWriteCallers
[] = $fname;
966 if ( $sql === self
::PING_QUERY
) {
967 $this->mRTTEstimate
= $queryRuntime;
970 $this->trxProfiler
->recordQueryCompletion(
971 $queryProf, $startTime, $isWrite, $this->affectedRows()
973 MWDebug
::query( $sql, $fname, $isMaster, $queryRuntime );
979 * Update the estimated run-time of a query, not counting large row lock times
981 * LoadBalancer can be set to rollback transactions that will create huge replication
982 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
983 * queries, like inserting a row can take a long time due to row locking. This method
984 * uses some simple heuristics to discount those cases.
986 * @param string $sql A SQL write query
987 * @param float $runtime Total runtime, including RTT
989 private function updateTrxWriteQueryTime( $sql, $runtime ) {
990 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
991 $indicativeOfReplicaRuntime = true;
992 if ( $runtime > self
::SLOW_WRITE_SEC
) {
993 $verb = $this->getQueryVerb( $sql );
994 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
995 if ( $verb === 'INSERT' ) {
996 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
997 } elseif ( $verb === 'REPLACE' ) {
998 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1002 $this->mTrxWriteDuration +
= $runtime;
1003 $this->mTrxWriteQueryCount +
= 1;
1004 if ( $indicativeOfReplicaRuntime ) {
1005 $this->mTrxWriteAdjDuration +
= $runtime;
1006 $this->mTrxWriteAdjQueryCount +
= 1;
1010 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1011 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1012 # Dropped connections also mean that named locks are automatically released.
1013 # Only allow error suppression in autocommit mode or when the lost transaction
1014 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1015 if ( $this->mNamedLocksHeld
) {
1016 return false; // possible critical section violation
1017 } elseif ( $sql === 'COMMIT' ) {
1018 return !$priorWritesPending; // nothing written anyway? (T127428)
1019 } elseif ( $sql === 'ROLLBACK' ) {
1020 return true; // transaction lost...which is also what was requested :)
1021 } elseif ( $this->explicitTrxActive() ) {
1022 return false; // don't drop atomocity
1023 } elseif ( $priorWritesPending ) {
1024 return false; // prior writes lost from implicit transaction
1030 private function handleTransactionLoss() {
1031 $this->mTrxLevel
= 0;
1032 $this->mTrxIdleCallbacks
= []; // bug 65263
1033 $this->mTrxPreCommitCallbacks
= []; // bug 65263
1035 // Handle callbacks in mTrxEndCallbacks
1036 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1037 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1039 } catch ( Exception
$e ) {
1040 // Already logged; move on...
1045 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1046 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1047 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1049 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1050 $this->queryLogger
->error(
1051 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1052 $this->getLogContext( [
1053 'method' => __METHOD__
,
1056 'sql1line' => $sql1line,
1060 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1061 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1066 * Intended to be compatible with the PEAR::DB wrapper functions.
1067 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1069 * ? = scalar value, quoted as necessary
1070 * ! = raw SQL bit (a function for instance)
1071 * & = filename; reads the file and inserts as a blob
1072 * (we don't use this though...)
1074 * @param string $sql
1075 * @param string $func
1079 protected function prepare( $sql, $func = __METHOD__
) {
1080 /* MySQL doesn't support prepared statements (yet), so just
1081 * pack up the query for reference. We'll manually replace
1084 return [ 'query' => $sql, 'func' => $func ];
1088 * Free a prepared query, generated by prepare().
1089 * @param string $prepared
1091 protected function freePrepared( $prepared ) {
1092 /* No-op by default */
1096 * Execute a prepared query with the various arguments
1097 * @param string $prepared The prepared sql
1098 * @param mixed $args Either an array here, or put scalars as varargs
1100 * @return ResultWrapper
1102 public function execute( $prepared, $args = null ) {
1103 if ( !is_array( $args ) ) {
1105 $args = func_get_args();
1106 array_shift( $args );
1109 $sql = $this->fillPrepared( $prepared['query'], $args );
1111 return $this->query( $sql, $prepared['func'] );
1115 * For faking prepared SQL statements on DBs that don't support it directly.
1117 * @param string $preparedQuery A 'preparable' SQL statement
1118 * @param array $args Array of Arguments to fill it with
1119 * @return string Executable SQL
1121 public function fillPrepared( $preparedQuery, $args ) {
1123 $this->preparedArgs
=& $args;
1125 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1126 [ &$this, 'fillPreparedArg' ], $preparedQuery );
1130 * preg_callback func for fillPrepared()
1131 * The arguments should be in $this->preparedArgs and must not be touched
1132 * while we're doing this.
1134 * @param array $matches
1135 * @throws DBUnexpectedError
1138 protected function fillPreparedArg( $matches ) {
1139 switch ( $matches[1] ) {
1148 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1150 switch ( $matches[1] ) {
1152 return $this->addQuotes( $arg );
1156 # return $this->addQuotes( file_get_contents( $arg ) );
1157 throw new DBUnexpectedError(
1159 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1162 throw new DBUnexpectedError(
1164 'Received invalid match. This should never happen!'
1169 public function freeResult( $res ) {
1172 public function selectField(
1173 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1175 if ( $var === '*' ) { // sanity
1176 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1179 if ( !is_array( $options ) ) {
1180 $options = [ $options ];
1183 $options['LIMIT'] = 1;
1185 $res = $this->select( $table, $var, $cond, $fname, $options );
1186 if ( $res === false ||
!$this->numRows( $res ) ) {
1190 $row = $this->fetchRow( $res );
1192 if ( $row !== false ) {
1193 return reset( $row );
1199 public function selectFieldValues(
1200 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1202 if ( $var === '*' ) { // sanity
1203 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1204 } elseif ( !is_string( $var ) ) { // sanity
1205 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1208 if ( !is_array( $options ) ) {
1209 $options = [ $options ];
1212 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1213 if ( $res === false ) {
1218 foreach ( $res as $row ) {
1219 $values[] = $row->$var;
1226 * Returns an optional USE INDEX clause to go after the table, and a
1227 * string to go at the end of the query.
1229 * @param array $options Associative array of options to be turned into
1230 * an SQL query, valid keys are listed in the function.
1232 * @see DatabaseBase::select()
1234 public function makeSelectOptions( $options ) {
1235 $preLimitTail = $postLimitTail = '';
1240 foreach ( $options as $key => $option ) {
1241 if ( is_numeric( $key ) ) {
1242 $noKeyOptions[$option] = true;
1246 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1248 $preLimitTail .= $this->makeOrderBy( $options );
1250 // if (isset($options['LIMIT'])) {
1251 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1252 // isset($options['OFFSET']) ? $options['OFFSET']
1256 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1257 $postLimitTail .= ' FOR UPDATE';
1260 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1261 $postLimitTail .= ' LOCK IN SHARE MODE';
1264 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1265 $startOpts .= 'DISTINCT';
1268 # Various MySQL extensions
1269 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1270 $startOpts .= ' /*! STRAIGHT_JOIN */';
1273 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1274 $startOpts .= ' HIGH_PRIORITY';
1277 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1278 $startOpts .= ' SQL_BIG_RESULT';
1281 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1282 $startOpts .= ' SQL_BUFFER_RESULT';
1285 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1286 $startOpts .= ' SQL_SMALL_RESULT';
1289 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1290 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1293 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1294 $startOpts .= ' SQL_CACHE';
1297 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1298 $startOpts .= ' SQL_NO_CACHE';
1301 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1302 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1306 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1307 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1312 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1316 * Returns an optional GROUP BY with an optional HAVING
1318 * @param array $options Associative array of options
1320 * @see DatabaseBase::select()
1323 public function makeGroupByWithHaving( $options ) {
1325 if ( isset( $options['GROUP BY'] ) ) {
1326 $gb = is_array( $options['GROUP BY'] )
1327 ?
implode( ',', $options['GROUP BY'] )
1328 : $options['GROUP BY'];
1329 $sql .= ' GROUP BY ' . $gb;
1331 if ( isset( $options['HAVING'] ) ) {
1332 $having = is_array( $options['HAVING'] )
1333 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1334 : $options['HAVING'];
1335 $sql .= ' HAVING ' . $having;
1342 * Returns an optional ORDER BY
1344 * @param array $options Associative array of options
1346 * @see DatabaseBase::select()
1349 public function makeOrderBy( $options ) {
1350 if ( isset( $options['ORDER BY'] ) ) {
1351 $ob = is_array( $options['ORDER BY'] )
1352 ?
implode( ',', $options['ORDER BY'] )
1353 : $options['ORDER BY'];
1355 return ' ORDER BY ' . $ob;
1361 // See IDatabase::select for the docs for this function
1362 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1363 $options = [], $join_conds = [] ) {
1364 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1366 return $this->query( $sql, $fname );
1369 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1370 $options = [], $join_conds = []
1372 if ( is_array( $vars ) ) {
1373 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1376 $options = (array)$options;
1377 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1378 ?
$options['USE INDEX']
1380 $ignoreIndexes = ( isset( $options['IGNORE INDEX'] ) && is_array( $options['IGNORE INDEX'] ) )
1381 ?
$options['IGNORE INDEX']
1384 if ( is_array( $table ) ) {
1386 $this->tableNamesWithIndexClauseOrJOIN( $table, $useIndexes, $ignoreIndexes, $join_conds );
1387 } elseif ( $table != '' ) {
1388 if ( $table[0] == ' ' ) {
1389 $from = ' FROM ' . $table;
1392 $this->tableNamesWithIndexClauseOrJOIN( [ $table ], $useIndexes, $ignoreIndexes, [] );
1398 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1399 $this->makeSelectOptions( $options );
1401 if ( !empty( $conds ) ) {
1402 if ( is_array( $conds ) ) {
1403 $conds = $this->makeList( $conds, LIST_AND
);
1405 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex WHERE $conds $preLimitTail";
1407 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1410 if ( isset( $options['LIMIT'] ) ) {
1411 $sql = $this->limitResult( $sql, $options['LIMIT'],
1412 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1414 $sql = "$sql $postLimitTail";
1416 if ( isset( $options['EXPLAIN'] ) ) {
1417 $sql = 'EXPLAIN ' . $sql;
1423 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1424 $options = [], $join_conds = []
1426 $options = (array)$options;
1427 $options['LIMIT'] = 1;
1428 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1430 if ( $res === false ) {
1434 if ( !$this->numRows( $res ) ) {
1438 $obj = $this->fetchObject( $res );
1443 public function estimateRowCount(
1444 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1447 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1450 $row = $this->fetchRow( $res );
1451 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1457 public function selectRowCount(
1458 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1461 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1462 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1465 $row = $this->fetchRow( $res );
1466 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1473 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1474 * It's only slightly flawed. Don't use for anything important.
1476 * @param string $sql A SQL Query
1480 protected static function generalizeSQL( $sql ) {
1481 # This does the same as the regexp below would do, but in such a way
1482 # as to avoid crashing php on some large strings.
1483 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1485 $sql = str_replace( "\\\\", '', $sql );
1486 $sql = str_replace( "\\'", '', $sql );
1487 $sql = str_replace( "\\\"", '', $sql );
1488 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1489 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1491 # All newlines, tabs, etc replaced by single space
1492 $sql = preg_replace( '/\s+/', ' ', $sql );
1495 # except the ones surrounded by characters, e.g. l10n
1496 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1497 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1502 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1503 $info = $this->fieldInfo( $table, $field );
1508 public function indexExists( $table, $index, $fname = __METHOD__
) {
1509 if ( !$this->tableExists( $table ) ) {
1513 $info = $this->indexInfo( $table, $index, $fname );
1514 if ( is_null( $info ) ) {
1517 return $info !== false;
1521 public function tableExists( $table, $fname = __METHOD__
) {
1522 $table = $this->tableName( $table );
1523 $old = $this->ignoreErrors( true );
1524 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1525 $this->ignoreErrors( $old );
1530 public function indexUnique( $table, $index ) {
1531 $indexInfo = $this->indexInfo( $table, $index );
1533 if ( !$indexInfo ) {
1537 return !$indexInfo[0]->Non_unique
;
1541 * Helper for DatabaseBase::insert().
1543 * @param array $options
1546 protected function makeInsertOptions( $options ) {
1547 return implode( ' ', $options );
1550 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1551 # No rows to insert, easy just return now
1552 if ( !count( $a ) ) {
1556 $table = $this->tableName( $table );
1558 if ( !is_array( $options ) ) {
1559 $options = [ $options ];
1563 if ( isset( $options['fileHandle'] ) ) {
1564 $fh = $options['fileHandle'];
1566 $options = $this->makeInsertOptions( $options );
1568 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1570 $keys = array_keys( $a[0] );
1573 $keys = array_keys( $a );
1576 $sql = 'INSERT ' . $options .
1577 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1581 foreach ( $a as $row ) {
1587 $sql .= '(' . $this->makeList( $row ) . ')';
1590 $sql .= '(' . $this->makeList( $a ) . ')';
1593 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1595 } elseif ( $fh !== null ) {
1599 return (bool)$this->query( $sql, $fname );
1603 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1605 * @param array $options
1608 protected function makeUpdateOptionsArray( $options ) {
1609 if ( !is_array( $options ) ) {
1610 $options = [ $options ];
1615 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1616 $opts[] = $this->lowPriorityOption();
1619 if ( in_array( 'IGNORE', $options ) ) {
1627 * Make UPDATE options for the DatabaseBase::update function
1629 * @param array $options The options passed to DatabaseBase::update
1632 protected function makeUpdateOptions( $options ) {
1633 $opts = $this->makeUpdateOptionsArray( $options );
1635 return implode( ' ', $opts );
1638 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1639 $table = $this->tableName( $table );
1640 $opts = $this->makeUpdateOptions( $options );
1641 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1643 if ( $conds !== [] && $conds !== '*' ) {
1644 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1647 return $this->query( $sql, $fname );
1650 public function makeList( $a, $mode = LIST_COMMA
) {
1651 if ( !is_array( $a ) ) {
1652 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1658 foreach ( $a as $field => $value ) {
1660 if ( $mode == LIST_AND
) {
1662 } elseif ( $mode == LIST_OR
) {
1671 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1672 $list .= "($value)";
1673 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1675 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1676 // Remove null from array to be handled separately if found
1677 $includeNull = false;
1678 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1679 $includeNull = true;
1680 unset( $value[$nullKey] );
1682 if ( count( $value ) == 0 && !$includeNull ) {
1683 throw new InvalidArgumentException( __METHOD__
. ": empty input for field $field" );
1684 } elseif ( count( $value ) == 0 ) {
1685 // only check if $field is null
1686 $list .= "$field IS NULL";
1688 // IN clause contains at least one valid element
1689 if ( $includeNull ) {
1690 // Group subconditions to ensure correct precedence
1693 if ( count( $value ) == 1 ) {
1694 // Special-case single values, as IN isn't terribly efficient
1695 // Don't necessarily assume the single key is 0; we don't
1696 // enforce linear numeric ordering on other arrays here.
1697 $value = array_values( $value )[0];
1698 $list .= $field . " = " . $this->addQuotes( $value );
1700 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1702 // if null present in array, append IS NULL
1703 if ( $includeNull ) {
1704 $list .= " OR $field IS NULL)";
1707 } elseif ( $value === null ) {
1708 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1709 $list .= "$field IS ";
1710 } elseif ( $mode == LIST_SET
) {
1711 $list .= "$field = ";
1715 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1716 $list .= "$field = ";
1718 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1725 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1728 foreach ( $data as $base => $sub ) {
1729 if ( count( $sub ) ) {
1730 $conds[] = $this->makeList(
1731 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1737 return $this->makeList( $conds, LIST_OR
);
1739 // Nothing to search for...
1745 * Return aggregated value alias
1747 * @param array $valuedata
1748 * @param string $valuename
1752 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1756 public function bitNot( $field ) {
1760 public function bitAnd( $fieldLeft, $fieldRight ) {
1761 return "($fieldLeft & $fieldRight)";
1764 public function bitOr( $fieldLeft, $fieldRight ) {
1765 return "($fieldLeft | $fieldRight)";
1768 public function buildConcat( $stringList ) {
1769 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1772 public function buildGroupConcatField(
1773 $delim, $table, $field, $conds = '', $join_conds = []
1775 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1777 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1781 * @param string $field Field or column to cast
1785 public function buildStringCast( $field ) {
1789 public function selectDB( $db ) {
1790 # Stub. Shouldn't cause serious problems if it's not overridden, but
1791 # if your database engine supports a concept similar to MySQL's
1792 # databases you may as well.
1793 $this->mDBname
= $db;
1798 public function getDBname() {
1799 return $this->mDBname
;
1802 public function getServer() {
1803 return $this->mServer
;
1807 * Format a table name ready for use in constructing an SQL query
1809 * This does two important things: it quotes the table names to clean them up,
1810 * and it adds a table prefix if only given a table name with no quotes.
1812 * All functions of this object which require a table name call this function
1813 * themselves. Pass the canonical name to such functions. This is only needed
1814 * when calling query() directly.
1816 * @note This function does not sanitize user input. It is not safe to use
1817 * this function to escape user input.
1818 * @param string $name Database table name
1819 * @param string $format One of:
1820 * quoted - Automatically pass the table name through addIdentifierQuotes()
1821 * so that it can be used in a query.
1822 * raw - Do not add identifier quotes to the table name
1823 * @return string Full database name
1825 public function tableName( $name, $format = 'quoted' ) {
1826 # Skip the entire process when we have a string quoted on both ends.
1827 # Note that we check the end so that we will still quote any use of
1828 # use of `database`.table. But won't break things if someone wants
1829 # to query a database table with a dot in the name.
1830 if ( $this->isQuotedIdentifier( $name ) ) {
1834 # Lets test for any bits of text that should never show up in a table
1835 # name. Basically anything like JOIN or ON which are actually part of
1836 # SQL queries, but may end up inside of the table value to combine
1837 # sql. Such as how the API is doing.
1838 # Note that we use a whitespace test rather than a \b test to avoid
1839 # any remote case where a word like on may be inside of a table name
1840 # surrounded by symbols which may be considered word breaks.
1841 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1845 # Split database and table into proper variables.
1846 # We reverse the explode so that database.table and table both output
1847 # the correct table.
1848 $dbDetails = explode( '.', $name, 3 );
1849 if ( count( $dbDetails ) == 3 ) {
1850 list( $database, $schema, $table ) = $dbDetails;
1851 # We don't want any prefix added in this case
1853 } elseif ( count( $dbDetails ) == 2 ) {
1854 list( $database, $table ) = $dbDetails;
1855 # We don't want any prefix added in this case
1856 # In dbs that support it, $database may actually be the schema
1857 # but that doesn't affect any of the functionality here
1861 list( $table ) = $dbDetails;
1862 if ( isset( $this->tableAliases
[$table] ) ) {
1863 $database = $this->tableAliases
[$table]['dbname'];
1864 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1865 ?
$this->tableAliases
[$table]['schema']
1867 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1868 ?
$this->tableAliases
[$table]['prefix']
1869 : $this->mTablePrefix
;
1872 $schema = $this->mSchema
; # Default schema
1873 $prefix = $this->mTablePrefix
; # Default prefix
1877 # Quote $table and apply the prefix if not quoted.
1878 # $tableName might be empty if this is called from Database::replaceVars()
1879 $tableName = "{$prefix}{$table}";
1880 if ( $format == 'quoted'
1881 && !$this->isQuotedIdentifier( $tableName ) && $tableName !== ''
1883 $tableName = $this->addIdentifierQuotes( $tableName );
1886 # Quote $schema and merge it with the table name if needed
1887 if ( strlen( $schema ) ) {
1888 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1889 $schema = $this->addIdentifierQuotes( $schema );
1891 $tableName = $schema . '.' . $tableName;
1894 # Quote $database and merge it with the table name if needed
1895 if ( $database !== null ) {
1896 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1897 $database = $this->addIdentifierQuotes( $database );
1899 $tableName = $database . '.' . $tableName;
1906 * Fetch a number of table names into an array
1907 * This is handy when you need to construct SQL for joins
1910 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1911 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1912 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1916 public function tableNames() {
1917 $inArray = func_get_args();
1920 foreach ( $inArray as $name ) {
1921 $retVal[$name] = $this->tableName( $name );
1928 * Fetch a number of table names into an zero-indexed numerical array
1929 * This is handy when you need to construct SQL for joins
1932 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1933 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1934 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1938 public function tableNamesN() {
1939 $inArray = func_get_args();
1942 foreach ( $inArray as $name ) {
1943 $retVal[] = $this->tableName( $name );
1950 * Get an aliased table name
1951 * e.g. tableName AS newTableName
1953 * @param string $name Table name, see tableName()
1954 * @param string|bool $alias Alias (optional)
1955 * @return string SQL name for aliased table. Will not alias a table to its own name
1957 public function tableNameWithAlias( $name, $alias = false ) {
1958 if ( !$alias ||
$alias == $name ) {
1959 return $this->tableName( $name );
1961 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1966 * Gets an array of aliased table names
1968 * @param array $tables [ [alias] => table ]
1969 * @return string[] See tableNameWithAlias()
1971 public function tableNamesWithAlias( $tables ) {
1973 foreach ( $tables as $alias => $table ) {
1974 if ( is_numeric( $alias ) ) {
1977 $retval[] = $this->tableNameWithAlias( $table, $alias );
1984 * Get an aliased field name
1985 * e.g. fieldName AS newFieldName
1987 * @param string $name Field name
1988 * @param string|bool $alias Alias (optional)
1989 * @return string SQL name for aliased field. Will not alias a field to its own name
1991 public function fieldNameWithAlias( $name, $alias = false ) {
1992 if ( !$alias ||
(string)$alias === (string)$name ) {
1995 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2000 * Gets an array of aliased field names
2002 * @param array $fields [ [alias] => field ]
2003 * @return string[] See fieldNameWithAlias()
2005 public function fieldNamesWithAlias( $fields ) {
2007 foreach ( $fields as $alias => $field ) {
2008 if ( is_numeric( $alias ) ) {
2011 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2018 * Get the aliased table name clause for a FROM clause
2019 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2021 * @param array $tables ( [alias] => table )
2022 * @param array $use_index Same as for select()
2023 * @param array $ignore_index Same as for select()
2024 * @param array $join_conds Same as for select()
2027 protected function tableNamesWithIndexClauseOrJOIN(
2028 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2032 $use_index = (array)$use_index;
2033 $ignore_index = (array)$ignore_index;
2034 $join_conds = (array)$join_conds;
2036 foreach ( $tables as $alias => $table ) {
2037 if ( !is_string( $alias ) ) {
2038 // No alias? Set it equal to the table name
2041 // Is there a JOIN clause for this table?
2042 if ( isset( $join_conds[$alias] ) ) {
2043 list( $joinType, $conds ) = $join_conds[$alias];
2044 $tableClause = $joinType;
2045 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2046 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2047 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2049 $tableClause .= ' ' . $use;
2052 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2053 $ignore = $this->ignoreIndexClause( implode( ',', (array)$ignore_index[$alias] ) );
2054 if ( $ignore != '' ) {
2055 $tableClause .= ' ' . $ignore;
2058 $on = $this->makeList( (array)$conds, LIST_AND
);
2060 $tableClause .= ' ON (' . $on . ')';
2063 $retJOIN[] = $tableClause;
2064 } elseif ( isset( $use_index[$alias] ) ) {
2065 // Is there an INDEX clause for this table?
2066 $tableClause = $this->tableNameWithAlias( $table, $alias );
2067 $tableClause .= ' ' . $this->useIndexClause(
2068 implode( ',', (array)$use_index[$alias] )
2071 $ret[] = $tableClause;
2072 } elseif ( isset( $ignore_index[$alias] ) ) {
2073 // Is there an INDEX clause for this table?
2074 $tableClause = $this->tableNameWithAlias( $table, $alias );
2075 $tableClause .= ' ' . $this->ignoreIndexClause(
2076 implode( ',', (array)$ignore_index[$alias] )
2079 $ret[] = $tableClause;
2081 $tableClause = $this->tableNameWithAlias( $table, $alias );
2083 $ret[] = $tableClause;
2087 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2088 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2089 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2091 // Compile our final table clause
2092 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2096 * Get the name of an index in a given table.
2098 * @param string $index
2101 protected function indexName( $index ) {
2102 // Backwards-compatibility hack
2104 'ar_usertext_timestamp' => 'usertext_timestamp',
2105 'un_user_id' => 'user_id',
2106 'un_user_ip' => 'user_ip',
2109 if ( isset( $renamed[$index] ) ) {
2110 return $renamed[$index];
2116 public function addQuotes( $s ) {
2117 if ( $s instanceof Blob
) {
2120 if ( $s === null ) {
2123 # This will also quote numeric values. This should be harmless,
2124 # and protects against weird problems that occur when they really
2125 # _are_ strings such as article titles and string->number->string
2126 # conversion is not 1:1.
2127 return "'" . $this->strencode( $s ) . "'";
2132 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2133 * MySQL uses `backticks` while basically everything else uses double quotes.
2134 * Since MySQL is the odd one out here the double quotes are our generic
2135 * and we implement backticks in DatabaseMysql.
2140 public function addIdentifierQuotes( $s ) {
2141 return '"' . str_replace( '"', '""', $s ) . '"';
2145 * Returns if the given identifier looks quoted or not according to
2146 * the database convention for quoting identifiers .
2148 * @note Do not use this to determine if untrusted input is safe.
2149 * A malicious user can trick this function.
2150 * @param string $name
2153 public function isQuotedIdentifier( $name ) {
2154 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2161 protected function escapeLikeInternal( $s ) {
2162 return addcslashes( $s, '\%_' );
2165 public function buildLike() {
2166 $params = func_get_args();
2168 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2169 $params = $params[0];
2174 foreach ( $params as $value ) {
2175 if ( $value instanceof LikeMatch
) {
2176 $s .= $value->toString();
2178 $s .= $this->escapeLikeInternal( $value );
2182 return " LIKE {$this->addQuotes( $s )} ";
2185 public function anyChar() {
2186 return new LikeMatch( '_' );
2189 public function anyString() {
2190 return new LikeMatch( '%' );
2193 public function nextSequenceValue( $seqName ) {
2198 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2199 * is only needed because a) MySQL must be as efficient as possible due to
2200 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2201 * which index to pick. Anyway, other databases might have different
2202 * indexes on a given table. So don't bother overriding this unless you're
2204 * @param string $index
2207 public function useIndexClause( $index ) {
2212 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2213 * is only needed because a) MySQL must be as efficient as possible due to
2214 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2215 * which index to pick. Anyway, other databases might have different
2216 * indexes on a given table. So don't bother overriding this unless you're
2218 * @param string $index
2221 public function ignoreIndexClause( $index ) {
2225 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2226 $quotedTable = $this->tableName( $table );
2228 if ( count( $rows ) == 0 ) {
2233 if ( !is_array( reset( $rows ) ) ) {
2237 // @FXIME: this is not atomic, but a trx would break affectedRows()
2238 foreach ( $rows as $row ) {
2239 # Delete rows which collide
2240 if ( $uniqueIndexes ) {
2241 $sql = "DELETE FROM $quotedTable WHERE ";
2243 foreach ( $uniqueIndexes as $index ) {
2250 if ( is_array( $index ) ) {
2252 foreach ( $index as $col ) {
2258 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2261 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2265 $this->query( $sql, $fname );
2268 # Now insert the row
2269 $this->insert( $table, $row, $fname );
2274 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2277 * @param string $table Table name
2278 * @param array|string $rows Row(s) to insert
2279 * @param string $fname Caller function name
2281 * @return ResultWrapper
2283 protected function nativeReplace( $table, $rows, $fname ) {
2284 $table = $this->tableName( $table );
2287 if ( !is_array( reset( $rows ) ) ) {
2291 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2294 foreach ( $rows as $row ) {
2301 $sql .= '(' . $this->makeList( $row ) . ')';
2304 return $this->query( $sql, $fname );
2307 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2310 if ( !count( $rows ) ) {
2311 return true; // nothing to do
2314 if ( !is_array( reset( $rows ) ) ) {
2318 if ( count( $uniqueIndexes ) ) {
2319 $clauses = []; // list WHERE clauses that each identify a single row
2320 foreach ( $rows as $row ) {
2321 foreach ( $uniqueIndexes as $index ) {
2322 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2323 $rowKey = []; // unique key to this row
2324 foreach ( $index as $column ) {
2325 $rowKey[$column] = $row[$column];
2327 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2330 $where = [ $this->makeList( $clauses, LIST_OR
) ];
2335 $useTrx = !$this->mTrxLevel
;
2337 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2340 # Update any existing conflicting row(s)
2341 if ( $where !== false ) {
2342 $ok = $this->update( $table, $set, $where, $fname );
2346 # Now insert any non-conflicting row(s)
2347 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2348 } catch ( Exception
$e ) {
2350 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2355 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2361 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2365 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2368 $delTable = $this->tableName( $delTable );
2369 $joinTable = $this->tableName( $joinTable );
2370 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2371 if ( $conds != '*' ) {
2372 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2376 $this->query( $sql, $fname );
2380 * Returns the size of a text field, or -1 for "unlimited"
2382 * @param string $table
2383 * @param string $field
2386 public function textFieldSize( $table, $field ) {
2387 $table = $this->tableName( $table );
2388 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2389 $res = $this->query( $sql, __METHOD__
);
2390 $row = $this->fetchObject( $res );
2394 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2404 * A string to insert into queries to show that they're low-priority, like
2405 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2406 * string and nothing bad should happen.
2408 * @return string Returns the text of the low priority option if it is
2409 * supported, or a blank string otherwise
2411 public function lowPriorityOption() {
2415 public function delete( $table, $conds, $fname = __METHOD__
) {
2417 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2420 $table = $this->tableName( $table );
2421 $sql = "DELETE FROM $table";
2423 if ( $conds != '*' ) {
2424 if ( is_array( $conds ) ) {
2425 $conds = $this->makeList( $conds, LIST_AND
);
2427 $sql .= ' WHERE ' . $conds;
2430 return $this->query( $sql, $fname );
2433 public function insertSelect(
2434 $destTable, $srcTable, $varMap, $conds,
2435 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2437 if ( $this->cliMode
) {
2438 // For massive migrations with downtime, we don't want to select everything
2439 // into memory and OOM, so do all this native on the server side if possible.
2440 return $this->nativeInsertSelect(
2451 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2452 // on only the master (without needing row-based-replication). It also makes it easy to
2453 // know how big the INSERT is going to be.
2455 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2456 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2458 $selectOptions[] = 'FOR UPDATE';
2459 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2465 foreach ( $res as $row ) {
2466 $rows[] = (array)$row;
2469 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2472 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2473 $fname = __METHOD__
,
2474 $insertOptions = [], $selectOptions = []
2476 $destTable = $this->tableName( $destTable );
2478 if ( !is_array( $insertOptions ) ) {
2479 $insertOptions = [ $insertOptions ];
2482 $insertOptions = $this->makeInsertOptions( $insertOptions );
2484 if ( !is_array( $selectOptions ) ) {
2485 $selectOptions = [ $selectOptions ];
2488 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2491 if ( is_array( $srcTable ) ) {
2492 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2494 $srcTable = $this->tableName( $srcTable );
2497 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2498 " SELECT $startOpts " . implode( ',', $varMap ) .
2499 " FROM $srcTable $useIndex $ignoreIndex ";
2501 if ( $conds != '*' ) {
2502 if ( is_array( $conds ) ) {
2503 $conds = $this->makeList( $conds, LIST_AND
);
2505 $sql .= " WHERE $conds";
2508 $sql .= " $tailOpts";
2510 return $this->query( $sql, $fname );
2514 * Construct a LIMIT query with optional offset. This is used for query
2515 * pages. The SQL should be adjusted so that only the first $limit rows
2516 * are returned. If $offset is provided as well, then the first $offset
2517 * rows should be discarded, and the next $limit rows should be returned.
2518 * If the result of the query is not ordered, then the rows to be returned
2519 * are theoretically arbitrary.
2521 * $sql is expected to be a SELECT, if that makes a difference.
2523 * The version provided by default works in MySQL and SQLite. It will very
2524 * likely need to be overridden for most other DBMSes.
2526 * @param string $sql SQL query we will append the limit too
2527 * @param int $limit The SQL limit
2528 * @param int|bool $offset The SQL offset (default false)
2529 * @throws DBUnexpectedError
2532 public function limitResult( $sql, $limit, $offset = false ) {
2533 if ( !is_numeric( $limit ) ) {
2534 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2537 return "$sql LIMIT "
2538 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2542 public function unionSupportsOrderAndLimit() {
2543 return true; // True for almost every DB supported
2546 public function unionQueries( $sqls, $all ) {
2547 $glue = $all ?
') UNION ALL (' : ') UNION (';
2549 return '(' . implode( $glue, $sqls ) . ')';
2552 public function conditional( $cond, $trueVal, $falseVal ) {
2553 if ( is_array( $cond ) ) {
2554 $cond = $this->makeList( $cond, LIST_AND
);
2557 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2560 public function strreplace( $orig, $old, $new ) {
2561 return "REPLACE({$orig}, {$old}, {$new})";
2564 public function getServerUptime() {
2568 public function wasDeadlock() {
2572 public function wasLockTimeout() {
2576 public function wasErrorReissuable() {
2580 public function wasReadOnlyError() {
2585 * Determines if the given query error was a connection drop
2588 * @param integer|string $errno
2591 public function wasConnectionError( $errno ) {
2596 * Perform a deadlock-prone transaction.
2598 * This function invokes a callback function to perform a set of write
2599 * queries. If a deadlock occurs during the processing, the transaction
2600 * will be rolled back and the callback function will be called again.
2602 * Avoid using this method outside of Job or Maintenance classes.
2605 * $dbw->deadlockLoop( callback, ... );
2607 * Extra arguments are passed through to the specified callback function.
2608 * This method requires that no transactions are already active to avoid
2609 * causing premature commits or exceptions.
2611 * Returns whatever the callback function returned on its successful,
2612 * iteration, or false on error, for example if the retry limit was
2616 * @throws DBUnexpectedError
2619 public function deadlockLoop() {
2620 $args = func_get_args();
2621 $function = array_shift( $args );
2622 $tries = self
::DEADLOCK_TRIES
;
2624 $this->begin( __METHOD__
);
2627 /** @var Exception $e */
2631 $retVal = call_user_func_array( $function, $args );
2633 } catch ( DBQueryError
$e ) {
2634 if ( $this->wasDeadlock() ) {
2635 // Retry after a randomized delay
2636 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2638 // Throw the error back up
2642 } while ( --$tries > 0 );
2644 if ( $tries <= 0 ) {
2645 // Too many deadlocks; give up
2646 $this->rollback( __METHOD__
);
2649 $this->commit( __METHOD__
);
2655 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2656 # Real waits are implemented in the subclass.
2660 public function getSlavePos() {
2665 public function getMasterPos() {
2670 public function serverIsReadOnly() {
2674 final public function onTransactionResolution( callable
$callback ) {
2675 if ( !$this->mTrxLevel
) {
2676 throw new DBUnexpectedError( $this, "No transaction is active." );
2678 $this->mTrxEndCallbacks
[] = [ $callback, wfGetCaller() ];
2681 final public function onTransactionIdle( callable
$callback ) {
2682 $this->mTrxIdleCallbacks
[] = [ $callback, wfGetCaller() ];
2683 if ( !$this->mTrxLevel
) {
2684 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2688 final public function onTransactionPreCommitOrIdle( callable
$callback ) {
2689 if ( $this->mTrxLevel
) {
2690 $this->mTrxPreCommitCallbacks
[] = [ $callback, wfGetCaller() ];
2692 // If no transaction is active, then make one for this callback
2693 $this->startAtomic( __METHOD__
);
2695 call_user_func( $callback );
2696 $this->endAtomic( __METHOD__
);
2697 } catch ( Exception
$e ) {
2698 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2704 final public function setTransactionListener( $name, callable
$callback = null ) {
2706 $this->mTrxRecurringCallbacks
[$name] = [ $callback, wfGetCaller() ];
2708 unset( $this->mTrxRecurringCallbacks
[$name] );
2713 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2715 * This method should not be used outside of Database/LoadBalancer
2717 * @param bool $suppress
2720 final public function setTrxEndCallbackSuppression( $suppress ) {
2721 $this->mTrxEndCallbacksSuppressed
= $suppress;
2725 * Actually run and consume any "on transaction idle/resolution" callbacks.
2727 * This method should not be used outside of Database/LoadBalancer
2729 * @param integer $trigger IDatabase::TRIGGER_* constant
2733 public function runOnTransactionIdleCallbacks( $trigger ) {
2734 if ( $this->mTrxEndCallbacksSuppressed
) {
2738 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2739 /** @var Exception $e */
2740 $e = null; // first exception
2741 do { // callbacks may add callbacks :)
2742 $callbacks = array_merge(
2743 $this->mTrxIdleCallbacks
,
2744 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2746 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2747 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2748 foreach ( $callbacks as $callback ) {
2750 list( $phpCallback ) = $callback;
2751 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2752 call_user_func_array( $phpCallback, [ $trigger ] );
2754 $this->setFlag( DBO_TRX
); // restore automatic begin()
2756 $this->clearFlag( DBO_TRX
); // restore auto-commit
2758 } catch ( Exception
$ex ) {
2759 call_user_func( $this->errorLogger
, $ex );
2761 // Some callbacks may use startAtomic/endAtomic, so make sure
2762 // their transactions are ended so other callbacks don't fail
2763 if ( $this->trxLevel() ) {
2764 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2768 } while ( count( $this->mTrxIdleCallbacks
) );
2770 if ( $e instanceof Exception
) {
2771 throw $e; // re-throw any first exception
2776 * Actually run and consume any "on transaction pre-commit" callbacks.
2778 * This method should not be used outside of Database/LoadBalancer
2783 public function runOnTransactionPreCommitCallbacks() {
2784 $e = null; // first exception
2785 do { // callbacks may add callbacks :)
2786 $callbacks = $this->mTrxPreCommitCallbacks
;
2787 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2788 foreach ( $callbacks as $callback ) {
2790 list( $phpCallback ) = $callback;
2791 call_user_func( $phpCallback );
2792 } catch ( Exception
$ex ) {
2793 call_user_func( $this->errorLogger
, $ex );
2797 } while ( count( $this->mTrxPreCommitCallbacks
) );
2799 if ( $e instanceof Exception
) {
2800 throw $e; // re-throw any first exception
2805 * Actually run any "transaction listener" callbacks.
2807 * This method should not be used outside of Database/LoadBalancer
2809 * @param integer $trigger IDatabase::TRIGGER_* constant
2813 public function runTransactionListenerCallbacks( $trigger ) {
2814 if ( $this->mTrxEndCallbacksSuppressed
) {
2818 /** @var Exception $e */
2819 $e = null; // first exception
2821 foreach ( $this->mTrxRecurringCallbacks
as $callback ) {
2823 list( $phpCallback ) = $callback;
2824 $phpCallback( $trigger, $this );
2825 } catch ( Exception
$ex ) {
2826 call_user_func( $this->errorLogger
, $ex );
2831 if ( $e instanceof Exception
) {
2832 throw $e; // re-throw any first exception
2836 final public function startAtomic( $fname = __METHOD__
) {
2837 if ( !$this->mTrxLevel
) {
2838 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2839 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2840 // in all changes being in one transaction to keep requests transactional.
2841 if ( !$this->getFlag( DBO_TRX
) ) {
2842 $this->mTrxAutomaticAtomic
= true;
2846 $this->mTrxAtomicLevels
[] = $fname;
2849 final public function endAtomic( $fname = __METHOD__
) {
2850 if ( !$this->mTrxLevel
) {
2851 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2853 if ( !$this->mTrxAtomicLevels ||
2854 array_pop( $this->mTrxAtomicLevels
) !== $fname
2856 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2859 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2860 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2864 final public function doAtomicSection( $fname, callable
$callback ) {
2865 $this->startAtomic( $fname );
2867 $res = call_user_func_array( $callback, [ $this, $fname ] );
2868 } catch ( Exception
$e ) {
2869 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2872 $this->endAtomic( $fname );
2877 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2878 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2879 if ( $this->mTrxLevel
) {
2880 if ( $this->mTrxAtomicLevels
) {
2881 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2882 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2883 throw new DBUnexpectedError( $this, $msg );
2884 } elseif ( !$this->mTrxAutomatic
) {
2885 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2886 throw new DBUnexpectedError( $this, $msg );
2888 // @TODO: make this an exception at some point
2889 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2890 $this->queryLogger
->error( $msg );
2891 return; // join the main transaction set
2893 } elseif ( $this->getFlag( DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2894 // @TODO: make this an exception at some point
2895 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2896 $this->queryLogger
->error( $msg );
2897 return; // let any writes be in the main transaction
2900 // Avoid fatals if close() was called
2901 $this->assertOpen();
2903 $this->doBegin( $fname );
2904 $this->mTrxTimestamp
= microtime( true );
2905 $this->mTrxFname
= $fname;
2906 $this->mTrxDoneWrites
= false;
2907 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2908 $this->mTrxAutomaticAtomic
= false;
2909 $this->mTrxAtomicLevels
= [];
2910 $this->mTrxShortId
= wfRandomString( 12 );
2911 $this->mTrxWriteDuration
= 0.0;
2912 $this->mTrxWriteQueryCount
= 0;
2913 $this->mTrxWriteAdjDuration
= 0.0;
2914 $this->mTrxWriteAdjQueryCount
= 0;
2915 $this->mTrxWriteCallers
= [];
2916 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2917 // Get an estimate of the replica DB lag before then, treating estimate staleness
2918 // as lag itself just to be safe
2919 $status = $this->getApproximateLagStatus();
2920 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2924 * Issues the BEGIN command to the database server.
2926 * @see DatabaseBase::begin()
2927 * @param string $fname
2929 protected function doBegin( $fname ) {
2930 $this->query( 'BEGIN', $fname );
2931 $this->mTrxLevel
= 1;
2934 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2935 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2936 // There are still atomic sections open. This cannot be ignored
2937 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2938 throw new DBUnexpectedError(
2940 "$fname: Got COMMIT while atomic sections $levels are still open."
2944 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2945 if ( !$this->mTrxLevel
) {
2946 return; // nothing to do
2947 } elseif ( !$this->mTrxAutomatic
) {
2948 throw new DBUnexpectedError(
2950 "$fname: Flushing an explicit transaction, getting out of sync."
2954 if ( !$this->mTrxLevel
) {
2955 $this->queryLogger
->error( "$fname: No transaction to commit, something got out of sync." );
2956 return; // nothing to do
2957 } elseif ( $this->mTrxAutomatic
) {
2958 // @TODO: make this an exception at some point
2959 $msg = "$fname: Explicit commit of implicit transaction.";
2960 $this->queryLogger
->error( $msg );
2961 return; // wait for the main transaction set commit round
2965 // Avoid fatals if close() was called
2966 $this->assertOpen();
2968 $this->runOnTransactionPreCommitCallbacks();
2969 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2970 $this->doCommit( $fname );
2971 if ( $this->mTrxDoneWrites
) {
2972 $this->mDoneWrites
= microtime( true );
2973 $this->trxProfiler
->transactionWritingOut(
2974 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2977 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2978 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
2982 * Issues the COMMIT command to the database server.
2984 * @see DatabaseBase::commit()
2985 * @param string $fname
2987 protected function doCommit( $fname ) {
2988 if ( $this->mTrxLevel
) {
2989 $this->query( 'COMMIT', $fname );
2990 $this->mTrxLevel
= 0;
2994 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2995 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2996 if ( !$this->mTrxLevel
) {
2997 return; // nothing to do
3000 if ( !$this->mTrxLevel
) {
3001 $this->queryLogger
->error(
3002 "$fname: No transaction to rollback, something got out of sync." );
3003 return; // nothing to do
3004 } elseif ( $this->getFlag( DBO_TRX
) ) {
3005 throw new DBUnexpectedError(
3007 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3012 // Avoid fatals if close() was called
3013 $this->assertOpen();
3015 $this->doRollback( $fname );
3016 $this->mTrxAtomicLevels
= [];
3017 if ( $this->mTrxDoneWrites
) {
3018 $this->trxProfiler
->transactionWritingOut(
3019 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3022 $this->mTrxIdleCallbacks
= []; // clear
3023 $this->mTrxPreCommitCallbacks
= []; // clear
3024 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3025 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3029 * Issues the ROLLBACK command to the database server.
3031 * @see DatabaseBase::rollback()
3032 * @param string $fname
3034 protected function doRollback( $fname ) {
3035 if ( $this->mTrxLevel
) {
3036 # Disconnects cause rollback anyway, so ignore those errors
3037 $ignoreErrors = true;
3038 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3039 $this->mTrxLevel
= 0;
3043 public function flushSnapshot( $fname = __METHOD__
) {
3044 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3045 // This only flushes transactions to clear snapshots, not to write data
3046 throw new DBUnexpectedError(
3048 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3052 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3055 public function explicitTrxActive() {
3056 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
3060 * Creates a new table with structure copied from existing table
3061 * Note that unlike most database abstraction functions, this function does not
3062 * automatically append database prefix, because it works at a lower
3063 * abstraction level.
3064 * The table names passed to this function shall not be quoted (this
3065 * function calls addIdentifierQuotes when needed).
3067 * @param string $oldName Name of table whose structure should be copied
3068 * @param string $newName Name of table to be created
3069 * @param bool $temporary Whether the new table should be temporary
3070 * @param string $fname Calling function name
3071 * @throws RuntimeException
3072 * @return bool True if operation was successful
3074 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3077 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3080 function listTables( $prefix = null, $fname = __METHOD__
) {
3081 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3085 * Reset the views process cache set by listViews()
3088 final public function clearViewsCache() {
3089 $this->allViews
= null;
3093 * Lists all the VIEWs in the database
3095 * For caching purposes the list of all views should be stored in
3096 * $this->allViews. The process cache can be cleared with clearViewsCache()
3098 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3099 * @param string $fname Name of calling function
3100 * @throws RuntimeException
3104 public function listViews( $prefix = null, $fname = __METHOD__
) {
3105 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3109 * Differentiates between a TABLE and a VIEW
3111 * @param string $name Name of the database-structure to test.
3112 * @throws RuntimeException
3116 public function isView( $name ) {
3117 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3120 public function timestamp( $ts = 0 ) {
3121 $t = new ConvertableTimestamp( $ts );
3122 // Let errors bubble up to avoid putting garbage in the DB
3123 return $t->getTimestamp( TS_MW
);
3126 public function timestampOrNull( $ts = null ) {
3127 if ( is_null( $ts ) ) {
3130 return $this->timestamp( $ts );
3135 * Take the result from a query, and wrap it in a ResultWrapper if
3136 * necessary. Boolean values are passed through as is, to indicate success
3137 * of write queries or failure.
3139 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3140 * resource, and it was necessary to call this function to convert it to
3141 * a wrapper. Nowadays, raw database objects are never exposed to external
3142 * callers, so this is unnecessary in external code.
3144 * @param bool|ResultWrapper|resource|object $result
3145 * @return bool|ResultWrapper
3147 protected function resultObject( $result ) {
3150 } elseif ( $result instanceof ResultWrapper
) {
3152 } elseif ( $result === true ) {
3153 // Successful write query
3156 return new ResultWrapper( $this, $result );
3160 public function ping( &$rtt = null ) {
3161 // Avoid hitting the server if it was hit recently
3162 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3163 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
3164 $rtt = $this->mRTTEstimate
;
3165 return true; // don't care about $rtt
3169 // This will reconnect if possible or return false if not
3170 $this->clearFlag( DBO_TRX
, self
::REMEMBER_PRIOR
);
3171 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3172 $this->restoreFlags( self
::RESTORE_PRIOR
);
3175 $rtt = $this->mRTTEstimate
;
3184 protected function reconnect() {
3185 $this->closeConnection();
3186 $this->mOpened
= false;
3187 $this->mConn
= false;
3189 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3190 $this->lastPing
= microtime( true );
3192 } catch ( DBConnectionError
$e ) {
3199 public function getSessionLagStatus() {
3200 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3204 * Get the replica DB lag when the current transaction started
3206 * This is useful when transactions might use snapshot isolation
3207 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3208 * is this lag plus transaction duration. If they don't, it is still
3209 * safe to be pessimistic. This returns null if there is no transaction.
3211 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3214 public function getTransactionLagStatus() {
3215 return $this->mTrxLevel
3216 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3221 * Get a replica DB lag estimate for this server
3223 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3226 public function getApproximateLagStatus() {
3228 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3229 'since' => microtime( true )
3234 * Merge the result of getSessionLagStatus() for several DBs
3235 * using the most pessimistic values to estimate the lag of
3236 * any data derived from them in combination
3238 * This is information is useful for caching modules
3240 * @see WANObjectCache::set()
3241 * @see WANObjectCache::getWithSetCallback()
3243 * @param IDatabase $db1
3244 * @param IDatabase ...
3245 * @return array Map of values:
3246 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3247 * - since: oldest UNIX timestamp of any of the DB lag estimates
3248 * - pending: whether any of the DBs have uncommitted changes
3251 public static function getCacheSetOptions( IDatabase
$db1 ) {
3252 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3253 foreach ( func_get_args() as $db ) {
3254 /** @var IDatabase $db */
3255 $status = $db->getSessionLagStatus();
3256 if ( $status['lag'] === false ) {
3257 $res['lag'] = false;
3258 } elseif ( $res['lag'] !== false ) {
3259 $res['lag'] = max( $res['lag'], $status['lag'] );
3261 $res['since'] = min( $res['since'], $status['since'] );
3262 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3268 public function getLag() {
3272 function maxListLen() {
3276 public function encodeBlob( $b ) {
3280 public function decodeBlob( $b ) {
3281 if ( $b instanceof Blob
) {
3287 public function setSessionOptions( array $options ) {
3291 * Read and execute SQL commands from a file.
3293 * Returns true on success, error string or exception on failure (depending
3294 * on object's error ignore settings).
3296 * @param string $filename File name to open
3297 * @param bool|callable $lineCallback Optional function called before reading each line
3298 * @param bool|callable $resultCallback Optional function called for each MySQL result
3299 * @param bool|string $fname Calling function name or false if name should be
3300 * generated dynamically using $filename
3301 * @param bool|callable $inputCallback Optional function called for each
3302 * complete line sent
3303 * @return bool|string
3306 public function sourceFile(
3307 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3309 MediaWiki\
suppressWarnings();
3310 $fp = fopen( $filename, 'r' );
3311 MediaWiki\restoreWarnings
();
3313 if ( false === $fp ) {
3314 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3318 $fname = __METHOD__
. "( $filename )";
3322 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3323 } catch ( Exception
$e ) {
3333 public function setSchemaVars( $vars ) {
3334 $this->mSchemaVars
= $vars;
3338 * Read and execute commands from an open file handle.
3340 * Returns true on success, error string or exception on failure (depending
3341 * on object's error ignore settings).
3343 * @param resource $fp File handle
3344 * @param bool|callable $lineCallback Optional function called before reading each query
3345 * @param bool|callable $resultCallback Optional function called for each MySQL result
3346 * @param string $fname Calling function name
3347 * @param bool|callable $inputCallback Optional function called for each complete query sent
3348 * @return bool|string
3350 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3351 $fname = __METHOD__
, $inputCallback = false
3355 while ( !feof( $fp ) ) {
3356 if ( $lineCallback ) {
3357 call_user_func( $lineCallback );
3360 $line = trim( fgets( $fp ) );
3362 if ( $line == '' ) {
3366 if ( '-' == $line[0] && '-' == $line[1] ) {
3374 $done = $this->streamStatementEnd( $cmd, $line );
3378 if ( $done ||
feof( $fp ) ) {
3379 $cmd = $this->replaceVars( $cmd );
3381 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3382 $res = $this->query( $cmd, $fname );
3384 if ( $resultCallback ) {
3385 call_user_func( $resultCallback, $res, $this );
3388 if ( false === $res ) {
3389 $err = $this->lastError();
3391 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3402 * Called by sourceStream() to check if we've reached a statement end
3404 * @param string $sql SQL assembled so far
3405 * @param string $newLine New line about to be added to $sql
3406 * @return bool Whether $newLine contains end of the statement
3408 public function streamStatementEnd( &$sql, &$newLine ) {
3409 if ( $this->delimiter
) {
3411 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3412 if ( $newLine != $prev ) {
3421 * Database independent variable replacement. Replaces a set of variables
3422 * in an SQL statement with their contents as given by $this->getSchemaVars().
3424 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3426 * - '{$var}' should be used for text and is passed through the database's
3428 * - `{$var}` should be used for identifiers (e.g. table and database names).
3429 * It is passed through the database's addIdentifierQuotes method which
3430 * can be overridden if the database uses something other than backticks.
3431 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3432 * database's tableName method.
3433 * - / *i* / passes the name that follows through the database's indexName method.
3434 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3435 * its use should be avoided. In 1.24 and older, string encoding was applied.
3437 * @param string $ins SQL statement to replace variables in
3438 * @return string The new SQL statement with variables replaced
3440 protected function replaceVars( $ins ) {
3441 $vars = $this->getSchemaVars();
3442 return preg_replace_callback(
3444 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3445 \'\{\$ (\w+) }\' | # 3. addQuotes
3446 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3447 /\*\$ (\w+) \*/ # 5. leave unencoded
3449 function ( $m ) use ( $vars ) {
3450 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3451 // check for both nonexistent keys *and* the empty string.
3452 if ( isset( $m[1] ) && $m[1] !== '' ) {
3453 if ( $m[1] === 'i' ) {
3454 return $this->indexName( $m[2] );
3456 return $this->tableName( $m[2] );
3458 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3459 return $this->addQuotes( $vars[$m[3]] );
3460 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3461 return $this->addIdentifierQuotes( $vars[$m[4]] );
3462 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3463 return $vars[$m[5]];
3473 * Get schema variables. If none have been set via setSchemaVars(), then
3474 * use some defaults from the current object.
3478 protected function getSchemaVars() {
3479 if ( $this->mSchemaVars
) {
3480 return $this->mSchemaVars
;
3482 return $this->getDefaultSchemaVars();
3487 * Get schema variables to use if none have been set via setSchemaVars().
3489 * Override this in derived classes to provide variables for tables.sql
3490 * and SQL patch files.
3494 protected function getDefaultSchemaVars() {
3498 public function lockIsFree( $lockName, $method ) {
3502 public function lock( $lockName, $method, $timeout = 5 ) {
3503 $this->mNamedLocksHeld
[$lockName] = 1;
3508 public function unlock( $lockName, $method ) {
3509 unset( $this->mNamedLocksHeld
[$lockName] );
3514 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3515 if ( $this->writesOrCallbacksPending() ) {
3516 // This only flushes transactions to clear snapshots, not to write data
3517 throw new DBUnexpectedError(
3519 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3523 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3527 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3528 if ( $this->trxLevel() ) {
3529 // There is a good chance an exception was thrown, causing any early return
3530 // from the caller. Let any error handler get a chance to issue rollback().
3531 // If there isn't one, let the error bubble up and trigger server-side rollback.
3532 $this->onTransactionResolution( function () use ( $lockKey, $fname ) {
3533 $this->unlock( $lockKey, $fname );
3536 $this->unlock( $lockKey, $fname );
3540 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
3545 public function namedLocksEnqueue() {
3550 * Lock specific tables
3552 * @param array $read Array of tables to lock for read access
3553 * @param array $write Array of tables to lock for write access
3554 * @param string $method Name of caller
3555 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3558 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3563 * Unlock specific tables
3565 * @param string $method The caller
3568 public function unlockTables( $method ) {
3574 * @param string $tableName
3575 * @param string $fName
3576 * @return bool|ResultWrapper
3579 public function dropTable( $tableName, $fName = __METHOD__
) {
3580 if ( !$this->tableExists( $tableName, $fName ) ) {
3583 $sql = "DROP TABLE " . $this->tableName( $tableName );
3584 if ( $this->cascadingDeletes() ) {
3588 return $this->query( $sql, $fName );
3592 * Get search engine class. All subclasses of this need to implement this
3593 * if they wish to use searching.
3597 public function getSearchEngine() {
3598 return 'SearchEngineDummy';
3601 public function getInfinity() {
3605 public function encodeExpiry( $expiry ) {
3606 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3607 ?
$this->getInfinity()
3608 : $this->timestamp( $expiry );
3611 public function decodeExpiry( $expiry, $format = TS_MW
) {
3612 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3617 $t = new ConvertableTimestamp( $expiry );
3619 return $t->getTimestamp( $format );
3620 } catch ( TimestampException
$e ) {
3625 public function setBigSelects( $value = true ) {
3629 public function isReadOnly() {
3630 return ( $this->getReadOnlyReason() !== false );
3634 * @return string|bool Reason this DB is read-only or false if it is not
3636 protected function getReadOnlyReason() {
3637 $reason = $this->getLBInfo( 'readOnlyReason' );
3639 return is_string( $reason ) ?
$reason : false;
3642 public function setTableAliases( array $aliases ) {
3643 $this->tableAliases
= $aliases;
3650 public function __toString() {
3651 return (string)$this->mConn
;
3655 * Run a few simple sanity checks
3657 public function __destruct() {
3658 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3659 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3661 $danglingCallbacks = array_merge(
3662 $this->mTrxIdleCallbacks
,
3663 $this->mTrxPreCommitCallbacks
,
3664 $this->mTrxEndCallbacks
3666 if ( $danglingCallbacks ) {
3668 foreach ( $danglingCallbacks as $callbackInfo ) {
3669 $callers[] = $callbackInfo[1];
3671 $callers = implode( ', ', $callers );
3672 trigger_error( "DB transaction callbacks still pending (from $callers)." );
3680 abstract class Database
extends DatabaseBase
{
3681 // B/C until nothing type hints for DatabaseBase
3682 // @TODO: finish renaming DatabaseBase => Database