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 Database
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 = [];
65 /** @var bool Whether this PHP instance is for a CLI script */
67 /** @var string Agent name for query profiling */
70 /** @var BagOStuff APC cache */
72 /** @var LoggerInterface */
73 protected $connLogger;
74 /** @var LoggerInterface */
75 protected $queryLogger;
76 /** @var callback Error logging callback */
77 protected $errorLogger;
79 /** @var resource Database connection */
80 protected $mConn = null;
82 protected $mOpened = false;
84 /** @var array[] List of (callable, method name) */
85 protected $mTrxIdleCallbacks = [];
86 /** @var array[] List of (callable, method name) */
87 protected $mTrxPreCommitCallbacks = [];
88 /** @var array[] List of (callable, method name) */
89 protected $mTrxEndCallbacks = [];
90 /** @var callable[] Map of (name => callable) */
91 protected $mTrxRecurringCallbacks = [];
92 /** @var bool Whether to suppress triggering of transaction end callbacks */
93 protected $mTrxEndCallbacksSuppressed = false;
96 protected $mTablePrefix = '';
98 protected $mSchema = '';
102 protected $mLBInfo = [];
103 /** @var bool|null */
104 protected $mDefaultBigSelects = null;
105 /** @var array|bool */
106 protected $mSchemaVars = false;
108 protected $mSessionVars = [];
109 /** @var array|null */
110 protected $preparedArgs;
111 /** @var string|bool|null Stashed value of html_errors INI setting */
112 protected $htmlErrors;
114 protected $delimiter = ';';
115 /** @var DatabaseDomain */
116 protected $currentDomain;
119 * Either 1 if a transaction is active or 0 otherwise.
120 * The other Trx fields may not be meaningfull if this is 0.
124 protected $mTrxLevel = 0;
126 * Either a short hexidecimal string if a transaction is active or ""
129 * @see DatabaseBase::mTrxLevel
131 protected $mTrxShortId = '';
133 * The UNIX time that the transaction started. Callers can assume that if
134 * snapshot isolation is used, then the data is *at least* up to date to that
135 * point (possibly more up-to-date since the first SELECT defines the snapshot).
138 * @see DatabaseBase::mTrxLevel
140 private $mTrxTimestamp = null;
141 /** @var float Lag estimate at the time of BEGIN */
142 private $mTrxReplicaLag = null;
144 * Remembers the function name given for starting the most recent transaction via begin().
145 * Used to provide additional context for error reporting.
148 * @see DatabaseBase::mTrxLevel
150 private $mTrxFname = null;
152 * Record if possible write queries were done in the last transaction started
155 * @see DatabaseBase::mTrxLevel
157 private $mTrxDoneWrites = false;
159 * Record if the current transaction was started implicitly due to DBO_TRX being set.
162 * @see DatabaseBase::mTrxLevel
164 private $mTrxAutomatic = false;
166 * Array of levels of atomicity within transactions
170 private $mTrxAtomicLevels = [];
172 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
176 private $mTrxAutomaticAtomic = false;
178 * Track the write query callers of the current transaction
182 private $mTrxWriteCallers = [];
184 * @var float Seconds spent in write queries for the current transaction
186 private $mTrxWriteDuration = 0.0;
188 * @var integer Number of write queries for the current transaction
190 private $mTrxWriteQueryCount = 0;
192 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
194 private $mTrxWriteAdjDuration = 0.0;
196 * @var integer Number of write queries counted in mTrxWriteAdjDuration
198 private $mTrxWriteAdjQueryCount = 0;
200 * @var float RTT time estimate
202 private $mRTTEstimate = 0.0;
204 /** @var array Map of (name => 1) for locks obtained via lock() */
205 private $mNamedLocksHeld = [];
207 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
208 private $lazyMasterHandle;
212 * @var resource File handle for upgrade
214 protected $fileHandle = null;
218 * @var string[] Process cache of VIEWs names in the database
220 protected $allViews = null;
222 /** @var float UNIX timestamp */
223 protected $lastPing = 0.0;
225 /** @var int[] Prior mFlags values */
226 private $priorFlags = [];
228 /** @var object|string Class name or object With profileIn/profileOut methods */
230 /** @var TransactionProfiler */
231 protected $trxProfiler;
236 * FIXME: It is possible to construct a Database object with no associated
237 * connection object, by specifying no parameters to __construct(). This
238 * feature is deprecated and should be removed.
240 * IDatabase classes should not be constructed directly in external
241 * code. DatabaseBase::factory() should be used instead.
243 * @param array $params Parameters passed from DatabaseBase::factory()
245 function __construct( array $params ) {
246 $server = $params['host'];
247 $user = $params['user'];
248 $password = $params['password'];
249 $dbName = $params['dbname'];
250 $flags = $params['flags'];
252 $this->mSchema
= $params['schema'];
253 $this->mTablePrefix
= $params['tablePrefix'];
255 $this->cliMode
= isset( $params['cliMode'] )
257 : ( PHP_SAPI
=== 'cli' );
258 $this->agent
= isset( $params['agent'] )
259 ?
str_replace( '/', '-', $params['agent'] ) // escape for comment
262 $this->mFlags
= $flags;
263 if ( $this->mFlags
& DBO_DEFAULT
) {
264 if ( $this->cliMode
) {
265 $this->mFlags
&= ~DBO_TRX
;
267 $this->mFlags |
= DBO_TRX
;
271 $this->mSessionVars
= $params['variables'];
273 $this->srvCache
= isset( $params['srvCache'] )
274 ?
$params['srvCache']
275 : new HashBagOStuff();
277 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
278 $this->trxProfiler
= isset( $params['trxProfiler'] )
279 ?
$params['trxProfiler']
280 : new TransactionProfiler();
281 $this->connLogger
= isset( $params['connLogger'] )
282 ?
$params['connLogger']
283 : new \Psr\Log\
NullLogger();
284 $this->queryLogger
= isset( $params['queryLogger'] )
285 ?
$params['queryLogger']
286 : new \Psr\Log\
NullLogger();
289 $this->open( $server, $user, $password, $dbName );
292 $this->currentDomain
= ( $this->mDBname
!= '' )
293 ?
new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
)
294 : DatabaseDomain
::newUnspecified();
298 * Given a DB type, construct the name of the appropriate child class of
299 * IDatabase. This is designed to replace all of the manual stuff like:
300 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
301 * as well as validate against the canonical list of DB types we have
303 * This factory function is mostly useful for when you need to connect to a
304 * database other than the MediaWiki default (such as for external auth,
305 * an extension, et cetera). Do not use this to connect to the MediaWiki
306 * database. Example uses in core:
307 * @see LoadBalancer::reallyOpenConnection()
308 * @see ForeignDBRepo::getMasterDB()
309 * @see WebInstallerDBConnect::execute()
313 * @param string $dbType A possible DB type
314 * @param array $p An array of options to pass to the constructor.
315 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
316 * @return IDatabase|null If the database driver or extension cannot be found
317 * @throws InvalidArgumentException If the database driver or extension cannot be found
319 final public static function factory( $dbType, $p = [] ) {
320 $canonicalDBTypes = [
321 'mysql' => [ 'mysqli', 'mysql' ],
329 $dbType = strtolower( $dbType );
330 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
331 $possibleDrivers = $canonicalDBTypes[$dbType];
332 if ( !empty( $p['driver'] ) ) {
333 if ( in_array( $p['driver'], $possibleDrivers ) ) {
334 $driver = $p['driver'];
336 throw new InvalidArgumentException( __METHOD__
.
337 " type '$dbType' does not support driver '{$p['driver']}'" );
340 foreach ( $possibleDrivers as $posDriver ) {
341 if ( extension_loaded( $posDriver ) ) {
342 $driver = $posDriver;
350 if ( $driver === false ) {
351 throw new InvalidArgumentException( __METHOD__
.
352 " no viable database extension found for type '$dbType'" );
355 $class = 'Database' . ucfirst( $driver );
356 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
357 // Resolve some defaults for b/c
358 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
359 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
360 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
361 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
362 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
363 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
364 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
365 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
366 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
368 $conn = new $class( $p );
369 if ( isset( $p['connLogger'] ) ) {
370 $conn->connLogger
= $p['connLogger'];
372 if ( isset( $p['queryLogger'] ) ) {
373 $conn->queryLogger
= $p['queryLogger'];
375 if ( isset( $p['errorLogger'] ) ) {
376 $conn->errorLogger
= $p['errorLogger'];
378 $conn->errorLogger
= function ( Exception
$e ) {
379 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_WARNING
);
389 public function setLogger( LoggerInterface
$logger ) {
390 $this->queryLogger
= $logger;
393 public function getServerInfo() {
394 return $this->getServerVersion();
397 public function bufferResults( $buffer = null ) {
398 $res = !$this->getFlag( DBO_NOBUFFER
);
399 if ( $buffer !== null ) {
400 $buffer ?
$this->clearFlag( DBO_NOBUFFER
) : $this->setFlag( DBO_NOBUFFER
);
407 * Turns on (false) or off (true) the automatic generation and sending
408 * of a "we're sorry, but there has been a database error" page on
409 * database errors. Default is on (false). When turned off, the
410 * code should use lastErrno() and lastError() to handle the
411 * situation as appropriate.
413 * Do not use this function outside of the Database classes.
415 * @param null|bool $ignoreErrors
416 * @return bool The previous value of the flag.
418 protected function ignoreErrors( $ignoreErrors = null ) {
419 $res = $this->getFlag( DBO_IGNORE
);
420 if ( $ignoreErrors !== null ) {
421 $ignoreErrors ?
$this->setFlag( DBO_IGNORE
) : $this->clearFlag( DBO_IGNORE
);
427 public function trxLevel() {
428 return $this->mTrxLevel
;
431 public function trxTimestamp() {
432 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
435 public function tablePrefix( $prefix = null ) {
436 $old = $this->mTablePrefix
;
437 if ( $prefix !== null ) {
438 $this->mTablePrefix
= $prefix;
439 $this->currentDomain
= ( $this->mDBname
!= '' )
440 ?
new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
)
441 : DatabaseDomain
::newUnspecified();
447 public function dbSchema( $schema = null ) {
448 $old = $this->mSchema
;
449 if ( $schema !== null ) {
450 $this->mSchema
= $schema;
457 * Set the filehandle to copy write statements to.
459 * @param resource $fh File handle
461 public function setFileHandle( $fh ) {
462 $this->fileHandle
= $fh;
465 public function getLBInfo( $name = null ) {
466 if ( is_null( $name ) ) {
467 return $this->mLBInfo
;
469 if ( array_key_exists( $name, $this->mLBInfo
) ) {
470 return $this->mLBInfo
[$name];
477 public function setLBInfo( $name, $value = null ) {
478 if ( is_null( $value ) ) {
479 $this->mLBInfo
= $name;
481 $this->mLBInfo
[$name] = $value;
485 public function setLazyMasterHandle( IDatabase
$conn ) {
486 $this->lazyMasterHandle
= $conn;
490 * @return IDatabase|null
491 * @see setLazyMasterHandle()
494 public function getLazyMasterHandle() {
495 return $this->lazyMasterHandle
;
498 public function implicitGroupby() {
502 public function implicitOrderby() {
506 public function lastQuery() {
507 return $this->mLastQuery
;
510 public function doneWrites() {
511 return (bool)$this->mDoneWrites
;
514 public function lastDoneWrites() {
515 return $this->mDoneWrites ?
: false;
518 public function writesPending() {
519 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
522 public function writesOrCallbacksPending() {
523 return $this->mTrxLevel
&& (
524 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
528 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
529 if ( !$this->mTrxLevel
) {
531 } elseif ( !$this->mTrxDoneWrites
) {
536 case self
::ESTIMATE_DB_APPLY
:
538 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
539 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
540 // For omitted queries, make them count as something at least
541 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
542 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
545 default: // everything
546 return $this->mTrxWriteDuration
;
550 public function pendingWriteCallers() {
551 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
554 protected function pendingWriteAndCallbackCallers() {
555 if ( !$this->mTrxLevel
) {
559 $fnames = $this->mTrxWriteCallers
;
561 $this->mTrxIdleCallbacks
,
562 $this->mTrxPreCommitCallbacks
,
563 $this->mTrxEndCallbacks
565 foreach ( $callbacks as $callback ) {
566 $fnames[] = $callback[1];
573 public function isOpen() {
574 return $this->mOpened
;
577 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
578 if ( $remember === self
::REMEMBER_PRIOR
) {
579 array_push( $this->priorFlags
, $this->mFlags
);
581 $this->mFlags |
= $flag;
584 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
585 if ( $remember === self
::REMEMBER_PRIOR
) {
586 array_push( $this->priorFlags
, $this->mFlags
);
588 $this->mFlags
&= ~
$flag;
591 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
592 if ( !$this->priorFlags
) {
596 if ( $state === self
::RESTORE_INITIAL
) {
597 $this->mFlags
= reset( $this->priorFlags
);
598 $this->priorFlags
= [];
600 $this->mFlags
= array_pop( $this->priorFlags
);
604 public function getFlag( $flag ) {
605 return !!( $this->mFlags
& $flag );
608 public function getProperty( $name ) {
612 public function getDomainID() {
613 return $this->currentDomain
->getId();
616 final public function getWikiID() {
617 return $this->getDomainID();
621 * Get information about an index into an object
622 * @param string $table Table name
623 * @param string $index Index name
624 * @param string $fname Calling function name
625 * @return mixed Database-specific index description class or false if the index does not exist
627 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
630 * Wrapper for addslashes()
632 * @param string $s String to be slashed.
633 * @return string Slashed string.
635 abstract function strencode( $s );
637 protected function installErrorHandler() {
638 $this->mPHPError
= false;
639 $this->htmlErrors
= ini_set( 'html_errors', '0' );
640 set_error_handler( [ $this, 'connectionerrorLogger' ] );
644 * @return bool|string
646 protected function restoreErrorHandler() {
647 restore_error_handler();
648 if ( $this->htmlErrors
!== false ) {
649 ini_set( 'html_errors', $this->htmlErrors
);
651 if ( $this->mPHPError
) {
652 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
653 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
663 * @param string $errstr
665 public function connectionerrorLogger( $errno, $errstr ) {
666 $this->mPHPError
= $errstr;
670 * Create a log context to pass to PSR logging functions.
672 * @param array $extras Additional data to add to context
675 protected function getLogContext( array $extras = [] ) {
678 'db_server' => $this->mServer
,
679 'db_name' => $this->mDBname
,
680 'db_user' => $this->mUser
,
686 public function close() {
687 if ( $this->mConn
) {
688 if ( $this->trxLevel() ) {
689 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
692 $closed = $this->closeConnection();
693 $this->mConn
= false;
694 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
695 throw new RuntimeException( "Transaction callbacks still pending." );
699 $this->mOpened
= false;
705 * Make sure isOpen() returns true as a sanity check
707 * @throws DBUnexpectedError
709 protected function assertOpen() {
710 if ( !$this->isOpen() ) {
711 throw new DBUnexpectedError( $this, "DB connection was already closed." );
716 * Closes underlying database connection
718 * @return bool Whether connection was closed successfully
720 abstract protected function closeConnection();
722 function reportConnectionError( $error = 'Unknown error' ) {
723 $myError = $this->lastError();
729 throw new DBConnectionError( $this, $error );
733 * The DBMS-dependent part of query()
735 * @param string $sql SQL query.
736 * @return ResultWrapper|bool Result object to feed to fetchObject,
737 * fetchRow, ...; or false on failure
739 abstract protected function doQuery( $sql );
742 * Determine whether a query writes to the DB.
743 * Should return true if unsure.
748 protected function isWriteQuery( $sql ) {
750 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
755 * @return string|null
757 protected function getQueryVerb( $sql ) {
758 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
762 * Determine whether a SQL statement is sensitive to isolation level.
763 * A SQL statement is considered transactable if its result could vary
764 * depending on the transaction isolation level. Operational commands
765 * such as 'SET' and 'SHOW' are not considered to be transactable.
770 protected function isTransactableQuery( $sql ) {
771 $verb = $this->getQueryVerb( $sql );
772 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
775 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
776 $priorWritesPending = $this->writesOrCallbacksPending();
777 $this->mLastQuery
= $sql;
779 $isWrite = $this->isWriteQuery( $sql );
781 $reason = $this->getReadOnlyReason();
782 if ( $reason !== false ) {
783 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
785 # Set a flag indicating that writes have been done
786 $this->mDoneWrites
= microtime( true );
789 // Add trace comment to the begin of the sql string, right after the operator.
790 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
791 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
793 # Start implicit transactions that wrap the request if DBO_TRX is enabled
794 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
)
795 && $this->isTransactableQuery( $sql )
797 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
798 $this->mTrxAutomatic
= true;
801 # Keep track of whether the transaction has write queries pending
802 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
803 $this->mTrxDoneWrites
= true;
804 $this->trxProfiler
->transactionWritingIn(
805 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
808 if ( $this->getFlag( DBO_DEBUG
) ) {
809 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
812 # Avoid fatals if close() was called
815 # Send the query to the server
816 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
818 # Try reconnecting if the connection was lost
819 if ( false === $ret && $this->wasErrorReissuable() ) {
820 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
821 # Stash the last error values before anything might clear them
822 $lastError = $this->lastError();
823 $lastErrno = $this->lastErrno();
824 # Update state tracking to reflect transaction loss due to disconnection
825 $this->handleTransactionLoss();
826 if ( $this->reconnect() ) {
827 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
828 $this->connLogger
->warning( $msg );
829 $this->queryLogger
->warning(
830 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
832 if ( !$recoverable ) {
833 # Callers may catch the exception and continue to use the DB
834 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
836 # Should be safe to silently retry the query
837 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
840 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
841 $this->connLogger
->error( $msg );
845 if ( false === $ret ) {
846 # Deadlocks cause the entire transaction to abort, not just the statement.
847 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
848 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
849 if ( $this->wasDeadlock() ) {
850 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
851 $tempIgnore = false; // not recoverable
853 # Update state tracking to reflect transaction loss
854 $this->handleTransactionLoss();
857 $this->reportQueryError(
858 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
861 $res = $this->resultObject( $ret );
866 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
867 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
868 # generalizeSQL() will probably cut down the query to reasonable
869 # logging size most of the time. The substr is really just a sanity check.
871 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
873 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
876 # Include query transaction state
877 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
879 $startTime = microtime( true );
880 if ( $this->profiler
) {
881 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
883 $ret = $this->doQuery( $commentedSql );
884 if ( $this->profiler
) {
885 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
887 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
889 unset( $queryProfSection ); // profile out (if set)
891 if ( $ret !== false ) {
892 $this->lastPing
= $startTime;
893 if ( $isWrite && $this->mTrxLevel
) {
894 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
895 $this->mTrxWriteCallers
[] = $fname;
899 if ( $sql === self
::PING_QUERY
) {
900 $this->mRTTEstimate
= $queryRuntime;
903 $this->trxProfiler
->recordQueryCompletion(
904 $queryProf, $startTime, $isWrite, $this->affectedRows()
906 $this->queryLogger
->debug( $sql, [
908 'master' => $isMaster,
909 'runtime' => $queryRuntime,
916 * Update the estimated run-time of a query, not counting large row lock times
918 * LoadBalancer can be set to rollback transactions that will create huge replication
919 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
920 * queries, like inserting a row can take a long time due to row locking. This method
921 * uses some simple heuristics to discount those cases.
923 * @param string $sql A SQL write query
924 * @param float $runtime Total runtime, including RTT
926 private function updateTrxWriteQueryTime( $sql, $runtime ) {
927 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
928 $indicativeOfReplicaRuntime = true;
929 if ( $runtime > self
::SLOW_WRITE_SEC
) {
930 $verb = $this->getQueryVerb( $sql );
931 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
932 if ( $verb === 'INSERT' ) {
933 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
934 } elseif ( $verb === 'REPLACE' ) {
935 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
939 $this->mTrxWriteDuration +
= $runtime;
940 $this->mTrxWriteQueryCount +
= 1;
941 if ( $indicativeOfReplicaRuntime ) {
942 $this->mTrxWriteAdjDuration +
= $runtime;
943 $this->mTrxWriteAdjQueryCount +
= 1;
947 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
948 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
949 # Dropped connections also mean that named locks are automatically released.
950 # Only allow error suppression in autocommit mode or when the lost transaction
951 # didn't matter anyway (aside from DBO_TRX snapshot loss).
952 if ( $this->mNamedLocksHeld
) {
953 return false; // possible critical section violation
954 } elseif ( $sql === 'COMMIT' ) {
955 return !$priorWritesPending; // nothing written anyway? (T127428)
956 } elseif ( $sql === 'ROLLBACK' ) {
957 return true; // transaction lost...which is also what was requested :)
958 } elseif ( $this->explicitTrxActive() ) {
959 return false; // don't drop atomocity
960 } elseif ( $priorWritesPending ) {
961 return false; // prior writes lost from implicit transaction
967 private function handleTransactionLoss() {
968 $this->mTrxLevel
= 0;
969 $this->mTrxIdleCallbacks
= []; // bug 65263
970 $this->mTrxPreCommitCallbacks
= []; // bug 65263
972 // Handle callbacks in mTrxEndCallbacks
973 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
974 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
976 } catch ( Exception
$e ) {
977 // Already logged; move on...
982 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
983 if ( $this->ignoreErrors() ||
$tempIgnore ) {
984 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
986 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
987 $this->queryLogger
->error(
988 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
989 $this->getLogContext( [
990 'method' => __METHOD__
,
993 'sql1line' => $sql1line,
997 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
998 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1002 public function freeResult( $res ) {
1005 public function selectField(
1006 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1008 if ( $var === '*' ) { // sanity
1009 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1012 if ( !is_array( $options ) ) {
1013 $options = [ $options ];
1016 $options['LIMIT'] = 1;
1018 $res = $this->select( $table, $var, $cond, $fname, $options );
1019 if ( $res === false ||
!$this->numRows( $res ) ) {
1023 $row = $this->fetchRow( $res );
1025 if ( $row !== false ) {
1026 return reset( $row );
1032 public function selectFieldValues(
1033 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1035 if ( $var === '*' ) { // sanity
1036 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1037 } elseif ( !is_string( $var ) ) { // sanity
1038 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1041 if ( !is_array( $options ) ) {
1042 $options = [ $options ];
1045 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1046 if ( $res === false ) {
1051 foreach ( $res as $row ) {
1052 $values[] = $row->$var;
1059 * Returns an optional USE INDEX clause to go after the table, and a
1060 * string to go at the end of the query.
1062 * @param array $options Associative array of options to be turned into
1063 * an SQL query, valid keys are listed in the function.
1065 * @see DatabaseBase::select()
1067 public function makeSelectOptions( $options ) {
1068 $preLimitTail = $postLimitTail = '';
1073 foreach ( $options as $key => $option ) {
1074 if ( is_numeric( $key ) ) {
1075 $noKeyOptions[$option] = true;
1079 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1081 $preLimitTail .= $this->makeOrderBy( $options );
1083 // if (isset($options['LIMIT'])) {
1084 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1085 // isset($options['OFFSET']) ? $options['OFFSET']
1089 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1090 $postLimitTail .= ' FOR UPDATE';
1093 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1094 $postLimitTail .= ' LOCK IN SHARE MODE';
1097 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1098 $startOpts .= 'DISTINCT';
1101 # Various MySQL extensions
1102 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1103 $startOpts .= ' /*! STRAIGHT_JOIN */';
1106 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1107 $startOpts .= ' HIGH_PRIORITY';
1110 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1111 $startOpts .= ' SQL_BIG_RESULT';
1114 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1115 $startOpts .= ' SQL_BUFFER_RESULT';
1118 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1119 $startOpts .= ' SQL_SMALL_RESULT';
1122 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1123 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1126 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1127 $startOpts .= ' SQL_CACHE';
1130 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1131 $startOpts .= ' SQL_NO_CACHE';
1134 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1135 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1139 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1140 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1145 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1149 * Returns an optional GROUP BY with an optional HAVING
1151 * @param array $options Associative array of options
1153 * @see DatabaseBase::select()
1156 public function makeGroupByWithHaving( $options ) {
1158 if ( isset( $options['GROUP BY'] ) ) {
1159 $gb = is_array( $options['GROUP BY'] )
1160 ?
implode( ',', $options['GROUP BY'] )
1161 : $options['GROUP BY'];
1162 $sql .= ' GROUP BY ' . $gb;
1164 if ( isset( $options['HAVING'] ) ) {
1165 $having = is_array( $options['HAVING'] )
1166 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1167 : $options['HAVING'];
1168 $sql .= ' HAVING ' . $having;
1175 * Returns an optional ORDER BY
1177 * @param array $options Associative array of options
1179 * @see DatabaseBase::select()
1182 public function makeOrderBy( $options ) {
1183 if ( isset( $options['ORDER BY'] ) ) {
1184 $ob = is_array( $options['ORDER BY'] )
1185 ?
implode( ',', $options['ORDER BY'] )
1186 : $options['ORDER BY'];
1188 return ' ORDER BY ' . $ob;
1194 // See IDatabase::select for the docs for this function
1195 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1196 $options = [], $join_conds = [] ) {
1197 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1199 return $this->query( $sql, $fname );
1202 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1203 $options = [], $join_conds = []
1205 if ( is_array( $vars ) ) {
1206 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1209 $options = (array)$options;
1210 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1211 ?
$options['USE INDEX']
1213 $ignoreIndexes = ( isset( $options['IGNORE INDEX'] ) && is_array( $options['IGNORE INDEX'] ) )
1214 ?
$options['IGNORE INDEX']
1217 if ( is_array( $table ) ) {
1219 $this->tableNamesWithIndexClauseOrJOIN( $table, $useIndexes, $ignoreIndexes, $join_conds );
1220 } elseif ( $table != '' ) {
1221 if ( $table[0] == ' ' ) {
1222 $from = ' FROM ' . $table;
1225 $this->tableNamesWithIndexClauseOrJOIN( [ $table ], $useIndexes, $ignoreIndexes, [] );
1231 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1232 $this->makeSelectOptions( $options );
1234 if ( !empty( $conds ) ) {
1235 if ( is_array( $conds ) ) {
1236 $conds = $this->makeList( $conds, self
::LIST_AND
);
1238 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex WHERE $conds $preLimitTail";
1240 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1243 if ( isset( $options['LIMIT'] ) ) {
1244 $sql = $this->limitResult( $sql, $options['LIMIT'],
1245 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1247 $sql = "$sql $postLimitTail";
1249 if ( isset( $options['EXPLAIN'] ) ) {
1250 $sql = 'EXPLAIN ' . $sql;
1256 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1257 $options = [], $join_conds = []
1259 $options = (array)$options;
1260 $options['LIMIT'] = 1;
1261 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1263 if ( $res === false ) {
1267 if ( !$this->numRows( $res ) ) {
1271 $obj = $this->fetchObject( $res );
1276 public function estimateRowCount(
1277 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1280 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1283 $row = $this->fetchRow( $res );
1284 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1290 public function selectRowCount(
1291 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1294 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1295 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1298 $row = $this->fetchRow( $res );
1299 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1306 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1307 * It's only slightly flawed. Don't use for anything important.
1309 * @param string $sql A SQL Query
1313 protected static function generalizeSQL( $sql ) {
1314 # This does the same as the regexp below would do, but in such a way
1315 # as to avoid crashing php on some large strings.
1316 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1318 $sql = str_replace( "\\\\", '', $sql );
1319 $sql = str_replace( "\\'", '', $sql );
1320 $sql = str_replace( "\\\"", '', $sql );
1321 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1322 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1324 # All newlines, tabs, etc replaced by single space
1325 $sql = preg_replace( '/\s+/', ' ', $sql );
1328 # except the ones surrounded by characters, e.g. l10n
1329 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1330 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1335 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1336 $info = $this->fieldInfo( $table, $field );
1341 public function indexExists( $table, $index, $fname = __METHOD__
) {
1342 if ( !$this->tableExists( $table ) ) {
1346 $info = $this->indexInfo( $table, $index, $fname );
1347 if ( is_null( $info ) ) {
1350 return $info !== false;
1354 public function tableExists( $table, $fname = __METHOD__
) {
1355 $table = $this->tableName( $table );
1356 $old = $this->ignoreErrors( true );
1357 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1358 $this->ignoreErrors( $old );
1363 public function indexUnique( $table, $index ) {
1364 $indexInfo = $this->indexInfo( $table, $index );
1366 if ( !$indexInfo ) {
1370 return !$indexInfo[0]->Non_unique
;
1374 * Helper for DatabaseBase::insert().
1376 * @param array $options
1379 protected function makeInsertOptions( $options ) {
1380 return implode( ' ', $options );
1383 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1384 # No rows to insert, easy just return now
1385 if ( !count( $a ) ) {
1389 $table = $this->tableName( $table );
1391 if ( !is_array( $options ) ) {
1392 $options = [ $options ];
1396 if ( isset( $options['fileHandle'] ) ) {
1397 $fh = $options['fileHandle'];
1399 $options = $this->makeInsertOptions( $options );
1401 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1403 $keys = array_keys( $a[0] );
1406 $keys = array_keys( $a );
1409 $sql = 'INSERT ' . $options .
1410 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1414 foreach ( $a as $row ) {
1420 $sql .= '(' . $this->makeList( $row ) . ')';
1423 $sql .= '(' . $this->makeList( $a ) . ')';
1426 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1428 } elseif ( $fh !== null ) {
1432 return (bool)$this->query( $sql, $fname );
1436 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1438 * @param array $options
1441 protected function makeUpdateOptionsArray( $options ) {
1442 if ( !is_array( $options ) ) {
1443 $options = [ $options ];
1448 if ( in_array( 'IGNORE', $options ) ) {
1456 * Make UPDATE options for the DatabaseBase::update function
1458 * @param array $options The options passed to DatabaseBase::update
1461 protected function makeUpdateOptions( $options ) {
1462 $opts = $this->makeUpdateOptionsArray( $options );
1464 return implode( ' ', $opts );
1467 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1468 $table = $this->tableName( $table );
1469 $opts = $this->makeUpdateOptions( $options );
1470 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1472 if ( $conds !== [] && $conds !== '*' ) {
1473 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1476 return $this->query( $sql, $fname );
1479 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1480 if ( !is_array( $a ) ) {
1481 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1487 foreach ( $a as $field => $value ) {
1489 if ( $mode == self
::LIST_AND
) {
1491 } elseif ( $mode == self
::LIST_OR
) {
1500 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1501 $list .= "($value)";
1502 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1505 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1507 // Remove null from array to be handled separately if found
1508 $includeNull = false;
1509 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1510 $includeNull = true;
1511 unset( $value[$nullKey] );
1513 if ( count( $value ) == 0 && !$includeNull ) {
1514 throw new InvalidArgumentException(
1515 __METHOD__
. ": empty input for field $field" );
1516 } elseif ( count( $value ) == 0 ) {
1517 // only check if $field is null
1518 $list .= "$field IS NULL";
1520 // IN clause contains at least one valid element
1521 if ( $includeNull ) {
1522 // Group subconditions to ensure correct precedence
1525 if ( count( $value ) == 1 ) {
1526 // Special-case single values, as IN isn't terribly efficient
1527 // Don't necessarily assume the single key is 0; we don't
1528 // enforce linear numeric ordering on other arrays here.
1529 $value = array_values( $value )[0];
1530 $list .= $field . " = " . $this->addQuotes( $value );
1532 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1534 // if null present in array, append IS NULL
1535 if ( $includeNull ) {
1536 $list .= " OR $field IS NULL)";
1539 } elseif ( $value === null ) {
1540 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1541 $list .= "$field IS ";
1542 } elseif ( $mode == self
::LIST_SET
) {
1543 $list .= "$field = ";
1548 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1550 $list .= "$field = ";
1552 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1559 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1562 foreach ( $data as $base => $sub ) {
1563 if ( count( $sub ) ) {
1564 $conds[] = $this->makeList(
1565 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1571 return $this->makeList( $conds, self
::LIST_OR
);
1573 // Nothing to search for...
1579 * Return aggregated value alias
1581 * @param array $valuedata
1582 * @param string $valuename
1586 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1590 public function bitNot( $field ) {
1594 public function bitAnd( $fieldLeft, $fieldRight ) {
1595 return "($fieldLeft & $fieldRight)";
1598 public function bitOr( $fieldLeft, $fieldRight ) {
1599 return "($fieldLeft | $fieldRight)";
1602 public function buildConcat( $stringList ) {
1603 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1606 public function buildGroupConcatField(
1607 $delim, $table, $field, $conds = '', $join_conds = []
1609 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1611 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1615 * @param string $field Field or column to cast
1619 public function buildStringCast( $field ) {
1623 public function selectDB( $db ) {
1624 # Stub. Shouldn't cause serious problems if it's not overridden, but
1625 # if your database engine supports a concept similar to MySQL's
1626 # databases you may as well.
1627 $this->mDBname
= $db;
1632 public function getDBname() {
1633 return $this->mDBname
;
1636 public function getServer() {
1637 return $this->mServer
;
1641 * Format a table name ready for use in constructing an SQL query
1643 * This does two important things: it quotes the table names to clean them up,
1644 * and it adds a table prefix if only given a table name with no quotes.
1646 * All functions of this object which require a table name call this function
1647 * themselves. Pass the canonical name to such functions. This is only needed
1648 * when calling query() directly.
1650 * @note This function does not sanitize user input. It is not safe to use
1651 * this function to escape user input.
1652 * @param string $name Database table name
1653 * @param string $format One of:
1654 * quoted - Automatically pass the table name through addIdentifierQuotes()
1655 * so that it can be used in a query.
1656 * raw - Do not add identifier quotes to the table name
1657 * @return string Full database name
1659 public function tableName( $name, $format = 'quoted' ) {
1660 # Skip the entire process when we have a string quoted on both ends.
1661 # Note that we check the end so that we will still quote any use of
1662 # use of `database`.table. But won't break things if someone wants
1663 # to query a database table with a dot in the name.
1664 if ( $this->isQuotedIdentifier( $name ) ) {
1668 # Lets test for any bits of text that should never show up in a table
1669 # name. Basically anything like JOIN or ON which are actually part of
1670 # SQL queries, but may end up inside of the table value to combine
1671 # sql. Such as how the API is doing.
1672 # Note that we use a whitespace test rather than a \b test to avoid
1673 # any remote case where a word like on may be inside of a table name
1674 # surrounded by symbols which may be considered word breaks.
1675 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1679 # Split database and table into proper variables.
1680 # We reverse the explode so that database.table and table both output
1681 # the correct table.
1682 $dbDetails = explode( '.', $name, 3 );
1683 if ( count( $dbDetails ) == 3 ) {
1684 list( $database, $schema, $table ) = $dbDetails;
1685 # We don't want any prefix added in this case
1687 } elseif ( count( $dbDetails ) == 2 ) {
1688 list( $database, $table ) = $dbDetails;
1689 # We don't want any prefix added in this case
1690 # In dbs that support it, $database may actually be the schema
1691 # but that doesn't affect any of the functionality here
1695 list( $table ) = $dbDetails;
1696 if ( isset( $this->tableAliases
[$table] ) ) {
1697 $database = $this->tableAliases
[$table]['dbname'];
1698 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1699 ?
$this->tableAliases
[$table]['schema']
1701 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1702 ?
$this->tableAliases
[$table]['prefix']
1703 : $this->mTablePrefix
;
1706 $schema = $this->mSchema
; # Default schema
1707 $prefix = $this->mTablePrefix
; # Default prefix
1711 # Quote $table and apply the prefix if not quoted.
1712 # $tableName might be empty if this is called from Database::replaceVars()
1713 $tableName = "{$prefix}{$table}";
1714 if ( $format == 'quoted'
1715 && !$this->isQuotedIdentifier( $tableName ) && $tableName !== ''
1717 $tableName = $this->addIdentifierQuotes( $tableName );
1720 # Quote $schema and merge it with the table name if needed
1721 if ( strlen( $schema ) ) {
1722 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1723 $schema = $this->addIdentifierQuotes( $schema );
1725 $tableName = $schema . '.' . $tableName;
1728 # Quote $database and merge it with the table name if needed
1729 if ( $database !== '' ) {
1730 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1731 $database = $this->addIdentifierQuotes( $database );
1733 $tableName = $database . '.' . $tableName;
1740 * Fetch a number of table names into an array
1741 * This is handy when you need to construct SQL for joins
1744 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1745 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1746 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1750 public function tableNames() {
1751 $inArray = func_get_args();
1754 foreach ( $inArray as $name ) {
1755 $retVal[$name] = $this->tableName( $name );
1762 * Fetch a number of table names into an zero-indexed numerical array
1763 * This is handy when you need to construct SQL for joins
1766 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1767 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1768 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1772 public function tableNamesN() {
1773 $inArray = func_get_args();
1776 foreach ( $inArray as $name ) {
1777 $retVal[] = $this->tableName( $name );
1784 * Get an aliased table name
1785 * e.g. tableName AS newTableName
1787 * @param string $name Table name, see tableName()
1788 * @param string|bool $alias Alias (optional)
1789 * @return string SQL name for aliased table. Will not alias a table to its own name
1791 public function tableNameWithAlias( $name, $alias = false ) {
1792 if ( !$alias ||
$alias == $name ) {
1793 return $this->tableName( $name );
1795 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1800 * Gets an array of aliased table names
1802 * @param array $tables [ [alias] => table ]
1803 * @return string[] See tableNameWithAlias()
1805 public function tableNamesWithAlias( $tables ) {
1807 foreach ( $tables as $alias => $table ) {
1808 if ( is_numeric( $alias ) ) {
1811 $retval[] = $this->tableNameWithAlias( $table, $alias );
1818 * Get an aliased field name
1819 * e.g. fieldName AS newFieldName
1821 * @param string $name Field name
1822 * @param string|bool $alias Alias (optional)
1823 * @return string SQL name for aliased field. Will not alias a field to its own name
1825 public function fieldNameWithAlias( $name, $alias = false ) {
1826 if ( !$alias ||
(string)$alias === (string)$name ) {
1829 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1834 * Gets an array of aliased field names
1836 * @param array $fields [ [alias] => field ]
1837 * @return string[] See fieldNameWithAlias()
1839 public function fieldNamesWithAlias( $fields ) {
1841 foreach ( $fields as $alias => $field ) {
1842 if ( is_numeric( $alias ) ) {
1845 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1852 * Get the aliased table name clause for a FROM clause
1853 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
1855 * @param array $tables ( [alias] => table )
1856 * @param array $use_index Same as for select()
1857 * @param array $ignore_index Same as for select()
1858 * @param array $join_conds Same as for select()
1861 protected function tableNamesWithIndexClauseOrJOIN(
1862 $tables, $use_index = [], $ignore_index = [], $join_conds = []
1866 $use_index = (array)$use_index;
1867 $ignore_index = (array)$ignore_index;
1868 $join_conds = (array)$join_conds;
1870 foreach ( $tables as $alias => $table ) {
1871 if ( !is_string( $alias ) ) {
1872 // No alias? Set it equal to the table name
1875 // Is there a JOIN clause for this table?
1876 if ( isset( $join_conds[$alias] ) ) {
1877 list( $joinType, $conds ) = $join_conds[$alias];
1878 $tableClause = $joinType;
1879 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1880 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1881 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1883 $tableClause .= ' ' . $use;
1886 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
1887 $ignore = $this->ignoreIndexClause( implode( ',', (array)$ignore_index[$alias] ) );
1888 if ( $ignore != '' ) {
1889 $tableClause .= ' ' . $ignore;
1892 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
1894 $tableClause .= ' ON (' . $on . ')';
1897 $retJOIN[] = $tableClause;
1898 } elseif ( isset( $use_index[$alias] ) ) {
1899 // Is there an INDEX clause for this table?
1900 $tableClause = $this->tableNameWithAlias( $table, $alias );
1901 $tableClause .= ' ' . $this->useIndexClause(
1902 implode( ',', (array)$use_index[$alias] )
1905 $ret[] = $tableClause;
1906 } elseif ( isset( $ignore_index[$alias] ) ) {
1907 // Is there an INDEX clause for this table?
1908 $tableClause = $this->tableNameWithAlias( $table, $alias );
1909 $tableClause .= ' ' . $this->ignoreIndexClause(
1910 implode( ',', (array)$ignore_index[$alias] )
1913 $ret[] = $tableClause;
1915 $tableClause = $this->tableNameWithAlias( $table, $alias );
1917 $ret[] = $tableClause;
1921 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1922 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1923 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1925 // Compile our final table clause
1926 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
1930 * Get the name of an index in a given table.
1932 * @param string $index
1935 protected function indexName( $index ) {
1936 // Backwards-compatibility hack
1938 'ar_usertext_timestamp' => 'usertext_timestamp',
1939 'un_user_id' => 'user_id',
1940 'un_user_ip' => 'user_ip',
1943 if ( isset( $renamed[$index] ) ) {
1944 return $renamed[$index];
1950 public function addQuotes( $s ) {
1951 if ( $s instanceof Blob
) {
1954 if ( $s === null ) {
1957 # This will also quote numeric values. This should be harmless,
1958 # and protects against weird problems that occur when they really
1959 # _are_ strings such as article titles and string->number->string
1960 # conversion is not 1:1.
1961 return "'" . $this->strencode( $s ) . "'";
1966 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1967 * MySQL uses `backticks` while basically everything else uses double quotes.
1968 * Since MySQL is the odd one out here the double quotes are our generic
1969 * and we implement backticks in DatabaseMysql.
1974 public function addIdentifierQuotes( $s ) {
1975 return '"' . str_replace( '"', '""', $s ) . '"';
1979 * Returns if the given identifier looks quoted or not according to
1980 * the database convention for quoting identifiers .
1982 * @note Do not use this to determine if untrusted input is safe.
1983 * A malicious user can trick this function.
1984 * @param string $name
1987 public function isQuotedIdentifier( $name ) {
1988 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
1995 protected function escapeLikeInternal( $s ) {
1996 return addcslashes( $s, '\%_' );
1999 public function buildLike() {
2000 $params = func_get_args();
2002 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2003 $params = $params[0];
2008 foreach ( $params as $value ) {
2009 if ( $value instanceof LikeMatch
) {
2010 $s .= $value->toString();
2012 $s .= $this->escapeLikeInternal( $value );
2016 return " LIKE {$this->addQuotes( $s )} ";
2019 public function anyChar() {
2020 return new LikeMatch( '_' );
2023 public function anyString() {
2024 return new LikeMatch( '%' );
2027 public function nextSequenceValue( $seqName ) {
2032 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2033 * is only needed because a) MySQL must be as efficient as possible due to
2034 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2035 * which index to pick. Anyway, other databases might have different
2036 * indexes on a given table. So don't bother overriding this unless you're
2038 * @param string $index
2041 public function useIndexClause( $index ) {
2046 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2047 * is only needed because a) MySQL must be as efficient as possible due to
2048 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2049 * which index to pick. Anyway, other databases might have different
2050 * indexes on a given table. So don't bother overriding this unless you're
2052 * @param string $index
2055 public function ignoreIndexClause( $index ) {
2059 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2060 $quotedTable = $this->tableName( $table );
2062 if ( count( $rows ) == 0 ) {
2067 if ( !is_array( reset( $rows ) ) ) {
2071 // @FXIME: this is not atomic, but a trx would break affectedRows()
2072 foreach ( $rows as $row ) {
2073 # Delete rows which collide
2074 if ( $uniqueIndexes ) {
2075 $sql = "DELETE FROM $quotedTable WHERE ";
2077 foreach ( $uniqueIndexes as $index ) {
2084 if ( is_array( $index ) ) {
2086 foreach ( $index as $col ) {
2092 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2095 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2099 $this->query( $sql, $fname );
2102 # Now insert the row
2103 $this->insert( $table, $row, $fname );
2108 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2111 * @param string $table Table name
2112 * @param array|string $rows Row(s) to insert
2113 * @param string $fname Caller function name
2115 * @return ResultWrapper
2117 protected function nativeReplace( $table, $rows, $fname ) {
2118 $table = $this->tableName( $table );
2121 if ( !is_array( reset( $rows ) ) ) {
2125 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2128 foreach ( $rows as $row ) {
2135 $sql .= '(' . $this->makeList( $row ) . ')';
2138 return $this->query( $sql, $fname );
2141 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2144 if ( !count( $rows ) ) {
2145 return true; // nothing to do
2148 if ( !is_array( reset( $rows ) ) ) {
2152 if ( count( $uniqueIndexes ) ) {
2153 $clauses = []; // list WHERE clauses that each identify a single row
2154 foreach ( $rows as $row ) {
2155 foreach ( $uniqueIndexes as $index ) {
2156 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2157 $rowKey = []; // unique key to this row
2158 foreach ( $index as $column ) {
2159 $rowKey[$column] = $row[$column];
2161 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2164 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2169 $useTrx = !$this->mTrxLevel
;
2171 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2174 # Update any existing conflicting row(s)
2175 if ( $where !== false ) {
2176 $ok = $this->update( $table, $set, $where, $fname );
2180 # Now insert any non-conflicting row(s)
2181 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2182 } catch ( Exception
$e ) {
2184 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2189 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2195 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2199 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2202 $delTable = $this->tableName( $delTable );
2203 $joinTable = $this->tableName( $joinTable );
2204 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2205 if ( $conds != '*' ) {
2206 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2210 $this->query( $sql, $fname );
2214 * Returns the size of a text field, or -1 for "unlimited"
2216 * @param string $table
2217 * @param string $field
2220 public function textFieldSize( $table, $field ) {
2221 $table = $this->tableName( $table );
2222 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2223 $res = $this->query( $sql, __METHOD__
);
2224 $row = $this->fetchObject( $res );
2228 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2237 public function delete( $table, $conds, $fname = __METHOD__
) {
2239 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2242 $table = $this->tableName( $table );
2243 $sql = "DELETE FROM $table";
2245 if ( $conds != '*' ) {
2246 if ( is_array( $conds ) ) {
2247 $conds = $this->makeList( $conds, self
::LIST_AND
);
2249 $sql .= ' WHERE ' . $conds;
2252 return $this->query( $sql, $fname );
2255 public function insertSelect(
2256 $destTable, $srcTable, $varMap, $conds,
2257 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2259 if ( $this->cliMode
) {
2260 // For massive migrations with downtime, we don't want to select everything
2261 // into memory and OOM, so do all this native on the server side if possible.
2262 return $this->nativeInsertSelect(
2273 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2274 // on only the master (without needing row-based-replication). It also makes it easy to
2275 // know how big the INSERT is going to be.
2277 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2278 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2280 $selectOptions[] = 'FOR UPDATE';
2281 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2287 foreach ( $res as $row ) {
2288 $rows[] = (array)$row;
2291 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2294 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2295 $fname = __METHOD__
,
2296 $insertOptions = [], $selectOptions = []
2298 $destTable = $this->tableName( $destTable );
2300 if ( !is_array( $insertOptions ) ) {
2301 $insertOptions = [ $insertOptions ];
2304 $insertOptions = $this->makeInsertOptions( $insertOptions );
2306 if ( !is_array( $selectOptions ) ) {
2307 $selectOptions = [ $selectOptions ];
2310 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2313 if ( is_array( $srcTable ) ) {
2314 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2316 $srcTable = $this->tableName( $srcTable );
2319 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2320 " SELECT $startOpts " . implode( ',', $varMap ) .
2321 " FROM $srcTable $useIndex $ignoreIndex ";
2323 if ( $conds != '*' ) {
2324 if ( is_array( $conds ) ) {
2325 $conds = $this->makeList( $conds, self
::LIST_AND
);
2327 $sql .= " WHERE $conds";
2330 $sql .= " $tailOpts";
2332 return $this->query( $sql, $fname );
2336 * Construct a LIMIT query with optional offset. This is used for query
2337 * pages. The SQL should be adjusted so that only the first $limit rows
2338 * are returned. If $offset is provided as well, then the first $offset
2339 * rows should be discarded, and the next $limit rows should be returned.
2340 * If the result of the query is not ordered, then the rows to be returned
2341 * are theoretically arbitrary.
2343 * $sql is expected to be a SELECT, if that makes a difference.
2345 * The version provided by default works in MySQL and SQLite. It will very
2346 * likely need to be overridden for most other DBMSes.
2348 * @param string $sql SQL query we will append the limit too
2349 * @param int $limit The SQL limit
2350 * @param int|bool $offset The SQL offset (default false)
2351 * @throws DBUnexpectedError
2354 public function limitResult( $sql, $limit, $offset = false ) {
2355 if ( !is_numeric( $limit ) ) {
2356 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2359 return "$sql LIMIT "
2360 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2364 public function unionSupportsOrderAndLimit() {
2365 return true; // True for almost every DB supported
2368 public function unionQueries( $sqls, $all ) {
2369 $glue = $all ?
') UNION ALL (' : ') UNION (';
2371 return '(' . implode( $glue, $sqls ) . ')';
2374 public function conditional( $cond, $trueVal, $falseVal ) {
2375 if ( is_array( $cond ) ) {
2376 $cond = $this->makeList( $cond, self
::LIST_AND
);
2379 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2382 public function strreplace( $orig, $old, $new ) {
2383 return "REPLACE({$orig}, {$old}, {$new})";
2386 public function getServerUptime() {
2390 public function wasDeadlock() {
2394 public function wasLockTimeout() {
2398 public function wasErrorReissuable() {
2402 public function wasReadOnlyError() {
2407 * Determines if the given query error was a connection drop
2410 * @param integer|string $errno
2413 public function wasConnectionError( $errno ) {
2418 * Perform a deadlock-prone transaction.
2420 * This function invokes a callback function to perform a set of write
2421 * queries. If a deadlock occurs during the processing, the transaction
2422 * will be rolled back and the callback function will be called again.
2424 * Avoid using this method outside of Job or Maintenance classes.
2427 * $dbw->deadlockLoop( callback, ... );
2429 * Extra arguments are passed through to the specified callback function.
2430 * This method requires that no transactions are already active to avoid
2431 * causing premature commits or exceptions.
2433 * Returns whatever the callback function returned on its successful,
2434 * iteration, or false on error, for example if the retry limit was
2438 * @throws DBUnexpectedError
2441 public function deadlockLoop() {
2442 $args = func_get_args();
2443 $function = array_shift( $args );
2444 $tries = self
::DEADLOCK_TRIES
;
2446 $this->begin( __METHOD__
);
2449 /** @var Exception $e */
2453 $retVal = call_user_func_array( $function, $args );
2455 } catch ( DBQueryError
$e ) {
2456 if ( $this->wasDeadlock() ) {
2457 // Retry after a randomized delay
2458 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2460 // Throw the error back up
2464 } while ( --$tries > 0 );
2466 if ( $tries <= 0 ) {
2467 // Too many deadlocks; give up
2468 $this->rollback( __METHOD__
);
2471 $this->commit( __METHOD__
);
2477 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2478 # Real waits are implemented in the subclass.
2482 public function getSlavePos() {
2487 public function getMasterPos() {
2492 public function serverIsReadOnly() {
2496 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2497 if ( !$this->mTrxLevel
) {
2498 throw new DBUnexpectedError( $this, "No transaction is active." );
2500 $this->mTrxEndCallbacks
[] = [ $callback, $fname ];
2503 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2504 $this->mTrxIdleCallbacks
[] = [ $callback, $fname ];
2505 if ( !$this->mTrxLevel
) {
2506 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2510 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2511 if ( $this->mTrxLevel
) {
2512 $this->mTrxPreCommitCallbacks
[] = [ $callback, $fname ];
2514 // If no transaction is active, then make one for this callback
2515 $this->startAtomic( __METHOD__
);
2517 call_user_func( $callback );
2518 $this->endAtomic( __METHOD__
);
2519 } catch ( Exception
$e ) {
2520 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2526 final public function setTransactionListener( $name, callable
$callback = null ) {
2528 $this->mTrxRecurringCallbacks
[$name] = $callback;
2530 unset( $this->mTrxRecurringCallbacks
[$name] );
2535 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2537 * This method should not be used outside of Database/LoadBalancer
2539 * @param bool $suppress
2542 final public function setTrxEndCallbackSuppression( $suppress ) {
2543 $this->mTrxEndCallbacksSuppressed
= $suppress;
2547 * Actually run and consume any "on transaction idle/resolution" callbacks.
2549 * This method should not be used outside of Database/LoadBalancer
2551 * @param integer $trigger IDatabase::TRIGGER_* constant
2555 public function runOnTransactionIdleCallbacks( $trigger ) {
2556 if ( $this->mTrxEndCallbacksSuppressed
) {
2560 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2561 /** @var Exception $e */
2562 $e = null; // first exception
2563 do { // callbacks may add callbacks :)
2564 $callbacks = array_merge(
2565 $this->mTrxIdleCallbacks
,
2566 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2568 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2569 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2570 foreach ( $callbacks as $callback ) {
2572 list( $phpCallback ) = $callback;
2573 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2574 call_user_func_array( $phpCallback, [ $trigger ] );
2576 $this->setFlag( DBO_TRX
); // restore automatic begin()
2578 $this->clearFlag( DBO_TRX
); // restore auto-commit
2580 } catch ( Exception
$ex ) {
2581 call_user_func( $this->errorLogger
, $ex );
2583 // Some callbacks may use startAtomic/endAtomic, so make sure
2584 // their transactions are ended so other callbacks don't fail
2585 if ( $this->trxLevel() ) {
2586 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2590 } while ( count( $this->mTrxIdleCallbacks
) );
2592 if ( $e instanceof Exception
) {
2593 throw $e; // re-throw any first exception
2598 * Actually run and consume any "on transaction pre-commit" callbacks.
2600 * This method should not be used outside of Database/LoadBalancer
2605 public function runOnTransactionPreCommitCallbacks() {
2606 $e = null; // first exception
2607 do { // callbacks may add callbacks :)
2608 $callbacks = $this->mTrxPreCommitCallbacks
;
2609 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2610 foreach ( $callbacks as $callback ) {
2612 list( $phpCallback ) = $callback;
2613 call_user_func( $phpCallback );
2614 } catch ( Exception
$ex ) {
2615 call_user_func( $this->errorLogger
, $ex );
2619 } while ( count( $this->mTrxPreCommitCallbacks
) );
2621 if ( $e instanceof Exception
) {
2622 throw $e; // re-throw any first exception
2627 * Actually run any "transaction listener" callbacks.
2629 * This method should not be used outside of Database/LoadBalancer
2631 * @param integer $trigger IDatabase::TRIGGER_* constant
2635 public function runTransactionListenerCallbacks( $trigger ) {
2636 if ( $this->mTrxEndCallbacksSuppressed
) {
2640 /** @var Exception $e */
2641 $e = null; // first exception
2643 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2645 $phpCallback( $trigger, $this );
2646 } catch ( Exception
$ex ) {
2647 call_user_func( $this->errorLogger
, $ex );
2652 if ( $e instanceof Exception
) {
2653 throw $e; // re-throw any first exception
2657 final public function startAtomic( $fname = __METHOD__
) {
2658 if ( !$this->mTrxLevel
) {
2659 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2660 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2661 // in all changes being in one transaction to keep requests transactional.
2662 if ( !$this->getFlag( DBO_TRX
) ) {
2663 $this->mTrxAutomaticAtomic
= true;
2667 $this->mTrxAtomicLevels
[] = $fname;
2670 final public function endAtomic( $fname = __METHOD__
) {
2671 if ( !$this->mTrxLevel
) {
2672 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2674 if ( !$this->mTrxAtomicLevels ||
2675 array_pop( $this->mTrxAtomicLevels
) !== $fname
2677 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2680 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2681 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2685 final public function doAtomicSection( $fname, callable
$callback ) {
2686 $this->startAtomic( $fname );
2688 $res = call_user_func_array( $callback, [ $this, $fname ] );
2689 } catch ( Exception
$e ) {
2690 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2693 $this->endAtomic( $fname );
2698 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2699 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2700 if ( $this->mTrxLevel
) {
2701 if ( $this->mTrxAtomicLevels
) {
2702 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2703 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2704 throw new DBUnexpectedError( $this, $msg );
2705 } elseif ( !$this->mTrxAutomatic
) {
2706 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2707 throw new DBUnexpectedError( $this, $msg );
2709 // @TODO: make this an exception at some point
2710 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2711 $this->queryLogger
->error( $msg );
2712 return; // join the main transaction set
2714 } elseif ( $this->getFlag( DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2715 // @TODO: make this an exception at some point
2716 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2717 $this->queryLogger
->error( $msg );
2718 return; // let any writes be in the main transaction
2721 // Avoid fatals if close() was called
2722 $this->assertOpen();
2724 $this->doBegin( $fname );
2725 $this->mTrxTimestamp
= microtime( true );
2726 $this->mTrxFname
= $fname;
2727 $this->mTrxDoneWrites
= false;
2728 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2729 $this->mTrxAutomaticAtomic
= false;
2730 $this->mTrxAtomicLevels
= [];
2731 $this->mTrxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2732 $this->mTrxWriteDuration
= 0.0;
2733 $this->mTrxWriteQueryCount
= 0;
2734 $this->mTrxWriteAdjDuration
= 0.0;
2735 $this->mTrxWriteAdjQueryCount
= 0;
2736 $this->mTrxWriteCallers
= [];
2737 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2738 // Get an estimate of the replica DB lag before then, treating estimate staleness
2739 // as lag itself just to be safe
2740 $status = $this->getApproximateLagStatus();
2741 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2745 * Issues the BEGIN command to the database server.
2747 * @see DatabaseBase::begin()
2748 * @param string $fname
2750 protected function doBegin( $fname ) {
2751 $this->query( 'BEGIN', $fname );
2752 $this->mTrxLevel
= 1;
2755 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2756 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2757 // There are still atomic sections open. This cannot be ignored
2758 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2759 throw new DBUnexpectedError(
2761 "$fname: Got COMMIT while atomic sections $levels are still open."
2765 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2766 if ( !$this->mTrxLevel
) {
2767 return; // nothing to do
2768 } elseif ( !$this->mTrxAutomatic
) {
2769 throw new DBUnexpectedError(
2771 "$fname: Flushing an explicit transaction, getting out of sync."
2775 if ( !$this->mTrxLevel
) {
2776 $this->queryLogger
->error( "$fname: No transaction to commit, something got out of sync." );
2777 return; // nothing to do
2778 } elseif ( $this->mTrxAutomatic
) {
2779 // @TODO: make this an exception at some point
2780 $msg = "$fname: Explicit commit of implicit transaction.";
2781 $this->queryLogger
->error( $msg );
2782 return; // wait for the main transaction set commit round
2786 // Avoid fatals if close() was called
2787 $this->assertOpen();
2789 $this->runOnTransactionPreCommitCallbacks();
2790 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2791 $this->doCommit( $fname );
2792 if ( $this->mTrxDoneWrites
) {
2793 $this->mDoneWrites
= microtime( true );
2794 $this->trxProfiler
->transactionWritingOut(
2795 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2798 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2799 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
2803 * Issues the COMMIT command to the database server.
2805 * @see DatabaseBase::commit()
2806 * @param string $fname
2808 protected function doCommit( $fname ) {
2809 if ( $this->mTrxLevel
) {
2810 $this->query( 'COMMIT', $fname );
2811 $this->mTrxLevel
= 0;
2815 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2816 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2817 if ( !$this->mTrxLevel
) {
2818 return; // nothing to do
2821 if ( !$this->mTrxLevel
) {
2822 $this->queryLogger
->error(
2823 "$fname: No transaction to rollback, something got out of sync." );
2824 return; // nothing to do
2825 } elseif ( $this->getFlag( DBO_TRX
) ) {
2826 throw new DBUnexpectedError(
2828 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2833 // Avoid fatals if close() was called
2834 $this->assertOpen();
2836 $this->doRollback( $fname );
2837 $this->mTrxAtomicLevels
= [];
2838 if ( $this->mTrxDoneWrites
) {
2839 $this->trxProfiler
->transactionWritingOut(
2840 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
2843 $this->mTrxIdleCallbacks
= []; // clear
2844 $this->mTrxPreCommitCallbacks
= []; // clear
2845 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
2846 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
2850 * Issues the ROLLBACK command to the database server.
2852 * @see DatabaseBase::rollback()
2853 * @param string $fname
2855 protected function doRollback( $fname ) {
2856 if ( $this->mTrxLevel
) {
2857 # Disconnects cause rollback anyway, so ignore those errors
2858 $ignoreErrors = true;
2859 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
2860 $this->mTrxLevel
= 0;
2864 public function flushSnapshot( $fname = __METHOD__
) {
2865 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
2866 // This only flushes transactions to clear snapshots, not to write data
2867 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
2868 throw new DBUnexpectedError(
2870 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
2874 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2877 public function explicitTrxActive() {
2878 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
2882 * Creates a new table with structure copied from existing table
2883 * Note that unlike most database abstraction functions, this function does not
2884 * automatically append database prefix, because it works at a lower
2885 * abstraction level.
2886 * The table names passed to this function shall not be quoted (this
2887 * function calls addIdentifierQuotes when needed).
2889 * @param string $oldName Name of table whose structure should be copied
2890 * @param string $newName Name of table to be created
2891 * @param bool $temporary Whether the new table should be temporary
2892 * @param string $fname Calling function name
2893 * @throws RuntimeException
2894 * @return bool True if operation was successful
2896 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
2899 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2902 function listTables( $prefix = null, $fname = __METHOD__
) {
2903 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2907 * Reset the views process cache set by listViews()
2910 final public function clearViewsCache() {
2911 $this->allViews
= null;
2915 * Lists all the VIEWs in the database
2917 * For caching purposes the list of all views should be stored in
2918 * $this->allViews. The process cache can be cleared with clearViewsCache()
2920 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
2921 * @param string $fname Name of calling function
2922 * @throws RuntimeException
2926 public function listViews( $prefix = null, $fname = __METHOD__
) {
2927 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2931 * Differentiates between a TABLE and a VIEW
2933 * @param string $name Name of the database-structure to test.
2934 * @throws RuntimeException
2938 public function isView( $name ) {
2939 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2942 public function timestamp( $ts = 0 ) {
2943 $t = new ConvertableTimestamp( $ts );
2944 // Let errors bubble up to avoid putting garbage in the DB
2945 return $t->getTimestamp( TS_MW
);
2948 public function timestampOrNull( $ts = null ) {
2949 if ( is_null( $ts ) ) {
2952 return $this->timestamp( $ts );
2957 * Take the result from a query, and wrap it in a ResultWrapper if
2958 * necessary. Boolean values are passed through as is, to indicate success
2959 * of write queries or failure.
2961 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2962 * resource, and it was necessary to call this function to convert it to
2963 * a wrapper. Nowadays, raw database objects are never exposed to external
2964 * callers, so this is unnecessary in external code.
2966 * @param bool|ResultWrapper|resource|object $result
2967 * @return bool|ResultWrapper
2969 protected function resultObject( $result ) {
2972 } elseif ( $result instanceof ResultWrapper
) {
2974 } elseif ( $result === true ) {
2975 // Successful write query
2978 return new ResultWrapper( $this, $result );
2982 public function ping( &$rtt = null ) {
2983 // Avoid hitting the server if it was hit recently
2984 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
2985 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
2986 $rtt = $this->mRTTEstimate
;
2987 return true; // don't care about $rtt
2991 // This will reconnect if possible or return false if not
2992 $this->clearFlag( DBO_TRX
, self
::REMEMBER_PRIOR
);
2993 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
2994 $this->restoreFlags( self
::RESTORE_PRIOR
);
2997 $rtt = $this->mRTTEstimate
;
3006 protected function reconnect() {
3007 $this->closeConnection();
3008 $this->mOpened
= false;
3009 $this->mConn
= false;
3011 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3012 $this->lastPing
= microtime( true );
3014 } catch ( DBConnectionError
$e ) {
3021 public function getSessionLagStatus() {
3022 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3026 * Get the replica DB lag when the current transaction started
3028 * This is useful when transactions might use snapshot isolation
3029 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3030 * is this lag plus transaction duration. If they don't, it is still
3031 * safe to be pessimistic. This returns null if there is no transaction.
3033 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3036 public function getTransactionLagStatus() {
3037 return $this->mTrxLevel
3038 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3043 * Get a replica DB lag estimate for this server
3045 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3048 public function getApproximateLagStatus() {
3050 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3051 'since' => microtime( true )
3056 * Merge the result of getSessionLagStatus() for several DBs
3057 * using the most pessimistic values to estimate the lag of
3058 * any data derived from them in combination
3060 * This is information is useful for caching modules
3062 * @see WANObjectCache::set()
3063 * @see WANObjectCache::getWithSetCallback()
3065 * @param IDatabase $db1
3066 * @param IDatabase ...
3067 * @return array Map of values:
3068 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3069 * - since: oldest UNIX timestamp of any of the DB lag estimates
3070 * - pending: whether any of the DBs have uncommitted changes
3073 public static function getCacheSetOptions( IDatabase
$db1 ) {
3074 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3075 foreach ( func_get_args() as $db ) {
3076 /** @var IDatabase $db */
3077 $status = $db->getSessionLagStatus();
3078 if ( $status['lag'] === false ) {
3079 $res['lag'] = false;
3080 } elseif ( $res['lag'] !== false ) {
3081 $res['lag'] = max( $res['lag'], $status['lag'] );
3083 $res['since'] = min( $res['since'], $status['since'] );
3084 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3090 public function getLag() {
3094 function maxListLen() {
3098 public function encodeBlob( $b ) {
3102 public function decodeBlob( $b ) {
3103 if ( $b instanceof Blob
) {
3109 public function setSessionOptions( array $options ) {
3113 * Read and execute SQL commands from a file.
3115 * Returns true on success, error string or exception on failure (depending
3116 * on object's error ignore settings).
3118 * @param string $filename File name to open
3119 * @param bool|callable $lineCallback Optional function called before reading each line
3120 * @param bool|callable $resultCallback Optional function called for each MySQL result
3121 * @param bool|string $fname Calling function name or false if name should be
3122 * generated dynamically using $filename
3123 * @param bool|callable $inputCallback Optional function called for each
3124 * complete line sent
3125 * @return bool|string
3128 public function sourceFile(
3129 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3131 MediaWiki\
suppressWarnings();
3132 $fp = fopen( $filename, 'r' );
3133 MediaWiki\restoreWarnings
();
3135 if ( false === $fp ) {
3136 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3140 $fname = __METHOD__
. "( $filename )";
3144 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3145 } catch ( Exception
$e ) {
3155 public function setSchemaVars( $vars ) {
3156 $this->mSchemaVars
= $vars;
3160 * Read and execute commands from an open file handle.
3162 * Returns true on success, error string or exception on failure (depending
3163 * on object's error ignore settings).
3165 * @param resource $fp File handle
3166 * @param bool|callable $lineCallback Optional function called before reading each query
3167 * @param bool|callable $resultCallback Optional function called for each MySQL result
3168 * @param string $fname Calling function name
3169 * @param bool|callable $inputCallback Optional function called for each complete query sent
3170 * @return bool|string
3172 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3173 $fname = __METHOD__
, $inputCallback = false
3177 while ( !feof( $fp ) ) {
3178 if ( $lineCallback ) {
3179 call_user_func( $lineCallback );
3182 $line = trim( fgets( $fp ) );
3184 if ( $line == '' ) {
3188 if ( '-' == $line[0] && '-' == $line[1] ) {
3196 $done = $this->streamStatementEnd( $cmd, $line );
3200 if ( $done ||
feof( $fp ) ) {
3201 $cmd = $this->replaceVars( $cmd );
3203 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3204 $res = $this->query( $cmd, $fname );
3206 if ( $resultCallback ) {
3207 call_user_func( $resultCallback, $res, $this );
3210 if ( false === $res ) {
3211 $err = $this->lastError();
3213 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3224 * Called by sourceStream() to check if we've reached a statement end
3226 * @param string $sql SQL assembled so far
3227 * @param string $newLine New line about to be added to $sql
3228 * @return bool Whether $newLine contains end of the statement
3230 public function streamStatementEnd( &$sql, &$newLine ) {
3231 if ( $this->delimiter
) {
3233 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3234 if ( $newLine != $prev ) {
3243 * Database independent variable replacement. Replaces a set of variables
3244 * in an SQL statement with their contents as given by $this->getSchemaVars().
3246 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3248 * - '{$var}' should be used for text and is passed through the database's
3250 * - `{$var}` should be used for identifiers (e.g. table and database names).
3251 * It is passed through the database's addIdentifierQuotes method which
3252 * can be overridden if the database uses something other than backticks.
3253 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3254 * database's tableName method.
3255 * - / *i* / passes the name that follows through the database's indexName method.
3256 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3257 * its use should be avoided. In 1.24 and older, string encoding was applied.
3259 * @param string $ins SQL statement to replace variables in
3260 * @return string The new SQL statement with variables replaced
3262 protected function replaceVars( $ins ) {
3263 $vars = $this->getSchemaVars();
3264 return preg_replace_callback(
3266 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3267 \'\{\$ (\w+) }\' | # 3. addQuotes
3268 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3269 /\*\$ (\w+) \*/ # 5. leave unencoded
3271 function ( $m ) use ( $vars ) {
3272 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3273 // check for both nonexistent keys *and* the empty string.
3274 if ( isset( $m[1] ) && $m[1] !== '' ) {
3275 if ( $m[1] === 'i' ) {
3276 return $this->indexName( $m[2] );
3278 return $this->tableName( $m[2] );
3280 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3281 return $this->addQuotes( $vars[$m[3]] );
3282 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3283 return $this->addIdentifierQuotes( $vars[$m[4]] );
3284 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3285 return $vars[$m[5]];
3295 * Get schema variables. If none have been set via setSchemaVars(), then
3296 * use some defaults from the current object.
3300 protected function getSchemaVars() {
3301 if ( $this->mSchemaVars
) {
3302 return $this->mSchemaVars
;
3304 return $this->getDefaultSchemaVars();
3309 * Get schema variables to use if none have been set via setSchemaVars().
3311 * Override this in derived classes to provide variables for tables.sql
3312 * and SQL patch files.
3316 protected function getDefaultSchemaVars() {
3320 public function lockIsFree( $lockName, $method ) {
3324 public function lock( $lockName, $method, $timeout = 5 ) {
3325 $this->mNamedLocksHeld
[$lockName] = 1;
3330 public function unlock( $lockName, $method ) {
3331 unset( $this->mNamedLocksHeld
[$lockName] );
3336 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3337 if ( $this->writesOrCallbacksPending() ) {
3338 // This only flushes transactions to clear snapshots, not to write data
3339 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3340 throw new DBUnexpectedError(
3342 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
3346 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3350 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3351 if ( $this->trxLevel() ) {
3352 // There is a good chance an exception was thrown, causing any early return
3353 // from the caller. Let any error handler get a chance to issue rollback().
3354 // If there isn't one, let the error bubble up and trigger server-side rollback.
3355 $this->onTransactionResolution(
3356 function () use ( $lockKey, $fname ) {
3357 $this->unlock( $lockKey, $fname );
3362 $this->unlock( $lockKey, $fname );
3366 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3371 public function namedLocksEnqueue() {
3376 * Lock specific tables
3378 * @param array $read Array of tables to lock for read access
3379 * @param array $write Array of tables to lock for write access
3380 * @param string $method Name of caller
3381 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3384 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3389 * Unlock specific tables
3391 * @param string $method The caller
3394 public function unlockTables( $method ) {
3400 * @param string $tableName
3401 * @param string $fName
3402 * @return bool|ResultWrapper
3405 public function dropTable( $tableName, $fName = __METHOD__
) {
3406 if ( !$this->tableExists( $tableName, $fName ) ) {
3409 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3411 return $this->query( $sql, $fName );
3414 public function getInfinity() {
3418 public function encodeExpiry( $expiry ) {
3419 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3420 ?
$this->getInfinity()
3421 : $this->timestamp( $expiry );
3424 public function decodeExpiry( $expiry, $format = TS_MW
) {
3425 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3430 $t = new ConvertableTimestamp( $expiry );
3432 return $t->getTimestamp( $format );
3433 } catch ( TimestampException
$e ) {
3438 public function setBigSelects( $value = true ) {
3442 public function isReadOnly() {
3443 return ( $this->getReadOnlyReason() !== false );
3447 * @return string|bool Reason this DB is read-only or false if it is not
3449 protected function getReadOnlyReason() {
3450 $reason = $this->getLBInfo( 'readOnlyReason' );
3452 return is_string( $reason ) ?
$reason : false;
3455 public function setTableAliases( array $aliases ) {
3456 $this->tableAliases
= $aliases;
3463 public function __toString() {
3464 return (string)$this->mConn
;
3468 * Called by serialize. Throw an exception when DB connection is serialized.
3469 * This causes problems on some database engines because the connection is
3470 * not restored on unserialize.
3472 public function __sleep() {
3473 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3474 'the connection is not restored on wakeup.' );
3478 * Run a few simple sanity checks
3480 public function __destruct() {
3481 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3482 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3485 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3486 if ( $danglingWriters ) {
3487 $fnames = implode( ', ', $danglingWriters );
3488 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );