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 MWDebug
::query( $sql, $fname, $isMaster, $queryRuntime );
912 * Update the estimated run-time of a query, not counting large row lock times
914 * LoadBalancer can be set to rollback transactions that will create huge replication
915 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
916 * queries, like inserting a row can take a long time due to row locking. This method
917 * uses some simple heuristics to discount those cases.
919 * @param string $sql A SQL write query
920 * @param float $runtime Total runtime, including RTT
922 private function updateTrxWriteQueryTime( $sql, $runtime ) {
923 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
924 $indicativeOfReplicaRuntime = true;
925 if ( $runtime > self
::SLOW_WRITE_SEC
) {
926 $verb = $this->getQueryVerb( $sql );
927 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
928 if ( $verb === 'INSERT' ) {
929 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
930 } elseif ( $verb === 'REPLACE' ) {
931 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
935 $this->mTrxWriteDuration +
= $runtime;
936 $this->mTrxWriteQueryCount +
= 1;
937 if ( $indicativeOfReplicaRuntime ) {
938 $this->mTrxWriteAdjDuration +
= $runtime;
939 $this->mTrxWriteAdjQueryCount +
= 1;
943 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
944 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
945 # Dropped connections also mean that named locks are automatically released.
946 # Only allow error suppression in autocommit mode or when the lost transaction
947 # didn't matter anyway (aside from DBO_TRX snapshot loss).
948 if ( $this->mNamedLocksHeld
) {
949 return false; // possible critical section violation
950 } elseif ( $sql === 'COMMIT' ) {
951 return !$priorWritesPending; // nothing written anyway? (T127428)
952 } elseif ( $sql === 'ROLLBACK' ) {
953 return true; // transaction lost...which is also what was requested :)
954 } elseif ( $this->explicitTrxActive() ) {
955 return false; // don't drop atomocity
956 } elseif ( $priorWritesPending ) {
957 return false; // prior writes lost from implicit transaction
963 private function handleTransactionLoss() {
964 $this->mTrxLevel
= 0;
965 $this->mTrxIdleCallbacks
= []; // bug 65263
966 $this->mTrxPreCommitCallbacks
= []; // bug 65263
968 // Handle callbacks in mTrxEndCallbacks
969 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
970 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
972 } catch ( Exception
$e ) {
973 // Already logged; move on...
978 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
979 if ( $this->ignoreErrors() ||
$tempIgnore ) {
980 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
982 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
983 $this->queryLogger
->error(
984 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
985 $this->getLogContext( [
986 'method' => __METHOD__
,
989 'sql1line' => $sql1line,
993 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
994 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
998 public function freeResult( $res ) {
1001 public function selectField(
1002 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1004 if ( $var === '*' ) { // sanity
1005 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1008 if ( !is_array( $options ) ) {
1009 $options = [ $options ];
1012 $options['LIMIT'] = 1;
1014 $res = $this->select( $table, $var, $cond, $fname, $options );
1015 if ( $res === false ||
!$this->numRows( $res ) ) {
1019 $row = $this->fetchRow( $res );
1021 if ( $row !== false ) {
1022 return reset( $row );
1028 public function selectFieldValues(
1029 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1031 if ( $var === '*' ) { // sanity
1032 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1033 } elseif ( !is_string( $var ) ) { // sanity
1034 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1037 if ( !is_array( $options ) ) {
1038 $options = [ $options ];
1041 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1042 if ( $res === false ) {
1047 foreach ( $res as $row ) {
1048 $values[] = $row->$var;
1055 * Returns an optional USE INDEX clause to go after the table, and a
1056 * string to go at the end of the query.
1058 * @param array $options Associative array of options to be turned into
1059 * an SQL query, valid keys are listed in the function.
1061 * @see DatabaseBase::select()
1063 public function makeSelectOptions( $options ) {
1064 $preLimitTail = $postLimitTail = '';
1069 foreach ( $options as $key => $option ) {
1070 if ( is_numeric( $key ) ) {
1071 $noKeyOptions[$option] = true;
1075 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1077 $preLimitTail .= $this->makeOrderBy( $options );
1079 // if (isset($options['LIMIT'])) {
1080 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1081 // isset($options['OFFSET']) ? $options['OFFSET']
1085 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1086 $postLimitTail .= ' FOR UPDATE';
1089 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1090 $postLimitTail .= ' LOCK IN SHARE MODE';
1093 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1094 $startOpts .= 'DISTINCT';
1097 # Various MySQL extensions
1098 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1099 $startOpts .= ' /*! STRAIGHT_JOIN */';
1102 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1103 $startOpts .= ' HIGH_PRIORITY';
1106 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1107 $startOpts .= ' SQL_BIG_RESULT';
1110 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1111 $startOpts .= ' SQL_BUFFER_RESULT';
1114 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1115 $startOpts .= ' SQL_SMALL_RESULT';
1118 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1119 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1122 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1123 $startOpts .= ' SQL_CACHE';
1126 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1127 $startOpts .= ' SQL_NO_CACHE';
1130 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1131 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1135 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1136 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1141 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1145 * Returns an optional GROUP BY with an optional HAVING
1147 * @param array $options Associative array of options
1149 * @see DatabaseBase::select()
1152 public function makeGroupByWithHaving( $options ) {
1154 if ( isset( $options['GROUP BY'] ) ) {
1155 $gb = is_array( $options['GROUP BY'] )
1156 ?
implode( ',', $options['GROUP BY'] )
1157 : $options['GROUP BY'];
1158 $sql .= ' GROUP BY ' . $gb;
1160 if ( isset( $options['HAVING'] ) ) {
1161 $having = is_array( $options['HAVING'] )
1162 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1163 : $options['HAVING'];
1164 $sql .= ' HAVING ' . $having;
1171 * Returns an optional ORDER BY
1173 * @param array $options Associative array of options
1175 * @see DatabaseBase::select()
1178 public function makeOrderBy( $options ) {
1179 if ( isset( $options['ORDER BY'] ) ) {
1180 $ob = is_array( $options['ORDER BY'] )
1181 ?
implode( ',', $options['ORDER BY'] )
1182 : $options['ORDER BY'];
1184 return ' ORDER BY ' . $ob;
1190 // See IDatabase::select for the docs for this function
1191 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1192 $options = [], $join_conds = [] ) {
1193 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1195 return $this->query( $sql, $fname );
1198 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1199 $options = [], $join_conds = []
1201 if ( is_array( $vars ) ) {
1202 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1205 $options = (array)$options;
1206 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1207 ?
$options['USE INDEX']
1209 $ignoreIndexes = ( isset( $options['IGNORE INDEX'] ) && is_array( $options['IGNORE INDEX'] ) )
1210 ?
$options['IGNORE INDEX']
1213 if ( is_array( $table ) ) {
1215 $this->tableNamesWithIndexClauseOrJOIN( $table, $useIndexes, $ignoreIndexes, $join_conds );
1216 } elseif ( $table != '' ) {
1217 if ( $table[0] == ' ' ) {
1218 $from = ' FROM ' . $table;
1221 $this->tableNamesWithIndexClauseOrJOIN( [ $table ], $useIndexes, $ignoreIndexes, [] );
1227 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1228 $this->makeSelectOptions( $options );
1230 if ( !empty( $conds ) ) {
1231 if ( is_array( $conds ) ) {
1232 $conds = $this->makeList( $conds, LIST_AND
);
1234 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex WHERE $conds $preLimitTail";
1236 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1239 if ( isset( $options['LIMIT'] ) ) {
1240 $sql = $this->limitResult( $sql, $options['LIMIT'],
1241 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1243 $sql = "$sql $postLimitTail";
1245 if ( isset( $options['EXPLAIN'] ) ) {
1246 $sql = 'EXPLAIN ' . $sql;
1252 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1253 $options = [], $join_conds = []
1255 $options = (array)$options;
1256 $options['LIMIT'] = 1;
1257 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1259 if ( $res === false ) {
1263 if ( !$this->numRows( $res ) ) {
1267 $obj = $this->fetchObject( $res );
1272 public function estimateRowCount(
1273 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1276 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1279 $row = $this->fetchRow( $res );
1280 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1286 public function selectRowCount(
1287 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1290 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1291 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1294 $row = $this->fetchRow( $res );
1295 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1302 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1303 * It's only slightly flawed. Don't use for anything important.
1305 * @param string $sql A SQL Query
1309 protected static function generalizeSQL( $sql ) {
1310 # This does the same as the regexp below would do, but in such a way
1311 # as to avoid crashing php on some large strings.
1312 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1314 $sql = str_replace( "\\\\", '', $sql );
1315 $sql = str_replace( "\\'", '', $sql );
1316 $sql = str_replace( "\\\"", '', $sql );
1317 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1318 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1320 # All newlines, tabs, etc replaced by single space
1321 $sql = preg_replace( '/\s+/', ' ', $sql );
1324 # except the ones surrounded by characters, e.g. l10n
1325 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1326 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1331 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1332 $info = $this->fieldInfo( $table, $field );
1337 public function indexExists( $table, $index, $fname = __METHOD__
) {
1338 if ( !$this->tableExists( $table ) ) {
1342 $info = $this->indexInfo( $table, $index, $fname );
1343 if ( is_null( $info ) ) {
1346 return $info !== false;
1350 public function tableExists( $table, $fname = __METHOD__
) {
1351 $table = $this->tableName( $table );
1352 $old = $this->ignoreErrors( true );
1353 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1354 $this->ignoreErrors( $old );
1359 public function indexUnique( $table, $index ) {
1360 $indexInfo = $this->indexInfo( $table, $index );
1362 if ( !$indexInfo ) {
1366 return !$indexInfo[0]->Non_unique
;
1370 * Helper for DatabaseBase::insert().
1372 * @param array $options
1375 protected function makeInsertOptions( $options ) {
1376 return implode( ' ', $options );
1379 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1380 # No rows to insert, easy just return now
1381 if ( !count( $a ) ) {
1385 $table = $this->tableName( $table );
1387 if ( !is_array( $options ) ) {
1388 $options = [ $options ];
1392 if ( isset( $options['fileHandle'] ) ) {
1393 $fh = $options['fileHandle'];
1395 $options = $this->makeInsertOptions( $options );
1397 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1399 $keys = array_keys( $a[0] );
1402 $keys = array_keys( $a );
1405 $sql = 'INSERT ' . $options .
1406 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1410 foreach ( $a as $row ) {
1416 $sql .= '(' . $this->makeList( $row ) . ')';
1419 $sql .= '(' . $this->makeList( $a ) . ')';
1422 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1424 } elseif ( $fh !== null ) {
1428 return (bool)$this->query( $sql, $fname );
1432 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1434 * @param array $options
1437 protected function makeUpdateOptionsArray( $options ) {
1438 if ( !is_array( $options ) ) {
1439 $options = [ $options ];
1444 if ( in_array( 'IGNORE', $options ) ) {
1452 * Make UPDATE options for the DatabaseBase::update function
1454 * @param array $options The options passed to DatabaseBase::update
1457 protected function makeUpdateOptions( $options ) {
1458 $opts = $this->makeUpdateOptionsArray( $options );
1460 return implode( ' ', $opts );
1463 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1464 $table = $this->tableName( $table );
1465 $opts = $this->makeUpdateOptions( $options );
1466 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1468 if ( $conds !== [] && $conds !== '*' ) {
1469 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1472 return $this->query( $sql, $fname );
1475 public function makeList( $a, $mode = LIST_COMMA
) {
1476 if ( !is_array( $a ) ) {
1477 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1483 foreach ( $a as $field => $value ) {
1485 if ( $mode == LIST_AND
) {
1487 } elseif ( $mode == LIST_OR
) {
1496 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1497 $list .= "($value)";
1498 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1500 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1501 // Remove null from array to be handled separately if found
1502 $includeNull = false;
1503 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1504 $includeNull = true;
1505 unset( $value[$nullKey] );
1507 if ( count( $value ) == 0 && !$includeNull ) {
1508 throw new InvalidArgumentException( __METHOD__
. ": empty input for field $field" );
1509 } elseif ( count( $value ) == 0 ) {
1510 // only check if $field is null
1511 $list .= "$field IS NULL";
1513 // IN clause contains at least one valid element
1514 if ( $includeNull ) {
1515 // Group subconditions to ensure correct precedence
1518 if ( count( $value ) == 1 ) {
1519 // Special-case single values, as IN isn't terribly efficient
1520 // Don't necessarily assume the single key is 0; we don't
1521 // enforce linear numeric ordering on other arrays here.
1522 $value = array_values( $value )[0];
1523 $list .= $field . " = " . $this->addQuotes( $value );
1525 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1527 // if null present in array, append IS NULL
1528 if ( $includeNull ) {
1529 $list .= " OR $field IS NULL)";
1532 } elseif ( $value === null ) {
1533 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1534 $list .= "$field IS ";
1535 } elseif ( $mode == LIST_SET
) {
1536 $list .= "$field = ";
1540 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1541 $list .= "$field = ";
1543 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1550 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1553 foreach ( $data as $base => $sub ) {
1554 if ( count( $sub ) ) {
1555 $conds[] = $this->makeList(
1556 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1562 return $this->makeList( $conds, LIST_OR
);
1564 // Nothing to search for...
1570 * Return aggregated value alias
1572 * @param array $valuedata
1573 * @param string $valuename
1577 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1581 public function bitNot( $field ) {
1585 public function bitAnd( $fieldLeft, $fieldRight ) {
1586 return "($fieldLeft & $fieldRight)";
1589 public function bitOr( $fieldLeft, $fieldRight ) {
1590 return "($fieldLeft | $fieldRight)";
1593 public function buildConcat( $stringList ) {
1594 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1597 public function buildGroupConcatField(
1598 $delim, $table, $field, $conds = '', $join_conds = []
1600 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1602 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1606 * @param string $field Field or column to cast
1610 public function buildStringCast( $field ) {
1614 public function selectDB( $db ) {
1615 # Stub. Shouldn't cause serious problems if it's not overridden, but
1616 # if your database engine supports a concept similar to MySQL's
1617 # databases you may as well.
1618 $this->mDBname
= $db;
1623 public function getDBname() {
1624 return $this->mDBname
;
1627 public function getServer() {
1628 return $this->mServer
;
1632 * Format a table name ready for use in constructing an SQL query
1634 * This does two important things: it quotes the table names to clean them up,
1635 * and it adds a table prefix if only given a table name with no quotes.
1637 * All functions of this object which require a table name call this function
1638 * themselves. Pass the canonical name to such functions. This is only needed
1639 * when calling query() directly.
1641 * @note This function does not sanitize user input. It is not safe to use
1642 * this function to escape user input.
1643 * @param string $name Database table name
1644 * @param string $format One of:
1645 * quoted - Automatically pass the table name through addIdentifierQuotes()
1646 * so that it can be used in a query.
1647 * raw - Do not add identifier quotes to the table name
1648 * @return string Full database name
1650 public function tableName( $name, $format = 'quoted' ) {
1651 # Skip the entire process when we have a string quoted on both ends.
1652 # Note that we check the end so that we will still quote any use of
1653 # use of `database`.table. But won't break things if someone wants
1654 # to query a database table with a dot in the name.
1655 if ( $this->isQuotedIdentifier( $name ) ) {
1659 # Lets test for any bits of text that should never show up in a table
1660 # name. Basically anything like JOIN or ON which are actually part of
1661 # SQL queries, but may end up inside of the table value to combine
1662 # sql. Such as how the API is doing.
1663 # Note that we use a whitespace test rather than a \b test to avoid
1664 # any remote case where a word like on may be inside of a table name
1665 # surrounded by symbols which may be considered word breaks.
1666 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1670 # Split database and table into proper variables.
1671 # We reverse the explode so that database.table and table both output
1672 # the correct table.
1673 $dbDetails = explode( '.', $name, 3 );
1674 if ( count( $dbDetails ) == 3 ) {
1675 list( $database, $schema, $table ) = $dbDetails;
1676 # We don't want any prefix added in this case
1678 } elseif ( count( $dbDetails ) == 2 ) {
1679 list( $database, $table ) = $dbDetails;
1680 # We don't want any prefix added in this case
1681 # In dbs that support it, $database may actually be the schema
1682 # but that doesn't affect any of the functionality here
1686 list( $table ) = $dbDetails;
1687 if ( isset( $this->tableAliases
[$table] ) ) {
1688 $database = $this->tableAliases
[$table]['dbname'];
1689 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1690 ?
$this->tableAliases
[$table]['schema']
1692 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1693 ?
$this->tableAliases
[$table]['prefix']
1694 : $this->mTablePrefix
;
1697 $schema = $this->mSchema
; # Default schema
1698 $prefix = $this->mTablePrefix
; # Default prefix
1702 # Quote $table and apply the prefix if not quoted.
1703 # $tableName might be empty if this is called from Database::replaceVars()
1704 $tableName = "{$prefix}{$table}";
1705 if ( $format == 'quoted'
1706 && !$this->isQuotedIdentifier( $tableName ) && $tableName !== ''
1708 $tableName = $this->addIdentifierQuotes( $tableName );
1711 # Quote $schema and merge it with the table name if needed
1712 if ( strlen( $schema ) ) {
1713 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1714 $schema = $this->addIdentifierQuotes( $schema );
1716 $tableName = $schema . '.' . $tableName;
1719 # Quote $database and merge it with the table name if needed
1720 if ( $database !== '' ) {
1721 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1722 $database = $this->addIdentifierQuotes( $database );
1724 $tableName = $database . '.' . $tableName;
1731 * Fetch a number of table names into an array
1732 * This is handy when you need to construct SQL for joins
1735 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1736 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1737 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1741 public function tableNames() {
1742 $inArray = func_get_args();
1745 foreach ( $inArray as $name ) {
1746 $retVal[$name] = $this->tableName( $name );
1753 * Fetch a number of table names into an zero-indexed numerical array
1754 * This is handy when you need to construct SQL for joins
1757 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1758 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1759 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1763 public function tableNamesN() {
1764 $inArray = func_get_args();
1767 foreach ( $inArray as $name ) {
1768 $retVal[] = $this->tableName( $name );
1775 * Get an aliased table name
1776 * e.g. tableName AS newTableName
1778 * @param string $name Table name, see tableName()
1779 * @param string|bool $alias Alias (optional)
1780 * @return string SQL name for aliased table. Will not alias a table to its own name
1782 public function tableNameWithAlias( $name, $alias = false ) {
1783 if ( !$alias ||
$alias == $name ) {
1784 return $this->tableName( $name );
1786 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1791 * Gets an array of aliased table names
1793 * @param array $tables [ [alias] => table ]
1794 * @return string[] See tableNameWithAlias()
1796 public function tableNamesWithAlias( $tables ) {
1798 foreach ( $tables as $alias => $table ) {
1799 if ( is_numeric( $alias ) ) {
1802 $retval[] = $this->tableNameWithAlias( $table, $alias );
1809 * Get an aliased field name
1810 * e.g. fieldName AS newFieldName
1812 * @param string $name Field name
1813 * @param string|bool $alias Alias (optional)
1814 * @return string SQL name for aliased field. Will not alias a field to its own name
1816 public function fieldNameWithAlias( $name, $alias = false ) {
1817 if ( !$alias ||
(string)$alias === (string)$name ) {
1820 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1825 * Gets an array of aliased field names
1827 * @param array $fields [ [alias] => field ]
1828 * @return string[] See fieldNameWithAlias()
1830 public function fieldNamesWithAlias( $fields ) {
1832 foreach ( $fields as $alias => $field ) {
1833 if ( is_numeric( $alias ) ) {
1836 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1843 * Get the aliased table name clause for a FROM clause
1844 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
1846 * @param array $tables ( [alias] => table )
1847 * @param array $use_index Same as for select()
1848 * @param array $ignore_index Same as for select()
1849 * @param array $join_conds Same as for select()
1852 protected function tableNamesWithIndexClauseOrJOIN(
1853 $tables, $use_index = [], $ignore_index = [], $join_conds = []
1857 $use_index = (array)$use_index;
1858 $ignore_index = (array)$ignore_index;
1859 $join_conds = (array)$join_conds;
1861 foreach ( $tables as $alias => $table ) {
1862 if ( !is_string( $alias ) ) {
1863 // No alias? Set it equal to the table name
1866 // Is there a JOIN clause for this table?
1867 if ( isset( $join_conds[$alias] ) ) {
1868 list( $joinType, $conds ) = $join_conds[$alias];
1869 $tableClause = $joinType;
1870 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1871 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1872 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1874 $tableClause .= ' ' . $use;
1877 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
1878 $ignore = $this->ignoreIndexClause( implode( ',', (array)$ignore_index[$alias] ) );
1879 if ( $ignore != '' ) {
1880 $tableClause .= ' ' . $ignore;
1883 $on = $this->makeList( (array)$conds, LIST_AND
);
1885 $tableClause .= ' ON (' . $on . ')';
1888 $retJOIN[] = $tableClause;
1889 } elseif ( isset( $use_index[$alias] ) ) {
1890 // Is there an INDEX clause for this table?
1891 $tableClause = $this->tableNameWithAlias( $table, $alias );
1892 $tableClause .= ' ' . $this->useIndexClause(
1893 implode( ',', (array)$use_index[$alias] )
1896 $ret[] = $tableClause;
1897 } elseif ( isset( $ignore_index[$alias] ) ) {
1898 // Is there an INDEX clause for this table?
1899 $tableClause = $this->tableNameWithAlias( $table, $alias );
1900 $tableClause .= ' ' . $this->ignoreIndexClause(
1901 implode( ',', (array)$ignore_index[$alias] )
1904 $ret[] = $tableClause;
1906 $tableClause = $this->tableNameWithAlias( $table, $alias );
1908 $ret[] = $tableClause;
1912 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1913 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1914 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1916 // Compile our final table clause
1917 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
1921 * Get the name of an index in a given table.
1923 * @param string $index
1926 protected function indexName( $index ) {
1927 // Backwards-compatibility hack
1929 'ar_usertext_timestamp' => 'usertext_timestamp',
1930 'un_user_id' => 'user_id',
1931 'un_user_ip' => 'user_ip',
1934 if ( isset( $renamed[$index] ) ) {
1935 return $renamed[$index];
1941 public function addQuotes( $s ) {
1942 if ( $s instanceof Blob
) {
1945 if ( $s === null ) {
1948 # This will also quote numeric values. This should be harmless,
1949 # and protects against weird problems that occur when they really
1950 # _are_ strings such as article titles and string->number->string
1951 # conversion is not 1:1.
1952 return "'" . $this->strencode( $s ) . "'";
1957 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1958 * MySQL uses `backticks` while basically everything else uses double quotes.
1959 * Since MySQL is the odd one out here the double quotes are our generic
1960 * and we implement backticks in DatabaseMysql.
1965 public function addIdentifierQuotes( $s ) {
1966 return '"' . str_replace( '"', '""', $s ) . '"';
1970 * Returns if the given identifier looks quoted or not according to
1971 * the database convention for quoting identifiers .
1973 * @note Do not use this to determine if untrusted input is safe.
1974 * A malicious user can trick this function.
1975 * @param string $name
1978 public function isQuotedIdentifier( $name ) {
1979 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
1986 protected function escapeLikeInternal( $s ) {
1987 return addcslashes( $s, '\%_' );
1990 public function buildLike() {
1991 $params = func_get_args();
1993 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1994 $params = $params[0];
1999 foreach ( $params as $value ) {
2000 if ( $value instanceof LikeMatch
) {
2001 $s .= $value->toString();
2003 $s .= $this->escapeLikeInternal( $value );
2007 return " LIKE {$this->addQuotes( $s )} ";
2010 public function anyChar() {
2011 return new LikeMatch( '_' );
2014 public function anyString() {
2015 return new LikeMatch( '%' );
2018 public function nextSequenceValue( $seqName ) {
2023 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2024 * is only needed because a) MySQL must be as efficient as possible due to
2025 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2026 * which index to pick. Anyway, other databases might have different
2027 * indexes on a given table. So don't bother overriding this unless you're
2029 * @param string $index
2032 public function useIndexClause( $index ) {
2037 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2038 * is only needed because a) MySQL must be as efficient as possible due to
2039 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2040 * which index to pick. Anyway, other databases might have different
2041 * indexes on a given table. So don't bother overriding this unless you're
2043 * @param string $index
2046 public function ignoreIndexClause( $index ) {
2050 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2051 $quotedTable = $this->tableName( $table );
2053 if ( count( $rows ) == 0 ) {
2058 if ( !is_array( reset( $rows ) ) ) {
2062 // @FXIME: this is not atomic, but a trx would break affectedRows()
2063 foreach ( $rows as $row ) {
2064 # Delete rows which collide
2065 if ( $uniqueIndexes ) {
2066 $sql = "DELETE FROM $quotedTable WHERE ";
2068 foreach ( $uniqueIndexes as $index ) {
2075 if ( is_array( $index ) ) {
2077 foreach ( $index as $col ) {
2083 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2086 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2090 $this->query( $sql, $fname );
2093 # Now insert the row
2094 $this->insert( $table, $row, $fname );
2099 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2102 * @param string $table Table name
2103 * @param array|string $rows Row(s) to insert
2104 * @param string $fname Caller function name
2106 * @return ResultWrapper
2108 protected function nativeReplace( $table, $rows, $fname ) {
2109 $table = $this->tableName( $table );
2112 if ( !is_array( reset( $rows ) ) ) {
2116 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2119 foreach ( $rows as $row ) {
2126 $sql .= '(' . $this->makeList( $row ) . ')';
2129 return $this->query( $sql, $fname );
2132 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2135 if ( !count( $rows ) ) {
2136 return true; // nothing to do
2139 if ( !is_array( reset( $rows ) ) ) {
2143 if ( count( $uniqueIndexes ) ) {
2144 $clauses = []; // list WHERE clauses that each identify a single row
2145 foreach ( $rows as $row ) {
2146 foreach ( $uniqueIndexes as $index ) {
2147 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2148 $rowKey = []; // unique key to this row
2149 foreach ( $index as $column ) {
2150 $rowKey[$column] = $row[$column];
2152 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2155 $where = [ $this->makeList( $clauses, LIST_OR
) ];
2160 $useTrx = !$this->mTrxLevel
;
2162 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2165 # Update any existing conflicting row(s)
2166 if ( $where !== false ) {
2167 $ok = $this->update( $table, $set, $where, $fname );
2171 # Now insert any non-conflicting row(s)
2172 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2173 } catch ( Exception
$e ) {
2175 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2180 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2186 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2190 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2193 $delTable = $this->tableName( $delTable );
2194 $joinTable = $this->tableName( $joinTable );
2195 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2196 if ( $conds != '*' ) {
2197 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2201 $this->query( $sql, $fname );
2205 * Returns the size of a text field, or -1 for "unlimited"
2207 * @param string $table
2208 * @param string $field
2211 public function textFieldSize( $table, $field ) {
2212 $table = $this->tableName( $table );
2213 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2214 $res = $this->query( $sql, __METHOD__
);
2215 $row = $this->fetchObject( $res );
2219 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2228 public function delete( $table, $conds, $fname = __METHOD__
) {
2230 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2233 $table = $this->tableName( $table );
2234 $sql = "DELETE FROM $table";
2236 if ( $conds != '*' ) {
2237 if ( is_array( $conds ) ) {
2238 $conds = $this->makeList( $conds, LIST_AND
);
2240 $sql .= ' WHERE ' . $conds;
2243 return $this->query( $sql, $fname );
2246 public function insertSelect(
2247 $destTable, $srcTable, $varMap, $conds,
2248 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2250 if ( $this->cliMode
) {
2251 // For massive migrations with downtime, we don't want to select everything
2252 // into memory and OOM, so do all this native on the server side if possible.
2253 return $this->nativeInsertSelect(
2264 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2265 // on only the master (without needing row-based-replication). It also makes it easy to
2266 // know how big the INSERT is going to be.
2268 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2269 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2271 $selectOptions[] = 'FOR UPDATE';
2272 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2278 foreach ( $res as $row ) {
2279 $rows[] = (array)$row;
2282 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2285 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2286 $fname = __METHOD__
,
2287 $insertOptions = [], $selectOptions = []
2289 $destTable = $this->tableName( $destTable );
2291 if ( !is_array( $insertOptions ) ) {
2292 $insertOptions = [ $insertOptions ];
2295 $insertOptions = $this->makeInsertOptions( $insertOptions );
2297 if ( !is_array( $selectOptions ) ) {
2298 $selectOptions = [ $selectOptions ];
2301 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2304 if ( is_array( $srcTable ) ) {
2305 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2307 $srcTable = $this->tableName( $srcTable );
2310 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2311 " SELECT $startOpts " . implode( ',', $varMap ) .
2312 " FROM $srcTable $useIndex $ignoreIndex ";
2314 if ( $conds != '*' ) {
2315 if ( is_array( $conds ) ) {
2316 $conds = $this->makeList( $conds, LIST_AND
);
2318 $sql .= " WHERE $conds";
2321 $sql .= " $tailOpts";
2323 return $this->query( $sql, $fname );
2327 * Construct a LIMIT query with optional offset. This is used for query
2328 * pages. The SQL should be adjusted so that only the first $limit rows
2329 * are returned. If $offset is provided as well, then the first $offset
2330 * rows should be discarded, and the next $limit rows should be returned.
2331 * If the result of the query is not ordered, then the rows to be returned
2332 * are theoretically arbitrary.
2334 * $sql is expected to be a SELECT, if that makes a difference.
2336 * The version provided by default works in MySQL and SQLite. It will very
2337 * likely need to be overridden for most other DBMSes.
2339 * @param string $sql SQL query we will append the limit too
2340 * @param int $limit The SQL limit
2341 * @param int|bool $offset The SQL offset (default false)
2342 * @throws DBUnexpectedError
2345 public function limitResult( $sql, $limit, $offset = false ) {
2346 if ( !is_numeric( $limit ) ) {
2347 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2350 return "$sql LIMIT "
2351 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2355 public function unionSupportsOrderAndLimit() {
2356 return true; // True for almost every DB supported
2359 public function unionQueries( $sqls, $all ) {
2360 $glue = $all ?
') UNION ALL (' : ') UNION (';
2362 return '(' . implode( $glue, $sqls ) . ')';
2365 public function conditional( $cond, $trueVal, $falseVal ) {
2366 if ( is_array( $cond ) ) {
2367 $cond = $this->makeList( $cond, LIST_AND
);
2370 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2373 public function strreplace( $orig, $old, $new ) {
2374 return "REPLACE({$orig}, {$old}, {$new})";
2377 public function getServerUptime() {
2381 public function wasDeadlock() {
2385 public function wasLockTimeout() {
2389 public function wasErrorReissuable() {
2393 public function wasReadOnlyError() {
2398 * Determines if the given query error was a connection drop
2401 * @param integer|string $errno
2404 public function wasConnectionError( $errno ) {
2409 * Perform a deadlock-prone transaction.
2411 * This function invokes a callback function to perform a set of write
2412 * queries. If a deadlock occurs during the processing, the transaction
2413 * will be rolled back and the callback function will be called again.
2415 * Avoid using this method outside of Job or Maintenance classes.
2418 * $dbw->deadlockLoop( callback, ... );
2420 * Extra arguments are passed through to the specified callback function.
2421 * This method requires that no transactions are already active to avoid
2422 * causing premature commits or exceptions.
2424 * Returns whatever the callback function returned on its successful,
2425 * iteration, or false on error, for example if the retry limit was
2429 * @throws DBUnexpectedError
2432 public function deadlockLoop() {
2433 $args = func_get_args();
2434 $function = array_shift( $args );
2435 $tries = self
::DEADLOCK_TRIES
;
2437 $this->begin( __METHOD__
);
2440 /** @var Exception $e */
2444 $retVal = call_user_func_array( $function, $args );
2446 } catch ( DBQueryError
$e ) {
2447 if ( $this->wasDeadlock() ) {
2448 // Retry after a randomized delay
2449 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2451 // Throw the error back up
2455 } while ( --$tries > 0 );
2457 if ( $tries <= 0 ) {
2458 // Too many deadlocks; give up
2459 $this->rollback( __METHOD__
);
2462 $this->commit( __METHOD__
);
2468 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2469 # Real waits are implemented in the subclass.
2473 public function getSlavePos() {
2478 public function getMasterPos() {
2483 public function serverIsReadOnly() {
2487 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2488 if ( !$this->mTrxLevel
) {
2489 throw new DBUnexpectedError( $this, "No transaction is active." );
2491 $this->mTrxEndCallbacks
[] = [ $callback, $fname ];
2494 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2495 $this->mTrxIdleCallbacks
[] = [ $callback, $fname ];
2496 if ( !$this->mTrxLevel
) {
2497 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2501 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2502 if ( $this->mTrxLevel
) {
2503 $this->mTrxPreCommitCallbacks
[] = [ $callback, $fname ];
2505 // If no transaction is active, then make one for this callback
2506 $this->startAtomic( __METHOD__
);
2508 call_user_func( $callback );
2509 $this->endAtomic( __METHOD__
);
2510 } catch ( Exception
$e ) {
2511 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2517 final public function setTransactionListener( $name, callable
$callback = null ) {
2519 $this->mTrxRecurringCallbacks
[$name] = $callback;
2521 unset( $this->mTrxRecurringCallbacks
[$name] );
2526 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2528 * This method should not be used outside of Database/LoadBalancer
2530 * @param bool $suppress
2533 final public function setTrxEndCallbackSuppression( $suppress ) {
2534 $this->mTrxEndCallbacksSuppressed
= $suppress;
2538 * Actually run and consume any "on transaction idle/resolution" callbacks.
2540 * This method should not be used outside of Database/LoadBalancer
2542 * @param integer $trigger IDatabase::TRIGGER_* constant
2546 public function runOnTransactionIdleCallbacks( $trigger ) {
2547 if ( $this->mTrxEndCallbacksSuppressed
) {
2551 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2552 /** @var Exception $e */
2553 $e = null; // first exception
2554 do { // callbacks may add callbacks :)
2555 $callbacks = array_merge(
2556 $this->mTrxIdleCallbacks
,
2557 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2559 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2560 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2561 foreach ( $callbacks as $callback ) {
2563 list( $phpCallback ) = $callback;
2564 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2565 call_user_func_array( $phpCallback, [ $trigger ] );
2567 $this->setFlag( DBO_TRX
); // restore automatic begin()
2569 $this->clearFlag( DBO_TRX
); // restore auto-commit
2571 } catch ( Exception
$ex ) {
2572 call_user_func( $this->errorLogger
, $ex );
2574 // Some callbacks may use startAtomic/endAtomic, so make sure
2575 // their transactions are ended so other callbacks don't fail
2576 if ( $this->trxLevel() ) {
2577 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2581 } while ( count( $this->mTrxIdleCallbacks
) );
2583 if ( $e instanceof Exception
) {
2584 throw $e; // re-throw any first exception
2589 * Actually run and consume any "on transaction pre-commit" callbacks.
2591 * This method should not be used outside of Database/LoadBalancer
2596 public function runOnTransactionPreCommitCallbacks() {
2597 $e = null; // first exception
2598 do { // callbacks may add callbacks :)
2599 $callbacks = $this->mTrxPreCommitCallbacks
;
2600 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2601 foreach ( $callbacks as $callback ) {
2603 list( $phpCallback ) = $callback;
2604 call_user_func( $phpCallback );
2605 } catch ( Exception
$ex ) {
2606 call_user_func( $this->errorLogger
, $ex );
2610 } while ( count( $this->mTrxPreCommitCallbacks
) );
2612 if ( $e instanceof Exception
) {
2613 throw $e; // re-throw any first exception
2618 * Actually run any "transaction listener" callbacks.
2620 * This method should not be used outside of Database/LoadBalancer
2622 * @param integer $trigger IDatabase::TRIGGER_* constant
2626 public function runTransactionListenerCallbacks( $trigger ) {
2627 if ( $this->mTrxEndCallbacksSuppressed
) {
2631 /** @var Exception $e */
2632 $e = null; // first exception
2634 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2636 $phpCallback( $trigger, $this );
2637 } catch ( Exception
$ex ) {
2638 call_user_func( $this->errorLogger
, $ex );
2643 if ( $e instanceof Exception
) {
2644 throw $e; // re-throw any first exception
2648 final public function startAtomic( $fname = __METHOD__
) {
2649 if ( !$this->mTrxLevel
) {
2650 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2651 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2652 // in all changes being in one transaction to keep requests transactional.
2653 if ( !$this->getFlag( DBO_TRX
) ) {
2654 $this->mTrxAutomaticAtomic
= true;
2658 $this->mTrxAtomicLevels
[] = $fname;
2661 final public function endAtomic( $fname = __METHOD__
) {
2662 if ( !$this->mTrxLevel
) {
2663 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2665 if ( !$this->mTrxAtomicLevels ||
2666 array_pop( $this->mTrxAtomicLevels
) !== $fname
2668 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2671 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2672 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2676 final public function doAtomicSection( $fname, callable
$callback ) {
2677 $this->startAtomic( $fname );
2679 $res = call_user_func_array( $callback, [ $this, $fname ] );
2680 } catch ( Exception
$e ) {
2681 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2684 $this->endAtomic( $fname );
2689 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2690 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2691 if ( $this->mTrxLevel
) {
2692 if ( $this->mTrxAtomicLevels
) {
2693 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2694 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2695 throw new DBUnexpectedError( $this, $msg );
2696 } elseif ( !$this->mTrxAutomatic
) {
2697 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2698 throw new DBUnexpectedError( $this, $msg );
2700 // @TODO: make this an exception at some point
2701 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2702 $this->queryLogger
->error( $msg );
2703 return; // join the main transaction set
2705 } elseif ( $this->getFlag( DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2706 // @TODO: make this an exception at some point
2707 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2708 $this->queryLogger
->error( $msg );
2709 return; // let any writes be in the main transaction
2712 // Avoid fatals if close() was called
2713 $this->assertOpen();
2715 $this->doBegin( $fname );
2716 $this->mTrxTimestamp
= microtime( true );
2717 $this->mTrxFname
= $fname;
2718 $this->mTrxDoneWrites
= false;
2719 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2720 $this->mTrxAutomaticAtomic
= false;
2721 $this->mTrxAtomicLevels
= [];
2722 $this->mTrxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2723 $this->mTrxWriteDuration
= 0.0;
2724 $this->mTrxWriteQueryCount
= 0;
2725 $this->mTrxWriteAdjDuration
= 0.0;
2726 $this->mTrxWriteAdjQueryCount
= 0;
2727 $this->mTrxWriteCallers
= [];
2728 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2729 // Get an estimate of the replica DB lag before then, treating estimate staleness
2730 // as lag itself just to be safe
2731 $status = $this->getApproximateLagStatus();
2732 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2736 * Issues the BEGIN command to the database server.
2738 * @see DatabaseBase::begin()
2739 * @param string $fname
2741 protected function doBegin( $fname ) {
2742 $this->query( 'BEGIN', $fname );
2743 $this->mTrxLevel
= 1;
2746 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2747 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2748 // There are still atomic sections open. This cannot be ignored
2749 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2750 throw new DBUnexpectedError(
2752 "$fname: Got COMMIT while atomic sections $levels are still open."
2756 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2757 if ( !$this->mTrxLevel
) {
2758 return; // nothing to do
2759 } elseif ( !$this->mTrxAutomatic
) {
2760 throw new DBUnexpectedError(
2762 "$fname: Flushing an explicit transaction, getting out of sync."
2766 if ( !$this->mTrxLevel
) {
2767 $this->queryLogger
->error( "$fname: No transaction to commit, something got out of sync." );
2768 return; // nothing to do
2769 } elseif ( $this->mTrxAutomatic
) {
2770 // @TODO: make this an exception at some point
2771 $msg = "$fname: Explicit commit of implicit transaction.";
2772 $this->queryLogger
->error( $msg );
2773 return; // wait for the main transaction set commit round
2777 // Avoid fatals if close() was called
2778 $this->assertOpen();
2780 $this->runOnTransactionPreCommitCallbacks();
2781 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2782 $this->doCommit( $fname );
2783 if ( $this->mTrxDoneWrites
) {
2784 $this->mDoneWrites
= microtime( true );
2785 $this->trxProfiler
->transactionWritingOut(
2786 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2789 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2790 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
2794 * Issues the COMMIT command to the database server.
2796 * @see DatabaseBase::commit()
2797 * @param string $fname
2799 protected function doCommit( $fname ) {
2800 if ( $this->mTrxLevel
) {
2801 $this->query( 'COMMIT', $fname );
2802 $this->mTrxLevel
= 0;
2806 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2807 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2808 if ( !$this->mTrxLevel
) {
2809 return; // nothing to do
2812 if ( !$this->mTrxLevel
) {
2813 $this->queryLogger
->error(
2814 "$fname: No transaction to rollback, something got out of sync." );
2815 return; // nothing to do
2816 } elseif ( $this->getFlag( DBO_TRX
) ) {
2817 throw new DBUnexpectedError(
2819 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2824 // Avoid fatals if close() was called
2825 $this->assertOpen();
2827 $this->doRollback( $fname );
2828 $this->mTrxAtomicLevels
= [];
2829 if ( $this->mTrxDoneWrites
) {
2830 $this->trxProfiler
->transactionWritingOut(
2831 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
2834 $this->mTrxIdleCallbacks
= []; // clear
2835 $this->mTrxPreCommitCallbacks
= []; // clear
2836 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
2837 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
2841 * Issues the ROLLBACK command to the database server.
2843 * @see DatabaseBase::rollback()
2844 * @param string $fname
2846 protected function doRollback( $fname ) {
2847 if ( $this->mTrxLevel
) {
2848 # Disconnects cause rollback anyway, so ignore those errors
2849 $ignoreErrors = true;
2850 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
2851 $this->mTrxLevel
= 0;
2855 public function flushSnapshot( $fname = __METHOD__
) {
2856 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
2857 // This only flushes transactions to clear snapshots, not to write data
2858 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
2859 throw new DBUnexpectedError(
2861 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
2865 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2868 public function explicitTrxActive() {
2869 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
2873 * Creates a new table with structure copied from existing table
2874 * Note that unlike most database abstraction functions, this function does not
2875 * automatically append database prefix, because it works at a lower
2876 * abstraction level.
2877 * The table names passed to this function shall not be quoted (this
2878 * function calls addIdentifierQuotes when needed).
2880 * @param string $oldName Name of table whose structure should be copied
2881 * @param string $newName Name of table to be created
2882 * @param bool $temporary Whether the new table should be temporary
2883 * @param string $fname Calling function name
2884 * @throws RuntimeException
2885 * @return bool True if operation was successful
2887 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
2890 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2893 function listTables( $prefix = null, $fname = __METHOD__
) {
2894 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2898 * Reset the views process cache set by listViews()
2901 final public function clearViewsCache() {
2902 $this->allViews
= null;
2906 * Lists all the VIEWs in the database
2908 * For caching purposes the list of all views should be stored in
2909 * $this->allViews. The process cache can be cleared with clearViewsCache()
2911 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
2912 * @param string $fname Name of calling function
2913 * @throws RuntimeException
2917 public function listViews( $prefix = null, $fname = __METHOD__
) {
2918 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2922 * Differentiates between a TABLE and a VIEW
2924 * @param string $name Name of the database-structure to test.
2925 * @throws RuntimeException
2929 public function isView( $name ) {
2930 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2933 public function timestamp( $ts = 0 ) {
2934 $t = new ConvertableTimestamp( $ts );
2935 // Let errors bubble up to avoid putting garbage in the DB
2936 return $t->getTimestamp( TS_MW
);
2939 public function timestampOrNull( $ts = null ) {
2940 if ( is_null( $ts ) ) {
2943 return $this->timestamp( $ts );
2948 * Take the result from a query, and wrap it in a ResultWrapper if
2949 * necessary. Boolean values are passed through as is, to indicate success
2950 * of write queries or failure.
2952 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2953 * resource, and it was necessary to call this function to convert it to
2954 * a wrapper. Nowadays, raw database objects are never exposed to external
2955 * callers, so this is unnecessary in external code.
2957 * @param bool|ResultWrapper|resource|object $result
2958 * @return bool|ResultWrapper
2960 protected function resultObject( $result ) {
2963 } elseif ( $result instanceof ResultWrapper
) {
2965 } elseif ( $result === true ) {
2966 // Successful write query
2969 return new ResultWrapper( $this, $result );
2973 public function ping( &$rtt = null ) {
2974 // Avoid hitting the server if it was hit recently
2975 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
2976 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
2977 $rtt = $this->mRTTEstimate
;
2978 return true; // don't care about $rtt
2982 // This will reconnect if possible or return false if not
2983 $this->clearFlag( DBO_TRX
, self
::REMEMBER_PRIOR
);
2984 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
2985 $this->restoreFlags( self
::RESTORE_PRIOR
);
2988 $rtt = $this->mRTTEstimate
;
2997 protected function reconnect() {
2998 $this->closeConnection();
2999 $this->mOpened
= false;
3000 $this->mConn
= false;
3002 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3003 $this->lastPing
= microtime( true );
3005 } catch ( DBConnectionError
$e ) {
3012 public function getSessionLagStatus() {
3013 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3017 * Get the replica DB lag when the current transaction started
3019 * This is useful when transactions might use snapshot isolation
3020 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3021 * is this lag plus transaction duration. If they don't, it is still
3022 * safe to be pessimistic. This returns null if there is no transaction.
3024 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3027 public function getTransactionLagStatus() {
3028 return $this->mTrxLevel
3029 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3034 * Get a replica DB lag estimate for this server
3036 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3039 public function getApproximateLagStatus() {
3041 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3042 'since' => microtime( true )
3047 * Merge the result of getSessionLagStatus() for several DBs
3048 * using the most pessimistic values to estimate the lag of
3049 * any data derived from them in combination
3051 * This is information is useful for caching modules
3053 * @see WANObjectCache::set()
3054 * @see WANObjectCache::getWithSetCallback()
3056 * @param IDatabase $db1
3057 * @param IDatabase ...
3058 * @return array Map of values:
3059 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3060 * - since: oldest UNIX timestamp of any of the DB lag estimates
3061 * - pending: whether any of the DBs have uncommitted changes
3064 public static function getCacheSetOptions( IDatabase
$db1 ) {
3065 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3066 foreach ( func_get_args() as $db ) {
3067 /** @var IDatabase $db */
3068 $status = $db->getSessionLagStatus();
3069 if ( $status['lag'] === false ) {
3070 $res['lag'] = false;
3071 } elseif ( $res['lag'] !== false ) {
3072 $res['lag'] = max( $res['lag'], $status['lag'] );
3074 $res['since'] = min( $res['since'], $status['since'] );
3075 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3081 public function getLag() {
3085 function maxListLen() {
3089 public function encodeBlob( $b ) {
3093 public function decodeBlob( $b ) {
3094 if ( $b instanceof Blob
) {
3100 public function setSessionOptions( array $options ) {
3104 * Read and execute SQL commands from a file.
3106 * Returns true on success, error string or exception on failure (depending
3107 * on object's error ignore settings).
3109 * @param string $filename File name to open
3110 * @param bool|callable $lineCallback Optional function called before reading each line
3111 * @param bool|callable $resultCallback Optional function called for each MySQL result
3112 * @param bool|string $fname Calling function name or false if name should be
3113 * generated dynamically using $filename
3114 * @param bool|callable $inputCallback Optional function called for each
3115 * complete line sent
3116 * @return bool|string
3119 public function sourceFile(
3120 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3122 MediaWiki\
suppressWarnings();
3123 $fp = fopen( $filename, 'r' );
3124 MediaWiki\restoreWarnings
();
3126 if ( false === $fp ) {
3127 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3131 $fname = __METHOD__
. "( $filename )";
3135 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3136 } catch ( Exception
$e ) {
3146 public function setSchemaVars( $vars ) {
3147 $this->mSchemaVars
= $vars;
3151 * Read and execute commands from an open file handle.
3153 * Returns true on success, error string or exception on failure (depending
3154 * on object's error ignore settings).
3156 * @param resource $fp File handle
3157 * @param bool|callable $lineCallback Optional function called before reading each query
3158 * @param bool|callable $resultCallback Optional function called for each MySQL result
3159 * @param string $fname Calling function name
3160 * @param bool|callable $inputCallback Optional function called for each complete query sent
3161 * @return bool|string
3163 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3164 $fname = __METHOD__
, $inputCallback = false
3168 while ( !feof( $fp ) ) {
3169 if ( $lineCallback ) {
3170 call_user_func( $lineCallback );
3173 $line = trim( fgets( $fp ) );
3175 if ( $line == '' ) {
3179 if ( '-' == $line[0] && '-' == $line[1] ) {
3187 $done = $this->streamStatementEnd( $cmd, $line );
3191 if ( $done ||
feof( $fp ) ) {
3192 $cmd = $this->replaceVars( $cmd );
3194 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3195 $res = $this->query( $cmd, $fname );
3197 if ( $resultCallback ) {
3198 call_user_func( $resultCallback, $res, $this );
3201 if ( false === $res ) {
3202 $err = $this->lastError();
3204 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3215 * Called by sourceStream() to check if we've reached a statement end
3217 * @param string $sql SQL assembled so far
3218 * @param string $newLine New line about to be added to $sql
3219 * @return bool Whether $newLine contains end of the statement
3221 public function streamStatementEnd( &$sql, &$newLine ) {
3222 if ( $this->delimiter
) {
3224 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3225 if ( $newLine != $prev ) {
3234 * Database independent variable replacement. Replaces a set of variables
3235 * in an SQL statement with their contents as given by $this->getSchemaVars().
3237 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3239 * - '{$var}' should be used for text and is passed through the database's
3241 * - `{$var}` should be used for identifiers (e.g. table and database names).
3242 * It is passed through the database's addIdentifierQuotes method which
3243 * can be overridden if the database uses something other than backticks.
3244 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3245 * database's tableName method.
3246 * - / *i* / passes the name that follows through the database's indexName method.
3247 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3248 * its use should be avoided. In 1.24 and older, string encoding was applied.
3250 * @param string $ins SQL statement to replace variables in
3251 * @return string The new SQL statement with variables replaced
3253 protected function replaceVars( $ins ) {
3254 $vars = $this->getSchemaVars();
3255 return preg_replace_callback(
3257 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3258 \'\{\$ (\w+) }\' | # 3. addQuotes
3259 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3260 /\*\$ (\w+) \*/ # 5. leave unencoded
3262 function ( $m ) use ( $vars ) {
3263 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3264 // check for both nonexistent keys *and* the empty string.
3265 if ( isset( $m[1] ) && $m[1] !== '' ) {
3266 if ( $m[1] === 'i' ) {
3267 return $this->indexName( $m[2] );
3269 return $this->tableName( $m[2] );
3271 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3272 return $this->addQuotes( $vars[$m[3]] );
3273 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3274 return $this->addIdentifierQuotes( $vars[$m[4]] );
3275 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3276 return $vars[$m[5]];
3286 * Get schema variables. If none have been set via setSchemaVars(), then
3287 * use some defaults from the current object.
3291 protected function getSchemaVars() {
3292 if ( $this->mSchemaVars
) {
3293 return $this->mSchemaVars
;
3295 return $this->getDefaultSchemaVars();
3300 * Get schema variables to use if none have been set via setSchemaVars().
3302 * Override this in derived classes to provide variables for tables.sql
3303 * and SQL patch files.
3307 protected function getDefaultSchemaVars() {
3311 public function lockIsFree( $lockName, $method ) {
3315 public function lock( $lockName, $method, $timeout = 5 ) {
3316 $this->mNamedLocksHeld
[$lockName] = 1;
3321 public function unlock( $lockName, $method ) {
3322 unset( $this->mNamedLocksHeld
[$lockName] );
3327 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3328 if ( $this->writesOrCallbacksPending() ) {
3329 // This only flushes transactions to clear snapshots, not to write data
3330 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3331 throw new DBUnexpectedError(
3333 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
3337 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3341 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3342 if ( $this->trxLevel() ) {
3343 // There is a good chance an exception was thrown, causing any early return
3344 // from the caller. Let any error handler get a chance to issue rollback().
3345 // If there isn't one, let the error bubble up and trigger server-side rollback.
3346 $this->onTransactionResolution(
3347 function () use ( $lockKey, $fname ) {
3348 $this->unlock( $lockKey, $fname );
3353 $this->unlock( $lockKey, $fname );
3357 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3362 public function namedLocksEnqueue() {
3367 * Lock specific tables
3369 * @param array $read Array of tables to lock for read access
3370 * @param array $write Array of tables to lock for write access
3371 * @param string $method Name of caller
3372 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3375 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3380 * Unlock specific tables
3382 * @param string $method The caller
3385 public function unlockTables( $method ) {
3391 * @param string $tableName
3392 * @param string $fName
3393 * @return bool|ResultWrapper
3396 public function dropTable( $tableName, $fName = __METHOD__
) {
3397 if ( !$this->tableExists( $tableName, $fName ) ) {
3400 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3402 return $this->query( $sql, $fName );
3405 public function getInfinity() {
3409 public function encodeExpiry( $expiry ) {
3410 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3411 ?
$this->getInfinity()
3412 : $this->timestamp( $expiry );
3415 public function decodeExpiry( $expiry, $format = TS_MW
) {
3416 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3421 $t = new ConvertableTimestamp( $expiry );
3423 return $t->getTimestamp( $format );
3424 } catch ( TimestampException
$e ) {
3429 public function setBigSelects( $value = true ) {
3433 public function isReadOnly() {
3434 return ( $this->getReadOnlyReason() !== false );
3438 * @return string|bool Reason this DB is read-only or false if it is not
3440 protected function getReadOnlyReason() {
3441 $reason = $this->getLBInfo( 'readOnlyReason' );
3443 return is_string( $reason ) ?
$reason : false;
3446 public function setTableAliases( array $aliases ) {
3447 $this->tableAliases
= $aliases;
3454 public function __toString() {
3455 return (string)$this->mConn
;
3459 * Called by serialize. Throw an exception when DB connection is serialized.
3460 * This causes problems on some database engines because the connection is
3461 * not restored on unserialize.
3463 public function __sleep() {
3464 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3465 'the connection is not restored on wakeup.' );
3469 * Run a few simple sanity checks
3471 public function __destruct() {
3472 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3473 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3476 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3477 if ( $danglingWriters ) {
3478 $fnames = implode( ', ', $danglingWriters );
3479 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );