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'], 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, 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, LIST_SET
);
1472 if ( $conds !== [] && $conds !== '*' ) {
1473 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1476 return $this->query( $sql, $fname );
1479 public function makeList( $a, $mode = 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 == LIST_AND
) {
1491 } elseif ( $mode == LIST_OR
) {
1500 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1501 $list .= "($value)";
1502 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1504 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1505 // Remove null from array to be handled separately if found
1506 $includeNull = false;
1507 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1508 $includeNull = true;
1509 unset( $value[$nullKey] );
1511 if ( count( $value ) == 0 && !$includeNull ) {
1512 throw new InvalidArgumentException( __METHOD__
. ": empty input for field $field" );
1513 } elseif ( count( $value ) == 0 ) {
1514 // only check if $field is null
1515 $list .= "$field IS NULL";
1517 // IN clause contains at least one valid element
1518 if ( $includeNull ) {
1519 // Group subconditions to ensure correct precedence
1522 if ( count( $value ) == 1 ) {
1523 // Special-case single values, as IN isn't terribly efficient
1524 // Don't necessarily assume the single key is 0; we don't
1525 // enforce linear numeric ordering on other arrays here.
1526 $value = array_values( $value )[0];
1527 $list .= $field . " = " . $this->addQuotes( $value );
1529 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1531 // if null present in array, append IS NULL
1532 if ( $includeNull ) {
1533 $list .= " OR $field IS NULL)";
1536 } elseif ( $value === null ) {
1537 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1538 $list .= "$field IS ";
1539 } elseif ( $mode == LIST_SET
) {
1540 $list .= "$field = ";
1544 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1545 $list .= "$field = ";
1547 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1554 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1557 foreach ( $data as $base => $sub ) {
1558 if ( count( $sub ) ) {
1559 $conds[] = $this->makeList(
1560 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1566 return $this->makeList( $conds, LIST_OR
);
1568 // Nothing to search for...
1574 * Return aggregated value alias
1576 * @param array $valuedata
1577 * @param string $valuename
1581 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1585 public function bitNot( $field ) {
1589 public function bitAnd( $fieldLeft, $fieldRight ) {
1590 return "($fieldLeft & $fieldRight)";
1593 public function bitOr( $fieldLeft, $fieldRight ) {
1594 return "($fieldLeft | $fieldRight)";
1597 public function buildConcat( $stringList ) {
1598 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1601 public function buildGroupConcatField(
1602 $delim, $table, $field, $conds = '', $join_conds = []
1604 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1606 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1610 * @param string $field Field or column to cast
1614 public function buildStringCast( $field ) {
1618 public function selectDB( $db ) {
1619 # Stub. Shouldn't cause serious problems if it's not overridden, but
1620 # if your database engine supports a concept similar to MySQL's
1621 # databases you may as well.
1622 $this->mDBname
= $db;
1627 public function getDBname() {
1628 return $this->mDBname
;
1631 public function getServer() {
1632 return $this->mServer
;
1636 * Format a table name ready for use in constructing an SQL query
1638 * This does two important things: it quotes the table names to clean them up,
1639 * and it adds a table prefix if only given a table name with no quotes.
1641 * All functions of this object which require a table name call this function
1642 * themselves. Pass the canonical name to such functions. This is only needed
1643 * when calling query() directly.
1645 * @note This function does not sanitize user input. It is not safe to use
1646 * this function to escape user input.
1647 * @param string $name Database table name
1648 * @param string $format One of:
1649 * quoted - Automatically pass the table name through addIdentifierQuotes()
1650 * so that it can be used in a query.
1651 * raw - Do not add identifier quotes to the table name
1652 * @return string Full database name
1654 public function tableName( $name, $format = 'quoted' ) {
1655 # Skip the entire process when we have a string quoted on both ends.
1656 # Note that we check the end so that we will still quote any use of
1657 # use of `database`.table. But won't break things if someone wants
1658 # to query a database table with a dot in the name.
1659 if ( $this->isQuotedIdentifier( $name ) ) {
1663 # Lets test for any bits of text that should never show up in a table
1664 # name. Basically anything like JOIN or ON which are actually part of
1665 # SQL queries, but may end up inside of the table value to combine
1666 # sql. Such as how the API is doing.
1667 # Note that we use a whitespace test rather than a \b test to avoid
1668 # any remote case where a word like on may be inside of a table name
1669 # surrounded by symbols which may be considered word breaks.
1670 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1674 # Split database and table into proper variables.
1675 # We reverse the explode so that database.table and table both output
1676 # the correct table.
1677 $dbDetails = explode( '.', $name, 3 );
1678 if ( count( $dbDetails ) == 3 ) {
1679 list( $database, $schema, $table ) = $dbDetails;
1680 # We don't want any prefix added in this case
1682 } elseif ( count( $dbDetails ) == 2 ) {
1683 list( $database, $table ) = $dbDetails;
1684 # We don't want any prefix added in this case
1685 # In dbs that support it, $database may actually be the schema
1686 # but that doesn't affect any of the functionality here
1690 list( $table ) = $dbDetails;
1691 if ( isset( $this->tableAliases
[$table] ) ) {
1692 $database = $this->tableAliases
[$table]['dbname'];
1693 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1694 ?
$this->tableAliases
[$table]['schema']
1696 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1697 ?
$this->tableAliases
[$table]['prefix']
1698 : $this->mTablePrefix
;
1701 $schema = $this->mSchema
; # Default schema
1702 $prefix = $this->mTablePrefix
; # Default prefix
1706 # Quote $table and apply the prefix if not quoted.
1707 # $tableName might be empty if this is called from Database::replaceVars()
1708 $tableName = "{$prefix}{$table}";
1709 if ( $format == 'quoted'
1710 && !$this->isQuotedIdentifier( $tableName ) && $tableName !== ''
1712 $tableName = $this->addIdentifierQuotes( $tableName );
1715 # Quote $schema and merge it with the table name if needed
1716 if ( strlen( $schema ) ) {
1717 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1718 $schema = $this->addIdentifierQuotes( $schema );
1720 $tableName = $schema . '.' . $tableName;
1723 # Quote $database and merge it with the table name if needed
1724 if ( $database !== '' ) {
1725 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1726 $database = $this->addIdentifierQuotes( $database );
1728 $tableName = $database . '.' . $tableName;
1735 * Fetch a number of table names into an array
1736 * This is handy when you need to construct SQL for joins
1739 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1740 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1741 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1745 public function tableNames() {
1746 $inArray = func_get_args();
1749 foreach ( $inArray as $name ) {
1750 $retVal[$name] = $this->tableName( $name );
1757 * Fetch a number of table names into an zero-indexed numerical array
1758 * This is handy when you need to construct SQL for joins
1761 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1762 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1763 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1767 public function tableNamesN() {
1768 $inArray = func_get_args();
1771 foreach ( $inArray as $name ) {
1772 $retVal[] = $this->tableName( $name );
1779 * Get an aliased table name
1780 * e.g. tableName AS newTableName
1782 * @param string $name Table name, see tableName()
1783 * @param string|bool $alias Alias (optional)
1784 * @return string SQL name for aliased table. Will not alias a table to its own name
1786 public function tableNameWithAlias( $name, $alias = false ) {
1787 if ( !$alias ||
$alias == $name ) {
1788 return $this->tableName( $name );
1790 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1795 * Gets an array of aliased table names
1797 * @param array $tables [ [alias] => table ]
1798 * @return string[] See tableNameWithAlias()
1800 public function tableNamesWithAlias( $tables ) {
1802 foreach ( $tables as $alias => $table ) {
1803 if ( is_numeric( $alias ) ) {
1806 $retval[] = $this->tableNameWithAlias( $table, $alias );
1813 * Get an aliased field name
1814 * e.g. fieldName AS newFieldName
1816 * @param string $name Field name
1817 * @param string|bool $alias Alias (optional)
1818 * @return string SQL name for aliased field. Will not alias a field to its own name
1820 public function fieldNameWithAlias( $name, $alias = false ) {
1821 if ( !$alias ||
(string)$alias === (string)$name ) {
1824 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1829 * Gets an array of aliased field names
1831 * @param array $fields [ [alias] => field ]
1832 * @return string[] See fieldNameWithAlias()
1834 public function fieldNamesWithAlias( $fields ) {
1836 foreach ( $fields as $alias => $field ) {
1837 if ( is_numeric( $alias ) ) {
1840 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1847 * Get the aliased table name clause for a FROM clause
1848 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
1850 * @param array $tables ( [alias] => table )
1851 * @param array $use_index Same as for select()
1852 * @param array $ignore_index Same as for select()
1853 * @param array $join_conds Same as for select()
1856 protected function tableNamesWithIndexClauseOrJOIN(
1857 $tables, $use_index = [], $ignore_index = [], $join_conds = []
1861 $use_index = (array)$use_index;
1862 $ignore_index = (array)$ignore_index;
1863 $join_conds = (array)$join_conds;
1865 foreach ( $tables as $alias => $table ) {
1866 if ( !is_string( $alias ) ) {
1867 // No alias? Set it equal to the table name
1870 // Is there a JOIN clause for this table?
1871 if ( isset( $join_conds[$alias] ) ) {
1872 list( $joinType, $conds ) = $join_conds[$alias];
1873 $tableClause = $joinType;
1874 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1875 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1876 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1878 $tableClause .= ' ' . $use;
1881 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
1882 $ignore = $this->ignoreIndexClause( implode( ',', (array)$ignore_index[$alias] ) );
1883 if ( $ignore != '' ) {
1884 $tableClause .= ' ' . $ignore;
1887 $on = $this->makeList( (array)$conds, LIST_AND
);
1889 $tableClause .= ' ON (' . $on . ')';
1892 $retJOIN[] = $tableClause;
1893 } elseif ( isset( $use_index[$alias] ) ) {
1894 // Is there an INDEX clause for this table?
1895 $tableClause = $this->tableNameWithAlias( $table, $alias );
1896 $tableClause .= ' ' . $this->useIndexClause(
1897 implode( ',', (array)$use_index[$alias] )
1900 $ret[] = $tableClause;
1901 } elseif ( isset( $ignore_index[$alias] ) ) {
1902 // Is there an INDEX clause for this table?
1903 $tableClause = $this->tableNameWithAlias( $table, $alias );
1904 $tableClause .= ' ' . $this->ignoreIndexClause(
1905 implode( ',', (array)$ignore_index[$alias] )
1908 $ret[] = $tableClause;
1910 $tableClause = $this->tableNameWithAlias( $table, $alias );
1912 $ret[] = $tableClause;
1916 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1917 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1918 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1920 // Compile our final table clause
1921 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
1925 * Get the name of an index in a given table.
1927 * @param string $index
1930 protected function indexName( $index ) {
1931 // Backwards-compatibility hack
1933 'ar_usertext_timestamp' => 'usertext_timestamp',
1934 'un_user_id' => 'user_id',
1935 'un_user_ip' => 'user_ip',
1938 if ( isset( $renamed[$index] ) ) {
1939 return $renamed[$index];
1945 public function addQuotes( $s ) {
1946 if ( $s instanceof Blob
) {
1949 if ( $s === null ) {
1952 # This will also quote numeric values. This should be harmless,
1953 # and protects against weird problems that occur when they really
1954 # _are_ strings such as article titles and string->number->string
1955 # conversion is not 1:1.
1956 return "'" . $this->strencode( $s ) . "'";
1961 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1962 * MySQL uses `backticks` while basically everything else uses double quotes.
1963 * Since MySQL is the odd one out here the double quotes are our generic
1964 * and we implement backticks in DatabaseMysql.
1969 public function addIdentifierQuotes( $s ) {
1970 return '"' . str_replace( '"', '""', $s ) . '"';
1974 * Returns if the given identifier looks quoted or not according to
1975 * the database convention for quoting identifiers .
1977 * @note Do not use this to determine if untrusted input is safe.
1978 * A malicious user can trick this function.
1979 * @param string $name
1982 public function isQuotedIdentifier( $name ) {
1983 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
1990 protected function escapeLikeInternal( $s ) {
1991 return addcslashes( $s, '\%_' );
1994 public function buildLike() {
1995 $params = func_get_args();
1997 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1998 $params = $params[0];
2003 foreach ( $params as $value ) {
2004 if ( $value instanceof LikeMatch
) {
2005 $s .= $value->toString();
2007 $s .= $this->escapeLikeInternal( $value );
2011 return " LIKE {$this->addQuotes( $s )} ";
2014 public function anyChar() {
2015 return new LikeMatch( '_' );
2018 public function anyString() {
2019 return new LikeMatch( '%' );
2022 public function nextSequenceValue( $seqName ) {
2027 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2028 * is only needed because a) MySQL must be as efficient as possible due to
2029 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2030 * which index to pick. Anyway, other databases might have different
2031 * indexes on a given table. So don't bother overriding this unless you're
2033 * @param string $index
2036 public function useIndexClause( $index ) {
2041 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2042 * is only needed because a) MySQL must be as efficient as possible due to
2043 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2044 * which index to pick. Anyway, other databases might have different
2045 * indexes on a given table. So don't bother overriding this unless you're
2047 * @param string $index
2050 public function ignoreIndexClause( $index ) {
2054 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2055 $quotedTable = $this->tableName( $table );
2057 if ( count( $rows ) == 0 ) {
2062 if ( !is_array( reset( $rows ) ) ) {
2066 // @FXIME: this is not atomic, but a trx would break affectedRows()
2067 foreach ( $rows as $row ) {
2068 # Delete rows which collide
2069 if ( $uniqueIndexes ) {
2070 $sql = "DELETE FROM $quotedTable WHERE ";
2072 foreach ( $uniqueIndexes as $index ) {
2079 if ( is_array( $index ) ) {
2081 foreach ( $index as $col ) {
2087 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2090 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2094 $this->query( $sql, $fname );
2097 # Now insert the row
2098 $this->insert( $table, $row, $fname );
2103 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2106 * @param string $table Table name
2107 * @param array|string $rows Row(s) to insert
2108 * @param string $fname Caller function name
2110 * @return ResultWrapper
2112 protected function nativeReplace( $table, $rows, $fname ) {
2113 $table = $this->tableName( $table );
2116 if ( !is_array( reset( $rows ) ) ) {
2120 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2123 foreach ( $rows as $row ) {
2130 $sql .= '(' . $this->makeList( $row ) . ')';
2133 return $this->query( $sql, $fname );
2136 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2139 if ( !count( $rows ) ) {
2140 return true; // nothing to do
2143 if ( !is_array( reset( $rows ) ) ) {
2147 if ( count( $uniqueIndexes ) ) {
2148 $clauses = []; // list WHERE clauses that each identify a single row
2149 foreach ( $rows as $row ) {
2150 foreach ( $uniqueIndexes as $index ) {
2151 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2152 $rowKey = []; // unique key to this row
2153 foreach ( $index as $column ) {
2154 $rowKey[$column] = $row[$column];
2156 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2159 $where = [ $this->makeList( $clauses, LIST_OR
) ];
2164 $useTrx = !$this->mTrxLevel
;
2166 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2169 # Update any existing conflicting row(s)
2170 if ( $where !== false ) {
2171 $ok = $this->update( $table, $set, $where, $fname );
2175 # Now insert any non-conflicting row(s)
2176 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2177 } catch ( Exception
$e ) {
2179 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2184 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2190 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2194 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2197 $delTable = $this->tableName( $delTable );
2198 $joinTable = $this->tableName( $joinTable );
2199 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2200 if ( $conds != '*' ) {
2201 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2205 $this->query( $sql, $fname );
2209 * Returns the size of a text field, or -1 for "unlimited"
2211 * @param string $table
2212 * @param string $field
2215 public function textFieldSize( $table, $field ) {
2216 $table = $this->tableName( $table );
2217 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2218 $res = $this->query( $sql, __METHOD__
);
2219 $row = $this->fetchObject( $res );
2223 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2232 public function delete( $table, $conds, $fname = __METHOD__
) {
2234 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2237 $table = $this->tableName( $table );
2238 $sql = "DELETE FROM $table";
2240 if ( $conds != '*' ) {
2241 if ( is_array( $conds ) ) {
2242 $conds = $this->makeList( $conds, LIST_AND
);
2244 $sql .= ' WHERE ' . $conds;
2247 return $this->query( $sql, $fname );
2250 public function insertSelect(
2251 $destTable, $srcTable, $varMap, $conds,
2252 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2254 if ( $this->cliMode
) {
2255 // For massive migrations with downtime, we don't want to select everything
2256 // into memory and OOM, so do all this native on the server side if possible.
2257 return $this->nativeInsertSelect(
2268 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2269 // on only the master (without needing row-based-replication). It also makes it easy to
2270 // know how big the INSERT is going to be.
2272 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2273 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2275 $selectOptions[] = 'FOR UPDATE';
2276 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2282 foreach ( $res as $row ) {
2283 $rows[] = (array)$row;
2286 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2289 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2290 $fname = __METHOD__
,
2291 $insertOptions = [], $selectOptions = []
2293 $destTable = $this->tableName( $destTable );
2295 if ( !is_array( $insertOptions ) ) {
2296 $insertOptions = [ $insertOptions ];
2299 $insertOptions = $this->makeInsertOptions( $insertOptions );
2301 if ( !is_array( $selectOptions ) ) {
2302 $selectOptions = [ $selectOptions ];
2305 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2308 if ( is_array( $srcTable ) ) {
2309 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2311 $srcTable = $this->tableName( $srcTable );
2314 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2315 " SELECT $startOpts " . implode( ',', $varMap ) .
2316 " FROM $srcTable $useIndex $ignoreIndex ";
2318 if ( $conds != '*' ) {
2319 if ( is_array( $conds ) ) {
2320 $conds = $this->makeList( $conds, LIST_AND
);
2322 $sql .= " WHERE $conds";
2325 $sql .= " $tailOpts";
2327 return $this->query( $sql, $fname );
2331 * Construct a LIMIT query with optional offset. This is used for query
2332 * pages. The SQL should be adjusted so that only the first $limit rows
2333 * are returned. If $offset is provided as well, then the first $offset
2334 * rows should be discarded, and the next $limit rows should be returned.
2335 * If the result of the query is not ordered, then the rows to be returned
2336 * are theoretically arbitrary.
2338 * $sql is expected to be a SELECT, if that makes a difference.
2340 * The version provided by default works in MySQL and SQLite. It will very
2341 * likely need to be overridden for most other DBMSes.
2343 * @param string $sql SQL query we will append the limit too
2344 * @param int $limit The SQL limit
2345 * @param int|bool $offset The SQL offset (default false)
2346 * @throws DBUnexpectedError
2349 public function limitResult( $sql, $limit, $offset = false ) {
2350 if ( !is_numeric( $limit ) ) {
2351 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2354 return "$sql LIMIT "
2355 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2359 public function unionSupportsOrderAndLimit() {
2360 return true; // True for almost every DB supported
2363 public function unionQueries( $sqls, $all ) {
2364 $glue = $all ?
') UNION ALL (' : ') UNION (';
2366 return '(' . implode( $glue, $sqls ) . ')';
2369 public function conditional( $cond, $trueVal, $falseVal ) {
2370 if ( is_array( $cond ) ) {
2371 $cond = $this->makeList( $cond, LIST_AND
);
2374 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2377 public function strreplace( $orig, $old, $new ) {
2378 return "REPLACE({$orig}, {$old}, {$new})";
2381 public function getServerUptime() {
2385 public function wasDeadlock() {
2389 public function wasLockTimeout() {
2393 public function wasErrorReissuable() {
2397 public function wasReadOnlyError() {
2402 * Determines if the given query error was a connection drop
2405 * @param integer|string $errno
2408 public function wasConnectionError( $errno ) {
2413 * Perform a deadlock-prone transaction.
2415 * This function invokes a callback function to perform a set of write
2416 * queries. If a deadlock occurs during the processing, the transaction
2417 * will be rolled back and the callback function will be called again.
2419 * Avoid using this method outside of Job or Maintenance classes.
2422 * $dbw->deadlockLoop( callback, ... );
2424 * Extra arguments are passed through to the specified callback function.
2425 * This method requires that no transactions are already active to avoid
2426 * causing premature commits or exceptions.
2428 * Returns whatever the callback function returned on its successful,
2429 * iteration, or false on error, for example if the retry limit was
2433 * @throws DBUnexpectedError
2436 public function deadlockLoop() {
2437 $args = func_get_args();
2438 $function = array_shift( $args );
2439 $tries = self
::DEADLOCK_TRIES
;
2441 $this->begin( __METHOD__
);
2444 /** @var Exception $e */
2448 $retVal = call_user_func_array( $function, $args );
2450 } catch ( DBQueryError
$e ) {
2451 if ( $this->wasDeadlock() ) {
2452 // Retry after a randomized delay
2453 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2455 // Throw the error back up
2459 } while ( --$tries > 0 );
2461 if ( $tries <= 0 ) {
2462 // Too many deadlocks; give up
2463 $this->rollback( __METHOD__
);
2466 $this->commit( __METHOD__
);
2472 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2473 # Real waits are implemented in the subclass.
2477 public function getSlavePos() {
2482 public function getMasterPos() {
2487 public function serverIsReadOnly() {
2491 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2492 if ( !$this->mTrxLevel
) {
2493 throw new DBUnexpectedError( $this, "No transaction is active." );
2495 $this->mTrxEndCallbacks
[] = [ $callback, $fname ];
2498 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2499 $this->mTrxIdleCallbacks
[] = [ $callback, $fname ];
2500 if ( !$this->mTrxLevel
) {
2501 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2505 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2506 if ( $this->mTrxLevel
) {
2507 $this->mTrxPreCommitCallbacks
[] = [ $callback, $fname ];
2509 // If no transaction is active, then make one for this callback
2510 $this->startAtomic( __METHOD__
);
2512 call_user_func( $callback );
2513 $this->endAtomic( __METHOD__
);
2514 } catch ( Exception
$e ) {
2515 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2521 final public function setTransactionListener( $name, callable
$callback = null ) {
2523 $this->mTrxRecurringCallbacks
[$name] = $callback;
2525 unset( $this->mTrxRecurringCallbacks
[$name] );
2530 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2532 * This method should not be used outside of Database/LoadBalancer
2534 * @param bool $suppress
2537 final public function setTrxEndCallbackSuppression( $suppress ) {
2538 $this->mTrxEndCallbacksSuppressed
= $suppress;
2542 * Actually run and consume any "on transaction idle/resolution" callbacks.
2544 * This method should not be used outside of Database/LoadBalancer
2546 * @param integer $trigger IDatabase::TRIGGER_* constant
2550 public function runOnTransactionIdleCallbacks( $trigger ) {
2551 if ( $this->mTrxEndCallbacksSuppressed
) {
2555 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2556 /** @var Exception $e */
2557 $e = null; // first exception
2558 do { // callbacks may add callbacks :)
2559 $callbacks = array_merge(
2560 $this->mTrxIdleCallbacks
,
2561 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2563 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2564 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2565 foreach ( $callbacks as $callback ) {
2567 list( $phpCallback ) = $callback;
2568 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2569 call_user_func_array( $phpCallback, [ $trigger ] );
2571 $this->setFlag( DBO_TRX
); // restore automatic begin()
2573 $this->clearFlag( DBO_TRX
); // restore auto-commit
2575 } catch ( Exception
$ex ) {
2576 call_user_func( $this->errorLogger
, $ex );
2578 // Some callbacks may use startAtomic/endAtomic, so make sure
2579 // their transactions are ended so other callbacks don't fail
2580 if ( $this->trxLevel() ) {
2581 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2585 } while ( count( $this->mTrxIdleCallbacks
) );
2587 if ( $e instanceof Exception
) {
2588 throw $e; // re-throw any first exception
2593 * Actually run and consume any "on transaction pre-commit" callbacks.
2595 * This method should not be used outside of Database/LoadBalancer
2600 public function runOnTransactionPreCommitCallbacks() {
2601 $e = null; // first exception
2602 do { // callbacks may add callbacks :)
2603 $callbacks = $this->mTrxPreCommitCallbacks
;
2604 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2605 foreach ( $callbacks as $callback ) {
2607 list( $phpCallback ) = $callback;
2608 call_user_func( $phpCallback );
2609 } catch ( Exception
$ex ) {
2610 call_user_func( $this->errorLogger
, $ex );
2614 } while ( count( $this->mTrxPreCommitCallbacks
) );
2616 if ( $e instanceof Exception
) {
2617 throw $e; // re-throw any first exception
2622 * Actually run any "transaction listener" callbacks.
2624 * This method should not be used outside of Database/LoadBalancer
2626 * @param integer $trigger IDatabase::TRIGGER_* constant
2630 public function runTransactionListenerCallbacks( $trigger ) {
2631 if ( $this->mTrxEndCallbacksSuppressed
) {
2635 /** @var Exception $e */
2636 $e = null; // first exception
2638 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2640 $phpCallback( $trigger, $this );
2641 } catch ( Exception
$ex ) {
2642 call_user_func( $this->errorLogger
, $ex );
2647 if ( $e instanceof Exception
) {
2648 throw $e; // re-throw any first exception
2652 final public function startAtomic( $fname = __METHOD__
) {
2653 if ( !$this->mTrxLevel
) {
2654 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2655 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2656 // in all changes being in one transaction to keep requests transactional.
2657 if ( !$this->getFlag( DBO_TRX
) ) {
2658 $this->mTrxAutomaticAtomic
= true;
2662 $this->mTrxAtomicLevels
[] = $fname;
2665 final public function endAtomic( $fname = __METHOD__
) {
2666 if ( !$this->mTrxLevel
) {
2667 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2669 if ( !$this->mTrxAtomicLevels ||
2670 array_pop( $this->mTrxAtomicLevels
) !== $fname
2672 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2675 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2676 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2680 final public function doAtomicSection( $fname, callable
$callback ) {
2681 $this->startAtomic( $fname );
2683 $res = call_user_func_array( $callback, [ $this, $fname ] );
2684 } catch ( Exception
$e ) {
2685 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2688 $this->endAtomic( $fname );
2693 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2694 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2695 if ( $this->mTrxLevel
) {
2696 if ( $this->mTrxAtomicLevels
) {
2697 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2698 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2699 throw new DBUnexpectedError( $this, $msg );
2700 } elseif ( !$this->mTrxAutomatic
) {
2701 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2702 throw new DBUnexpectedError( $this, $msg );
2704 // @TODO: make this an exception at some point
2705 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2706 $this->queryLogger
->error( $msg );
2707 return; // join the main transaction set
2709 } elseif ( $this->getFlag( DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2710 // @TODO: make this an exception at some point
2711 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2712 $this->queryLogger
->error( $msg );
2713 return; // let any writes be in the main transaction
2716 // Avoid fatals if close() was called
2717 $this->assertOpen();
2719 $this->doBegin( $fname );
2720 $this->mTrxTimestamp
= microtime( true );
2721 $this->mTrxFname
= $fname;
2722 $this->mTrxDoneWrites
= false;
2723 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2724 $this->mTrxAutomaticAtomic
= false;
2725 $this->mTrxAtomicLevels
= [];
2726 $this->mTrxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2727 $this->mTrxWriteDuration
= 0.0;
2728 $this->mTrxWriteQueryCount
= 0;
2729 $this->mTrxWriteAdjDuration
= 0.0;
2730 $this->mTrxWriteAdjQueryCount
= 0;
2731 $this->mTrxWriteCallers
= [];
2732 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2733 // Get an estimate of the replica DB lag before then, treating estimate staleness
2734 // as lag itself just to be safe
2735 $status = $this->getApproximateLagStatus();
2736 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2740 * Issues the BEGIN command to the database server.
2742 * @see DatabaseBase::begin()
2743 * @param string $fname
2745 protected function doBegin( $fname ) {
2746 $this->query( 'BEGIN', $fname );
2747 $this->mTrxLevel
= 1;
2750 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2751 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2752 // There are still atomic sections open. This cannot be ignored
2753 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2754 throw new DBUnexpectedError(
2756 "$fname: Got COMMIT while atomic sections $levels are still open."
2760 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2761 if ( !$this->mTrxLevel
) {
2762 return; // nothing to do
2763 } elseif ( !$this->mTrxAutomatic
) {
2764 throw new DBUnexpectedError(
2766 "$fname: Flushing an explicit transaction, getting out of sync."
2770 if ( !$this->mTrxLevel
) {
2771 $this->queryLogger
->error( "$fname: No transaction to commit, something got out of sync." );
2772 return; // nothing to do
2773 } elseif ( $this->mTrxAutomatic
) {
2774 // @TODO: make this an exception at some point
2775 $msg = "$fname: Explicit commit of implicit transaction.";
2776 $this->queryLogger
->error( $msg );
2777 return; // wait for the main transaction set commit round
2781 // Avoid fatals if close() was called
2782 $this->assertOpen();
2784 $this->runOnTransactionPreCommitCallbacks();
2785 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2786 $this->doCommit( $fname );
2787 if ( $this->mTrxDoneWrites
) {
2788 $this->mDoneWrites
= microtime( true );
2789 $this->trxProfiler
->transactionWritingOut(
2790 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2793 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2794 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
2798 * Issues the COMMIT command to the database server.
2800 * @see DatabaseBase::commit()
2801 * @param string $fname
2803 protected function doCommit( $fname ) {
2804 if ( $this->mTrxLevel
) {
2805 $this->query( 'COMMIT', $fname );
2806 $this->mTrxLevel
= 0;
2810 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2811 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2812 if ( !$this->mTrxLevel
) {
2813 return; // nothing to do
2816 if ( !$this->mTrxLevel
) {
2817 $this->queryLogger
->error(
2818 "$fname: No transaction to rollback, something got out of sync." );
2819 return; // nothing to do
2820 } elseif ( $this->getFlag( DBO_TRX
) ) {
2821 throw new DBUnexpectedError(
2823 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2828 // Avoid fatals if close() was called
2829 $this->assertOpen();
2831 $this->doRollback( $fname );
2832 $this->mTrxAtomicLevels
= [];
2833 if ( $this->mTrxDoneWrites
) {
2834 $this->trxProfiler
->transactionWritingOut(
2835 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
2838 $this->mTrxIdleCallbacks
= []; // clear
2839 $this->mTrxPreCommitCallbacks
= []; // clear
2840 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
2841 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
2845 * Issues the ROLLBACK command to the database server.
2847 * @see DatabaseBase::rollback()
2848 * @param string $fname
2850 protected function doRollback( $fname ) {
2851 if ( $this->mTrxLevel
) {
2852 # Disconnects cause rollback anyway, so ignore those errors
2853 $ignoreErrors = true;
2854 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
2855 $this->mTrxLevel
= 0;
2859 public function flushSnapshot( $fname = __METHOD__
) {
2860 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
2861 // This only flushes transactions to clear snapshots, not to write data
2862 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
2863 throw new DBUnexpectedError(
2865 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
2869 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2872 public function explicitTrxActive() {
2873 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
2877 * Creates a new table with structure copied from existing table
2878 * Note that unlike most database abstraction functions, this function does not
2879 * automatically append database prefix, because it works at a lower
2880 * abstraction level.
2881 * The table names passed to this function shall not be quoted (this
2882 * function calls addIdentifierQuotes when needed).
2884 * @param string $oldName Name of table whose structure should be copied
2885 * @param string $newName Name of table to be created
2886 * @param bool $temporary Whether the new table should be temporary
2887 * @param string $fname Calling function name
2888 * @throws RuntimeException
2889 * @return bool True if operation was successful
2891 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
2894 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2897 function listTables( $prefix = null, $fname = __METHOD__
) {
2898 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2902 * Reset the views process cache set by listViews()
2905 final public function clearViewsCache() {
2906 $this->allViews
= null;
2910 * Lists all the VIEWs in the database
2912 * For caching purposes the list of all views should be stored in
2913 * $this->allViews. The process cache can be cleared with clearViewsCache()
2915 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
2916 * @param string $fname Name of calling function
2917 * @throws RuntimeException
2921 public function listViews( $prefix = null, $fname = __METHOD__
) {
2922 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2926 * Differentiates between a TABLE and a VIEW
2928 * @param string $name Name of the database-structure to test.
2929 * @throws RuntimeException
2933 public function isView( $name ) {
2934 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2937 public function timestamp( $ts = 0 ) {
2938 $t = new ConvertableTimestamp( $ts );
2939 // Let errors bubble up to avoid putting garbage in the DB
2940 return $t->getTimestamp( TS_MW
);
2943 public function timestampOrNull( $ts = null ) {
2944 if ( is_null( $ts ) ) {
2947 return $this->timestamp( $ts );
2952 * Take the result from a query, and wrap it in a ResultWrapper if
2953 * necessary. Boolean values are passed through as is, to indicate success
2954 * of write queries or failure.
2956 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2957 * resource, and it was necessary to call this function to convert it to
2958 * a wrapper. Nowadays, raw database objects are never exposed to external
2959 * callers, so this is unnecessary in external code.
2961 * @param bool|ResultWrapper|resource|object $result
2962 * @return bool|ResultWrapper
2964 protected function resultObject( $result ) {
2967 } elseif ( $result instanceof ResultWrapper
) {
2969 } elseif ( $result === true ) {
2970 // Successful write query
2973 return new ResultWrapper( $this, $result );
2977 public function ping( &$rtt = null ) {
2978 // Avoid hitting the server if it was hit recently
2979 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
2980 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
2981 $rtt = $this->mRTTEstimate
;
2982 return true; // don't care about $rtt
2986 // This will reconnect if possible or return false if not
2987 $this->clearFlag( DBO_TRX
, self
::REMEMBER_PRIOR
);
2988 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
2989 $this->restoreFlags( self
::RESTORE_PRIOR
);
2992 $rtt = $this->mRTTEstimate
;
3001 protected function reconnect() {
3002 $this->closeConnection();
3003 $this->mOpened
= false;
3004 $this->mConn
= false;
3006 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3007 $this->lastPing
= microtime( true );
3009 } catch ( DBConnectionError
$e ) {
3016 public function getSessionLagStatus() {
3017 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3021 * Get the replica DB lag when the current transaction started
3023 * This is useful when transactions might use snapshot isolation
3024 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3025 * is this lag plus transaction duration. If they don't, it is still
3026 * safe to be pessimistic. This returns null if there is no transaction.
3028 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3031 public function getTransactionLagStatus() {
3032 return $this->mTrxLevel
3033 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3038 * Get a replica DB lag estimate for this server
3040 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3043 public function getApproximateLagStatus() {
3045 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3046 'since' => microtime( true )
3051 * Merge the result of getSessionLagStatus() for several DBs
3052 * using the most pessimistic values to estimate the lag of
3053 * any data derived from them in combination
3055 * This is information is useful for caching modules
3057 * @see WANObjectCache::set()
3058 * @see WANObjectCache::getWithSetCallback()
3060 * @param IDatabase $db1
3061 * @param IDatabase ...
3062 * @return array Map of values:
3063 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3064 * - since: oldest UNIX timestamp of any of the DB lag estimates
3065 * - pending: whether any of the DBs have uncommitted changes
3068 public static function getCacheSetOptions( IDatabase
$db1 ) {
3069 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3070 foreach ( func_get_args() as $db ) {
3071 /** @var IDatabase $db */
3072 $status = $db->getSessionLagStatus();
3073 if ( $status['lag'] === false ) {
3074 $res['lag'] = false;
3075 } elseif ( $res['lag'] !== false ) {
3076 $res['lag'] = max( $res['lag'], $status['lag'] );
3078 $res['since'] = min( $res['since'], $status['since'] );
3079 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3085 public function getLag() {
3089 function maxListLen() {
3093 public function encodeBlob( $b ) {
3097 public function decodeBlob( $b ) {
3098 if ( $b instanceof Blob
) {
3104 public function setSessionOptions( array $options ) {
3108 * Read and execute SQL commands from a file.
3110 * Returns true on success, error string or exception on failure (depending
3111 * on object's error ignore settings).
3113 * @param string $filename File name to open
3114 * @param bool|callable $lineCallback Optional function called before reading each line
3115 * @param bool|callable $resultCallback Optional function called for each MySQL result
3116 * @param bool|string $fname Calling function name or false if name should be
3117 * generated dynamically using $filename
3118 * @param bool|callable $inputCallback Optional function called for each
3119 * complete line sent
3120 * @return bool|string
3123 public function sourceFile(
3124 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3126 MediaWiki\
suppressWarnings();
3127 $fp = fopen( $filename, 'r' );
3128 MediaWiki\restoreWarnings
();
3130 if ( false === $fp ) {
3131 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3135 $fname = __METHOD__
. "( $filename )";
3139 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3140 } catch ( Exception
$e ) {
3150 public function setSchemaVars( $vars ) {
3151 $this->mSchemaVars
= $vars;
3155 * Read and execute commands from an open file handle.
3157 * Returns true on success, error string or exception on failure (depending
3158 * on object's error ignore settings).
3160 * @param resource $fp File handle
3161 * @param bool|callable $lineCallback Optional function called before reading each query
3162 * @param bool|callable $resultCallback Optional function called for each MySQL result
3163 * @param string $fname Calling function name
3164 * @param bool|callable $inputCallback Optional function called for each complete query sent
3165 * @return bool|string
3167 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3168 $fname = __METHOD__
, $inputCallback = false
3172 while ( !feof( $fp ) ) {
3173 if ( $lineCallback ) {
3174 call_user_func( $lineCallback );
3177 $line = trim( fgets( $fp ) );
3179 if ( $line == '' ) {
3183 if ( '-' == $line[0] && '-' == $line[1] ) {
3191 $done = $this->streamStatementEnd( $cmd, $line );
3195 if ( $done ||
feof( $fp ) ) {
3196 $cmd = $this->replaceVars( $cmd );
3198 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3199 $res = $this->query( $cmd, $fname );
3201 if ( $resultCallback ) {
3202 call_user_func( $resultCallback, $res, $this );
3205 if ( false === $res ) {
3206 $err = $this->lastError();
3208 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3219 * Called by sourceStream() to check if we've reached a statement end
3221 * @param string $sql SQL assembled so far
3222 * @param string $newLine New line about to be added to $sql
3223 * @return bool Whether $newLine contains end of the statement
3225 public function streamStatementEnd( &$sql, &$newLine ) {
3226 if ( $this->delimiter
) {
3228 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3229 if ( $newLine != $prev ) {
3238 * Database independent variable replacement. Replaces a set of variables
3239 * in an SQL statement with their contents as given by $this->getSchemaVars().
3241 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3243 * - '{$var}' should be used for text and is passed through the database's
3245 * - `{$var}` should be used for identifiers (e.g. table and database names).
3246 * It is passed through the database's addIdentifierQuotes method which
3247 * can be overridden if the database uses something other than backticks.
3248 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3249 * database's tableName method.
3250 * - / *i* / passes the name that follows through the database's indexName method.
3251 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3252 * its use should be avoided. In 1.24 and older, string encoding was applied.
3254 * @param string $ins SQL statement to replace variables in
3255 * @return string The new SQL statement with variables replaced
3257 protected function replaceVars( $ins ) {
3258 $vars = $this->getSchemaVars();
3259 return preg_replace_callback(
3261 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3262 \'\{\$ (\w+) }\' | # 3. addQuotes
3263 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3264 /\*\$ (\w+) \*/ # 5. leave unencoded
3266 function ( $m ) use ( $vars ) {
3267 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3268 // check for both nonexistent keys *and* the empty string.
3269 if ( isset( $m[1] ) && $m[1] !== '' ) {
3270 if ( $m[1] === 'i' ) {
3271 return $this->indexName( $m[2] );
3273 return $this->tableName( $m[2] );
3275 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3276 return $this->addQuotes( $vars[$m[3]] );
3277 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3278 return $this->addIdentifierQuotes( $vars[$m[4]] );
3279 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3280 return $vars[$m[5]];
3290 * Get schema variables. If none have been set via setSchemaVars(), then
3291 * use some defaults from the current object.
3295 protected function getSchemaVars() {
3296 if ( $this->mSchemaVars
) {
3297 return $this->mSchemaVars
;
3299 return $this->getDefaultSchemaVars();
3304 * Get schema variables to use if none have been set via setSchemaVars().
3306 * Override this in derived classes to provide variables for tables.sql
3307 * and SQL patch files.
3311 protected function getDefaultSchemaVars() {
3315 public function lockIsFree( $lockName, $method ) {
3319 public function lock( $lockName, $method, $timeout = 5 ) {
3320 $this->mNamedLocksHeld
[$lockName] = 1;
3325 public function unlock( $lockName, $method ) {
3326 unset( $this->mNamedLocksHeld
[$lockName] );
3331 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3332 if ( $this->writesOrCallbacksPending() ) {
3333 // This only flushes transactions to clear snapshots, not to write data
3334 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3335 throw new DBUnexpectedError(
3337 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
3341 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3345 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3346 if ( $this->trxLevel() ) {
3347 // There is a good chance an exception was thrown, causing any early return
3348 // from the caller. Let any error handler get a chance to issue rollback().
3349 // If there isn't one, let the error bubble up and trigger server-side rollback.
3350 $this->onTransactionResolution(
3351 function () use ( $lockKey, $fname ) {
3352 $this->unlock( $lockKey, $fname );
3357 $this->unlock( $lockKey, $fname );
3361 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3366 public function namedLocksEnqueue() {
3371 * Lock specific tables
3373 * @param array $read Array of tables to lock for read access
3374 * @param array $write Array of tables to lock for write access
3375 * @param string $method Name of caller
3376 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3379 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3384 * Unlock specific tables
3386 * @param string $method The caller
3389 public function unlockTables( $method ) {
3395 * @param string $tableName
3396 * @param string $fName
3397 * @return bool|ResultWrapper
3400 public function dropTable( $tableName, $fName = __METHOD__
) {
3401 if ( !$this->tableExists( $tableName, $fName ) ) {
3404 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3406 return $this->query( $sql, $fName );
3409 public function getInfinity() {
3413 public function encodeExpiry( $expiry ) {
3414 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3415 ?
$this->getInfinity()
3416 : $this->timestamp( $expiry );
3419 public function decodeExpiry( $expiry, $format = TS_MW
) {
3420 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3425 $t = new ConvertableTimestamp( $expiry );
3427 return $t->getTimestamp( $format );
3428 } catch ( TimestampException
$e ) {
3433 public function setBigSelects( $value = true ) {
3437 public function isReadOnly() {
3438 return ( $this->getReadOnlyReason() !== false );
3442 * @return string|bool Reason this DB is read-only or false if it is not
3444 protected function getReadOnlyReason() {
3445 $reason = $this->getLBInfo( 'readOnlyReason' );
3447 return is_string( $reason ) ?
$reason : false;
3450 public function setTableAliases( array $aliases ) {
3451 $this->tableAliases
= $aliases;
3458 public function __toString() {
3459 return (string)$this->mConn
;
3463 * Called by serialize. Throw an exception when DB connection is serialized.
3464 * This causes problems on some database engines because the connection is
3465 * not restored on unserialize.
3467 public function __sleep() {
3468 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3469 'the connection is not restored on wakeup.' );
3473 * Run a few simple sanity checks
3475 public function __destruct() {
3476 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3477 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3480 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3481 if ( $danglingWriters ) {
3482 $fnames = implode( ', ', $danglingWriters );
3483 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );