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 = [];
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'] )
278 ?
$params['profiler']
279 : Profiler
::instance(); // @TODO: remove global state
280 $this->trxProfiler
= isset( $params['trxProfiler'] )
281 ?
$params['trxProfiler']
282 : new TransactionProfiler();
283 $this->connLogger
= isset( $params['connLogger'] )
284 ?
$params['connLogger']
285 : new \Psr\Log\
NullLogger();
286 $this->queryLogger
= isset( $params['queryLogger'] )
287 ?
$params['queryLogger']
288 : new \Psr\Log\
NullLogger();
291 $this->open( $server, $user, $password, $dbName );
294 $this->currentDomain
= ( $this->mDBname
!= '' )
295 ?
new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
)
296 : DatabaseDomain
::newUnspecified();
300 * Given a DB type, construct the name of the appropriate child class of
301 * IDatabase. This is designed to replace all of the manual stuff like:
302 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
303 * as well as validate against the canonical list of DB types we have
305 * This factory function is mostly useful for when you need to connect to a
306 * database other than the MediaWiki default (such as for external auth,
307 * an extension, et cetera). Do not use this to connect to the MediaWiki
308 * database. Example uses in core:
309 * @see LoadBalancer::reallyOpenConnection()
310 * @see ForeignDBRepo::getMasterDB()
311 * @see WebInstallerDBConnect::execute()
315 * @param string $dbType A possible DB type
316 * @param array $p An array of options to pass to the constructor.
317 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
318 * @return IDatabase|null If the database driver or extension cannot be found
319 * @throws InvalidArgumentException If the database driver or extension cannot be found
321 final public static function factory( $dbType, $p = [] ) {
322 $canonicalDBTypes = [
323 'mysql' => [ 'mysqli', 'mysql' ],
331 $dbType = strtolower( $dbType );
332 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
333 $possibleDrivers = $canonicalDBTypes[$dbType];
334 if ( !empty( $p['driver'] ) ) {
335 if ( in_array( $p['driver'], $possibleDrivers ) ) {
336 $driver = $p['driver'];
338 throw new InvalidArgumentException( __METHOD__
.
339 " type '$dbType' does not support driver '{$p['driver']}'" );
342 foreach ( $possibleDrivers as $posDriver ) {
343 if ( extension_loaded( $posDriver ) ) {
344 $driver = $posDriver;
352 if ( $driver === false ) {
353 throw new InvalidArgumentException( __METHOD__
.
354 " no viable database extension found for type '$dbType'" );
357 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
358 // and everything else doesn't use a schema (e.g. null)
359 // Although postgres and oracle support schemas, we don't use them (yet)
360 // to maintain backwards compatibility
362 'mssql' => 'get from global',
365 $class = 'Database' . ucfirst( $driver );
366 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
367 // Resolve some defaults for b/c
368 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
369 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
370 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
371 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
372 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
373 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
374 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
375 if ( !isset( $p['schema'] ) ) {
376 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : '';
378 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
380 $conn = new $class( $p );
381 if ( isset( $p['connLogger'] ) ) {
382 $conn->connLogger
= $p['connLogger'];
384 if ( isset( $p['queryLogger'] ) ) {
385 $conn->queryLogger
= $p['queryLogger'];
387 if ( isset( $p['errorLogger'] ) ) {
388 $conn->errorLogger
= $p['errorLogger'];
390 $conn->errorLogger
= function ( Exception
$e ) {
391 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_WARNING
);
401 public function setLogger( LoggerInterface
$logger ) {
402 $this->queryLogger
= $logger;
405 public function getServerInfo() {
406 return $this->getServerVersion();
409 public function bufferResults( $buffer = null ) {
410 $res = !$this->getFlag( DBO_NOBUFFER
);
411 if ( $buffer !== null ) {
412 $buffer ?
$this->clearFlag( DBO_NOBUFFER
) : $this->setFlag( DBO_NOBUFFER
);
419 * Turns on (false) or off (true) the automatic generation and sending
420 * of a "we're sorry, but there has been a database error" page on
421 * database errors. Default is on (false). When turned off, the
422 * code should use lastErrno() and lastError() to handle the
423 * situation as appropriate.
425 * Do not use this function outside of the Database classes.
427 * @param null|bool $ignoreErrors
428 * @return bool The previous value of the flag.
430 protected function ignoreErrors( $ignoreErrors = null ) {
431 $res = $this->getFlag( DBO_IGNORE
);
432 if ( $ignoreErrors !== null ) {
433 $ignoreErrors ?
$this->setFlag( DBO_IGNORE
) : $this->clearFlag( DBO_IGNORE
);
439 public function trxLevel() {
440 return $this->mTrxLevel
;
443 public function trxTimestamp() {
444 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
447 public function tablePrefix( $prefix = null ) {
448 $old = $this->mTablePrefix
;
449 if ( $prefix !== null ) {
450 $this->mTablePrefix
= $prefix;
451 $this->currentDomain
= ( $this->mDBname
!= '' )
452 ?
new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
)
453 : DatabaseDomain
::newUnspecified();
459 public function dbSchema( $schema = null ) {
460 $old = $this->mSchema
;
461 if ( $schema !== null ) {
462 $this->mSchema
= $schema;
469 * Set the filehandle to copy write statements to.
471 * @param resource $fh File handle
473 public function setFileHandle( $fh ) {
474 $this->fileHandle
= $fh;
477 public function getLBInfo( $name = null ) {
478 if ( is_null( $name ) ) {
479 return $this->mLBInfo
;
481 if ( array_key_exists( $name, $this->mLBInfo
) ) {
482 return $this->mLBInfo
[$name];
489 public function setLBInfo( $name, $value = null ) {
490 if ( is_null( $value ) ) {
491 $this->mLBInfo
= $name;
493 $this->mLBInfo
[$name] = $value;
497 public function setLazyMasterHandle( IDatabase
$conn ) {
498 $this->lazyMasterHandle
= $conn;
502 * @return IDatabase|null
503 * @see setLazyMasterHandle()
506 public function getLazyMasterHandle() {
507 return $this->lazyMasterHandle
;
511 * @param TransactionProfiler $profiler
514 public function setTransactionProfiler( TransactionProfiler
$profiler ) {
515 $this->trxProfiler
= $profiler;
518 public function implicitGroupby() {
522 public function implicitOrderby() {
526 public function lastQuery() {
527 return $this->mLastQuery
;
530 public function doneWrites() {
531 return (bool)$this->mDoneWrites
;
534 public function lastDoneWrites() {
535 return $this->mDoneWrites ?
: false;
538 public function writesPending() {
539 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
542 public function writesOrCallbacksPending() {
543 return $this->mTrxLevel
&& (
544 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
548 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
549 if ( !$this->mTrxLevel
) {
551 } elseif ( !$this->mTrxDoneWrites
) {
556 case self
::ESTIMATE_DB_APPLY
:
558 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
559 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
560 // For omitted queries, make them count as something at least
561 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
562 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
565 default: // everything
566 return $this->mTrxWriteDuration
;
570 public function pendingWriteCallers() {
571 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
574 protected function pendingWriteAndCallbackCallers() {
575 if ( !$this->mTrxLevel
) {
579 $fnames = $this->mTrxWriteCallers
;
581 $this->mTrxIdleCallbacks
,
582 $this->mTrxPreCommitCallbacks
,
583 $this->mTrxEndCallbacks
585 foreach ( $callbacks as $callback ) {
586 $fnames[] = $callback[1];
593 public function isOpen() {
594 return $this->mOpened
;
597 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
598 if ( $remember === self
::REMEMBER_PRIOR
) {
599 array_push( $this->priorFlags
, $this->mFlags
);
601 $this->mFlags |
= $flag;
604 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
605 if ( $remember === self
::REMEMBER_PRIOR
) {
606 array_push( $this->priorFlags
, $this->mFlags
);
608 $this->mFlags
&= ~
$flag;
611 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
612 if ( !$this->priorFlags
) {
616 if ( $state === self
::RESTORE_INITIAL
) {
617 $this->mFlags
= reset( $this->priorFlags
);
618 $this->priorFlags
= [];
620 $this->mFlags
= array_pop( $this->priorFlags
);
624 public function getFlag( $flag ) {
625 return !!( $this->mFlags
& $flag );
628 public function getProperty( $name ) {
632 public function getDomainID() {
633 return $this->currentDomain
->getId();
636 final public function getWikiID() {
637 return $this->getDomainID();
641 * Get information about an index into an object
642 * @param string $table Table name
643 * @param string $index Index name
644 * @param string $fname Calling function name
645 * @return mixed Database-specific index description class or false if the index does not exist
647 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
650 * Wrapper for addslashes()
652 * @param string $s String to be slashed.
653 * @return string Slashed string.
655 abstract function strencode( $s );
657 protected function installErrorHandler() {
658 $this->mPHPError
= false;
659 $this->htmlErrors
= ini_set( 'html_errors', '0' );
660 set_error_handler( [ $this, 'connectionerrorLogger' ] );
664 * @return bool|string
666 protected function restoreErrorHandler() {
667 restore_error_handler();
668 if ( $this->htmlErrors
!== false ) {
669 ini_set( 'html_errors', $this->htmlErrors
);
671 if ( $this->mPHPError
) {
672 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
673 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
683 * @param string $errstr
685 public function connectionerrorLogger( $errno, $errstr ) {
686 $this->mPHPError
= $errstr;
690 * Create a log context to pass to PSR logging functions.
692 * @param array $extras Additional data to add to context
695 protected function getLogContext( array $extras = [] ) {
698 'db_server' => $this->mServer
,
699 'db_name' => $this->mDBname
,
700 'db_user' => $this->mUser
,
706 public function close() {
707 if ( $this->mConn
) {
708 if ( $this->trxLevel() ) {
709 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
712 $closed = $this->closeConnection();
713 $this->mConn
= false;
714 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
715 throw new RuntimeException( "Transaction callbacks still pending." );
719 $this->mOpened
= false;
725 * Make sure isOpen() returns true as a sanity check
727 * @throws DBUnexpectedError
729 protected function assertOpen() {
730 if ( !$this->isOpen() ) {
731 throw new DBUnexpectedError( $this, "DB connection was already closed." );
736 * Closes underlying database connection
738 * @return bool Whether connection was closed successfully
740 abstract protected function closeConnection();
742 function reportConnectionError( $error = 'Unknown error' ) {
743 $myError = $this->lastError();
749 throw new DBConnectionError( $this, $error );
753 * The DBMS-dependent part of query()
755 * @param string $sql SQL query.
756 * @return ResultWrapper|bool Result object to feed to fetchObject,
757 * fetchRow, ...; or false on failure
759 abstract protected function doQuery( $sql );
762 * Determine whether a query writes to the DB.
763 * Should return true if unsure.
768 protected function isWriteQuery( $sql ) {
770 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
775 * @return string|null
777 protected function getQueryVerb( $sql ) {
778 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
782 * Determine whether a SQL statement is sensitive to isolation level.
783 * A SQL statement is considered transactable if its result could vary
784 * depending on the transaction isolation level. Operational commands
785 * such as 'SET' and 'SHOW' are not considered to be transactable.
790 protected function isTransactableQuery( $sql ) {
791 $verb = $this->getQueryVerb( $sql );
792 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
795 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
796 $priorWritesPending = $this->writesOrCallbacksPending();
797 $this->mLastQuery
= $sql;
799 $isWrite = $this->isWriteQuery( $sql );
801 $reason = $this->getReadOnlyReason();
802 if ( $reason !== false ) {
803 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
805 # Set a flag indicating that writes have been done
806 $this->mDoneWrites
= microtime( true );
809 // Add trace comment to the begin of the sql string, right after the operator.
810 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
811 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
813 # Start implicit transactions that wrap the request if DBO_TRX is enabled
814 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
)
815 && $this->isTransactableQuery( $sql )
817 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
818 $this->mTrxAutomatic
= true;
821 # Keep track of whether the transaction has write queries pending
822 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
823 $this->mTrxDoneWrites
= true;
824 $this->trxProfiler
->transactionWritingIn(
825 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
828 if ( $this->getFlag( DBO_DEBUG
) ) {
829 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
832 # Avoid fatals if close() was called
835 # Send the query to the server
836 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
838 # Try reconnecting if the connection was lost
839 if ( false === $ret && $this->wasErrorReissuable() ) {
840 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
841 # Stash the last error values before anything might clear them
842 $lastError = $this->lastError();
843 $lastErrno = $this->lastErrno();
844 # Update state tracking to reflect transaction loss due to disconnection
845 $this->handleTransactionLoss();
846 if ( $this->reconnect() ) {
847 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
848 $this->connLogger
->warning( $msg );
849 $this->queryLogger
->warning(
850 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
852 if ( !$recoverable ) {
853 # Callers may catch the exception and continue to use the DB
854 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
856 # Should be safe to silently retry the query
857 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
860 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
861 $this->connLogger
->error( $msg );
865 if ( false === $ret ) {
866 # Deadlocks cause the entire transaction to abort, not just the statement.
867 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
868 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
869 if ( $this->wasDeadlock() ) {
870 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
871 $tempIgnore = false; // not recoverable
873 # Update state tracking to reflect transaction loss
874 $this->handleTransactionLoss();
877 $this->reportQueryError(
878 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
881 $res = $this->resultObject( $ret );
886 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
887 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
888 # generalizeSQL() will probably cut down the query to reasonable
889 # logging size most of the time. The substr is really just a sanity check.
891 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
893 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
896 # Include query transaction state
897 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
899 $startTime = microtime( true );
900 $this->profiler
->profileIn( $queryProf );
901 $ret = $this->doQuery( $commentedSql );
902 $this->profiler
->profileOut( $queryProf );
903 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
905 unset( $queryProfSection ); // profile out (if set)
907 if ( $ret !== false ) {
908 $this->lastPing
= $startTime;
909 if ( $isWrite && $this->mTrxLevel
) {
910 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
911 $this->mTrxWriteCallers
[] = $fname;
915 if ( $sql === self
::PING_QUERY
) {
916 $this->mRTTEstimate
= $queryRuntime;
919 $this->trxProfiler
->recordQueryCompletion(
920 $queryProf, $startTime, $isWrite, $this->affectedRows()
922 MWDebug
::query( $sql, $fname, $isMaster, $queryRuntime );
928 * Update the estimated run-time of a query, not counting large row lock times
930 * LoadBalancer can be set to rollback transactions that will create huge replication
931 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
932 * queries, like inserting a row can take a long time due to row locking. This method
933 * uses some simple heuristics to discount those cases.
935 * @param string $sql A SQL write query
936 * @param float $runtime Total runtime, including RTT
938 private function updateTrxWriteQueryTime( $sql, $runtime ) {
939 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
940 $indicativeOfReplicaRuntime = true;
941 if ( $runtime > self
::SLOW_WRITE_SEC
) {
942 $verb = $this->getQueryVerb( $sql );
943 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
944 if ( $verb === 'INSERT' ) {
945 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
946 } elseif ( $verb === 'REPLACE' ) {
947 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
951 $this->mTrxWriteDuration +
= $runtime;
952 $this->mTrxWriteQueryCount +
= 1;
953 if ( $indicativeOfReplicaRuntime ) {
954 $this->mTrxWriteAdjDuration +
= $runtime;
955 $this->mTrxWriteAdjQueryCount +
= 1;
959 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
960 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
961 # Dropped connections also mean that named locks are automatically released.
962 # Only allow error suppression in autocommit mode or when the lost transaction
963 # didn't matter anyway (aside from DBO_TRX snapshot loss).
964 if ( $this->mNamedLocksHeld
) {
965 return false; // possible critical section violation
966 } elseif ( $sql === 'COMMIT' ) {
967 return !$priorWritesPending; // nothing written anyway? (T127428)
968 } elseif ( $sql === 'ROLLBACK' ) {
969 return true; // transaction lost...which is also what was requested :)
970 } elseif ( $this->explicitTrxActive() ) {
971 return false; // don't drop atomocity
972 } elseif ( $priorWritesPending ) {
973 return false; // prior writes lost from implicit transaction
979 private function handleTransactionLoss() {
980 $this->mTrxLevel
= 0;
981 $this->mTrxIdleCallbacks
= []; // bug 65263
982 $this->mTrxPreCommitCallbacks
= []; // bug 65263
984 // Handle callbacks in mTrxEndCallbacks
985 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
986 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
988 } catch ( Exception
$e ) {
989 // Already logged; move on...
994 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
995 if ( $this->ignoreErrors() ||
$tempIgnore ) {
996 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
998 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
999 $this->queryLogger
->error(
1000 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1001 $this->getLogContext( [
1002 'method' => __METHOD__
,
1005 'sql1line' => $sql1line,
1009 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1010 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1014 public function freeResult( $res ) {
1017 public function selectField(
1018 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1020 if ( $var === '*' ) { // sanity
1021 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1024 if ( !is_array( $options ) ) {
1025 $options = [ $options ];
1028 $options['LIMIT'] = 1;
1030 $res = $this->select( $table, $var, $cond, $fname, $options );
1031 if ( $res === false ||
!$this->numRows( $res ) ) {
1035 $row = $this->fetchRow( $res );
1037 if ( $row !== false ) {
1038 return reset( $row );
1044 public function selectFieldValues(
1045 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1047 if ( $var === '*' ) { // sanity
1048 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1049 } elseif ( !is_string( $var ) ) { // sanity
1050 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1053 if ( !is_array( $options ) ) {
1054 $options = [ $options ];
1057 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1058 if ( $res === false ) {
1063 foreach ( $res as $row ) {
1064 $values[] = $row->$var;
1071 * Returns an optional USE INDEX clause to go after the table, and a
1072 * string to go at the end of the query.
1074 * @param array $options Associative array of options to be turned into
1075 * an SQL query, valid keys are listed in the function.
1077 * @see DatabaseBase::select()
1079 public function makeSelectOptions( $options ) {
1080 $preLimitTail = $postLimitTail = '';
1085 foreach ( $options as $key => $option ) {
1086 if ( is_numeric( $key ) ) {
1087 $noKeyOptions[$option] = true;
1091 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1093 $preLimitTail .= $this->makeOrderBy( $options );
1095 // if (isset($options['LIMIT'])) {
1096 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1097 // isset($options['OFFSET']) ? $options['OFFSET']
1101 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1102 $postLimitTail .= ' FOR UPDATE';
1105 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1106 $postLimitTail .= ' LOCK IN SHARE MODE';
1109 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1110 $startOpts .= 'DISTINCT';
1113 # Various MySQL extensions
1114 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1115 $startOpts .= ' /*! STRAIGHT_JOIN */';
1118 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1119 $startOpts .= ' HIGH_PRIORITY';
1122 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1123 $startOpts .= ' SQL_BIG_RESULT';
1126 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1127 $startOpts .= ' SQL_BUFFER_RESULT';
1130 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1131 $startOpts .= ' SQL_SMALL_RESULT';
1134 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1135 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1138 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1139 $startOpts .= ' SQL_CACHE';
1142 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1143 $startOpts .= ' SQL_NO_CACHE';
1146 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1147 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1151 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1152 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1157 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1161 * Returns an optional GROUP BY with an optional HAVING
1163 * @param array $options Associative array of options
1165 * @see DatabaseBase::select()
1168 public function makeGroupByWithHaving( $options ) {
1170 if ( isset( $options['GROUP BY'] ) ) {
1171 $gb = is_array( $options['GROUP BY'] )
1172 ?
implode( ',', $options['GROUP BY'] )
1173 : $options['GROUP BY'];
1174 $sql .= ' GROUP BY ' . $gb;
1176 if ( isset( $options['HAVING'] ) ) {
1177 $having = is_array( $options['HAVING'] )
1178 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1179 : $options['HAVING'];
1180 $sql .= ' HAVING ' . $having;
1187 * Returns an optional ORDER BY
1189 * @param array $options Associative array of options
1191 * @see DatabaseBase::select()
1194 public function makeOrderBy( $options ) {
1195 if ( isset( $options['ORDER BY'] ) ) {
1196 $ob = is_array( $options['ORDER BY'] )
1197 ?
implode( ',', $options['ORDER BY'] )
1198 : $options['ORDER BY'];
1200 return ' ORDER BY ' . $ob;
1206 // See IDatabase::select for the docs for this function
1207 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1208 $options = [], $join_conds = [] ) {
1209 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1211 return $this->query( $sql, $fname );
1214 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1215 $options = [], $join_conds = []
1217 if ( is_array( $vars ) ) {
1218 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1221 $options = (array)$options;
1222 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1223 ?
$options['USE INDEX']
1225 $ignoreIndexes = ( isset( $options['IGNORE INDEX'] ) && is_array( $options['IGNORE INDEX'] ) )
1226 ?
$options['IGNORE INDEX']
1229 if ( is_array( $table ) ) {
1231 $this->tableNamesWithIndexClauseOrJOIN( $table, $useIndexes, $ignoreIndexes, $join_conds );
1232 } elseif ( $table != '' ) {
1233 if ( $table[0] == ' ' ) {
1234 $from = ' FROM ' . $table;
1237 $this->tableNamesWithIndexClauseOrJOIN( [ $table ], $useIndexes, $ignoreIndexes, [] );
1243 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1244 $this->makeSelectOptions( $options );
1246 if ( !empty( $conds ) ) {
1247 if ( is_array( $conds ) ) {
1248 $conds = $this->makeList( $conds, LIST_AND
);
1250 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex WHERE $conds $preLimitTail";
1252 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1255 if ( isset( $options['LIMIT'] ) ) {
1256 $sql = $this->limitResult( $sql, $options['LIMIT'],
1257 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1259 $sql = "$sql $postLimitTail";
1261 if ( isset( $options['EXPLAIN'] ) ) {
1262 $sql = 'EXPLAIN ' . $sql;
1268 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1269 $options = [], $join_conds = []
1271 $options = (array)$options;
1272 $options['LIMIT'] = 1;
1273 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1275 if ( $res === false ) {
1279 if ( !$this->numRows( $res ) ) {
1283 $obj = $this->fetchObject( $res );
1288 public function estimateRowCount(
1289 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1292 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1295 $row = $this->fetchRow( $res );
1296 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1302 public function selectRowCount(
1303 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1306 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1307 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1310 $row = $this->fetchRow( $res );
1311 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1318 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1319 * It's only slightly flawed. Don't use for anything important.
1321 * @param string $sql A SQL Query
1325 protected static function generalizeSQL( $sql ) {
1326 # This does the same as the regexp below would do, but in such a way
1327 # as to avoid crashing php on some large strings.
1328 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1330 $sql = str_replace( "\\\\", '', $sql );
1331 $sql = str_replace( "\\'", '', $sql );
1332 $sql = str_replace( "\\\"", '', $sql );
1333 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1334 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1336 # All newlines, tabs, etc replaced by single space
1337 $sql = preg_replace( '/\s+/', ' ', $sql );
1340 # except the ones surrounded by characters, e.g. l10n
1341 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1342 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1347 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1348 $info = $this->fieldInfo( $table, $field );
1353 public function indexExists( $table, $index, $fname = __METHOD__
) {
1354 if ( !$this->tableExists( $table ) ) {
1358 $info = $this->indexInfo( $table, $index, $fname );
1359 if ( is_null( $info ) ) {
1362 return $info !== false;
1366 public function tableExists( $table, $fname = __METHOD__
) {
1367 $table = $this->tableName( $table );
1368 $old = $this->ignoreErrors( true );
1369 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1370 $this->ignoreErrors( $old );
1375 public function indexUnique( $table, $index ) {
1376 $indexInfo = $this->indexInfo( $table, $index );
1378 if ( !$indexInfo ) {
1382 return !$indexInfo[0]->Non_unique
;
1386 * Helper for DatabaseBase::insert().
1388 * @param array $options
1391 protected function makeInsertOptions( $options ) {
1392 return implode( ' ', $options );
1395 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1396 # No rows to insert, easy just return now
1397 if ( !count( $a ) ) {
1401 $table = $this->tableName( $table );
1403 if ( !is_array( $options ) ) {
1404 $options = [ $options ];
1408 if ( isset( $options['fileHandle'] ) ) {
1409 $fh = $options['fileHandle'];
1411 $options = $this->makeInsertOptions( $options );
1413 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1415 $keys = array_keys( $a[0] );
1418 $keys = array_keys( $a );
1421 $sql = 'INSERT ' . $options .
1422 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1426 foreach ( $a as $row ) {
1432 $sql .= '(' . $this->makeList( $row ) . ')';
1435 $sql .= '(' . $this->makeList( $a ) . ')';
1438 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1440 } elseif ( $fh !== null ) {
1444 return (bool)$this->query( $sql, $fname );
1448 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1450 * @param array $options
1453 protected function makeUpdateOptionsArray( $options ) {
1454 if ( !is_array( $options ) ) {
1455 $options = [ $options ];
1460 if ( in_array( 'IGNORE', $options ) ) {
1468 * Make UPDATE options for the DatabaseBase::update function
1470 * @param array $options The options passed to DatabaseBase::update
1473 protected function makeUpdateOptions( $options ) {
1474 $opts = $this->makeUpdateOptionsArray( $options );
1476 return implode( ' ', $opts );
1479 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1480 $table = $this->tableName( $table );
1481 $opts = $this->makeUpdateOptions( $options );
1482 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1484 if ( $conds !== [] && $conds !== '*' ) {
1485 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1488 return $this->query( $sql, $fname );
1491 public function makeList( $a, $mode = LIST_COMMA
) {
1492 if ( !is_array( $a ) ) {
1493 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1499 foreach ( $a as $field => $value ) {
1501 if ( $mode == LIST_AND
) {
1503 } elseif ( $mode == LIST_OR
) {
1512 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1513 $list .= "($value)";
1514 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1516 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1517 // Remove null from array to be handled separately if found
1518 $includeNull = false;
1519 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1520 $includeNull = true;
1521 unset( $value[$nullKey] );
1523 if ( count( $value ) == 0 && !$includeNull ) {
1524 throw new InvalidArgumentException( __METHOD__
. ": empty input for field $field" );
1525 } elseif ( count( $value ) == 0 ) {
1526 // only check if $field is null
1527 $list .= "$field IS NULL";
1529 // IN clause contains at least one valid element
1530 if ( $includeNull ) {
1531 // Group subconditions to ensure correct precedence
1534 if ( count( $value ) == 1 ) {
1535 // Special-case single values, as IN isn't terribly efficient
1536 // Don't necessarily assume the single key is 0; we don't
1537 // enforce linear numeric ordering on other arrays here.
1538 $value = array_values( $value )[0];
1539 $list .= $field . " = " . $this->addQuotes( $value );
1541 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1543 // if null present in array, append IS NULL
1544 if ( $includeNull ) {
1545 $list .= " OR $field IS NULL)";
1548 } elseif ( $value === null ) {
1549 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1550 $list .= "$field IS ";
1551 } elseif ( $mode == LIST_SET
) {
1552 $list .= "$field = ";
1556 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1557 $list .= "$field = ";
1559 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1566 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1569 foreach ( $data as $base => $sub ) {
1570 if ( count( $sub ) ) {
1571 $conds[] = $this->makeList(
1572 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1578 return $this->makeList( $conds, LIST_OR
);
1580 // Nothing to search for...
1586 * Return aggregated value alias
1588 * @param array $valuedata
1589 * @param string $valuename
1593 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1597 public function bitNot( $field ) {
1601 public function bitAnd( $fieldLeft, $fieldRight ) {
1602 return "($fieldLeft & $fieldRight)";
1605 public function bitOr( $fieldLeft, $fieldRight ) {
1606 return "($fieldLeft | $fieldRight)";
1609 public function buildConcat( $stringList ) {
1610 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1613 public function buildGroupConcatField(
1614 $delim, $table, $field, $conds = '', $join_conds = []
1616 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1618 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1622 * @param string $field Field or column to cast
1626 public function buildStringCast( $field ) {
1630 public function selectDB( $db ) {
1631 # Stub. Shouldn't cause serious problems if it's not overridden, but
1632 # if your database engine supports a concept similar to MySQL's
1633 # databases you may as well.
1634 $this->mDBname
= $db;
1639 public function getDBname() {
1640 return $this->mDBname
;
1643 public function getServer() {
1644 return $this->mServer
;
1648 * Format a table name ready for use in constructing an SQL query
1650 * This does two important things: it quotes the table names to clean them up,
1651 * and it adds a table prefix if only given a table name with no quotes.
1653 * All functions of this object which require a table name call this function
1654 * themselves. Pass the canonical name to such functions. This is only needed
1655 * when calling query() directly.
1657 * @note This function does not sanitize user input. It is not safe to use
1658 * this function to escape user input.
1659 * @param string $name Database table name
1660 * @param string $format One of:
1661 * quoted - Automatically pass the table name through addIdentifierQuotes()
1662 * so that it can be used in a query.
1663 * raw - Do not add identifier quotes to the table name
1664 * @return string Full database name
1666 public function tableName( $name, $format = 'quoted' ) {
1667 # Skip the entire process when we have a string quoted on both ends.
1668 # Note that we check the end so that we will still quote any use of
1669 # use of `database`.table. But won't break things if someone wants
1670 # to query a database table with a dot in the name.
1671 if ( $this->isQuotedIdentifier( $name ) ) {
1675 # Lets test for any bits of text that should never show up in a table
1676 # name. Basically anything like JOIN or ON which are actually part of
1677 # SQL queries, but may end up inside of the table value to combine
1678 # sql. Such as how the API is doing.
1679 # Note that we use a whitespace test rather than a \b test to avoid
1680 # any remote case where a word like on may be inside of a table name
1681 # surrounded by symbols which may be considered word breaks.
1682 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1686 # Split database and table into proper variables.
1687 # We reverse the explode so that database.table and table both output
1688 # the correct table.
1689 $dbDetails = explode( '.', $name, 3 );
1690 if ( count( $dbDetails ) == 3 ) {
1691 list( $database, $schema, $table ) = $dbDetails;
1692 # We don't want any prefix added in this case
1694 } elseif ( count( $dbDetails ) == 2 ) {
1695 list( $database, $table ) = $dbDetails;
1696 # We don't want any prefix added in this case
1697 # In dbs that support it, $database may actually be the schema
1698 # but that doesn't affect any of the functionality here
1702 list( $table ) = $dbDetails;
1703 if ( isset( $this->tableAliases
[$table] ) ) {
1704 $database = $this->tableAliases
[$table]['dbname'];
1705 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1706 ?
$this->tableAliases
[$table]['schema']
1708 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1709 ?
$this->tableAliases
[$table]['prefix']
1710 : $this->mTablePrefix
;
1713 $schema = $this->mSchema
; # Default schema
1714 $prefix = $this->mTablePrefix
; # Default prefix
1718 # Quote $table and apply the prefix if not quoted.
1719 # $tableName might be empty if this is called from Database::replaceVars()
1720 $tableName = "{$prefix}{$table}";
1721 if ( $format == 'quoted'
1722 && !$this->isQuotedIdentifier( $tableName ) && $tableName !== ''
1724 $tableName = $this->addIdentifierQuotes( $tableName );
1727 # Quote $schema and merge it with the table name if needed
1728 if ( strlen( $schema ) ) {
1729 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1730 $schema = $this->addIdentifierQuotes( $schema );
1732 $tableName = $schema . '.' . $tableName;
1735 # Quote $database and merge it with the table name if needed
1736 if ( $database !== '' ) {
1737 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1738 $database = $this->addIdentifierQuotes( $database );
1740 $tableName = $database . '.' . $tableName;
1747 * Fetch a number of table names into an array
1748 * This is handy when you need to construct SQL for joins
1751 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1752 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1753 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1757 public function tableNames() {
1758 $inArray = func_get_args();
1761 foreach ( $inArray as $name ) {
1762 $retVal[$name] = $this->tableName( $name );
1769 * Fetch a number of table names into an zero-indexed numerical array
1770 * This is handy when you need to construct SQL for joins
1773 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1774 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1775 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1779 public function tableNamesN() {
1780 $inArray = func_get_args();
1783 foreach ( $inArray as $name ) {
1784 $retVal[] = $this->tableName( $name );
1791 * Get an aliased table name
1792 * e.g. tableName AS newTableName
1794 * @param string $name Table name, see tableName()
1795 * @param string|bool $alias Alias (optional)
1796 * @return string SQL name for aliased table. Will not alias a table to its own name
1798 public function tableNameWithAlias( $name, $alias = false ) {
1799 if ( !$alias ||
$alias == $name ) {
1800 return $this->tableName( $name );
1802 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1807 * Gets an array of aliased table names
1809 * @param array $tables [ [alias] => table ]
1810 * @return string[] See tableNameWithAlias()
1812 public function tableNamesWithAlias( $tables ) {
1814 foreach ( $tables as $alias => $table ) {
1815 if ( is_numeric( $alias ) ) {
1818 $retval[] = $this->tableNameWithAlias( $table, $alias );
1825 * Get an aliased field name
1826 * e.g. fieldName AS newFieldName
1828 * @param string $name Field name
1829 * @param string|bool $alias Alias (optional)
1830 * @return string SQL name for aliased field. Will not alias a field to its own name
1832 public function fieldNameWithAlias( $name, $alias = false ) {
1833 if ( !$alias ||
(string)$alias === (string)$name ) {
1836 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1841 * Gets an array of aliased field names
1843 * @param array $fields [ [alias] => field ]
1844 * @return string[] See fieldNameWithAlias()
1846 public function fieldNamesWithAlias( $fields ) {
1848 foreach ( $fields as $alias => $field ) {
1849 if ( is_numeric( $alias ) ) {
1852 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1859 * Get the aliased table name clause for a FROM clause
1860 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
1862 * @param array $tables ( [alias] => table )
1863 * @param array $use_index Same as for select()
1864 * @param array $ignore_index Same as for select()
1865 * @param array $join_conds Same as for select()
1868 protected function tableNamesWithIndexClauseOrJOIN(
1869 $tables, $use_index = [], $ignore_index = [], $join_conds = []
1873 $use_index = (array)$use_index;
1874 $ignore_index = (array)$ignore_index;
1875 $join_conds = (array)$join_conds;
1877 foreach ( $tables as $alias => $table ) {
1878 if ( !is_string( $alias ) ) {
1879 // No alias? Set it equal to the table name
1882 // Is there a JOIN clause for this table?
1883 if ( isset( $join_conds[$alias] ) ) {
1884 list( $joinType, $conds ) = $join_conds[$alias];
1885 $tableClause = $joinType;
1886 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1887 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1888 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1890 $tableClause .= ' ' . $use;
1893 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
1894 $ignore = $this->ignoreIndexClause( implode( ',', (array)$ignore_index[$alias] ) );
1895 if ( $ignore != '' ) {
1896 $tableClause .= ' ' . $ignore;
1899 $on = $this->makeList( (array)$conds, LIST_AND
);
1901 $tableClause .= ' ON (' . $on . ')';
1904 $retJOIN[] = $tableClause;
1905 } elseif ( isset( $use_index[$alias] ) ) {
1906 // Is there an INDEX clause for this table?
1907 $tableClause = $this->tableNameWithAlias( $table, $alias );
1908 $tableClause .= ' ' . $this->useIndexClause(
1909 implode( ',', (array)$use_index[$alias] )
1912 $ret[] = $tableClause;
1913 } elseif ( isset( $ignore_index[$alias] ) ) {
1914 // Is there an INDEX clause for this table?
1915 $tableClause = $this->tableNameWithAlias( $table, $alias );
1916 $tableClause .= ' ' . $this->ignoreIndexClause(
1917 implode( ',', (array)$ignore_index[$alias] )
1920 $ret[] = $tableClause;
1922 $tableClause = $this->tableNameWithAlias( $table, $alias );
1924 $ret[] = $tableClause;
1928 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1929 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1930 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1932 // Compile our final table clause
1933 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
1937 * Get the name of an index in a given table.
1939 * @param string $index
1942 protected function indexName( $index ) {
1943 // Backwards-compatibility hack
1945 'ar_usertext_timestamp' => 'usertext_timestamp',
1946 'un_user_id' => 'user_id',
1947 'un_user_ip' => 'user_ip',
1950 if ( isset( $renamed[$index] ) ) {
1951 return $renamed[$index];
1957 public function addQuotes( $s ) {
1958 if ( $s instanceof Blob
) {
1961 if ( $s === null ) {
1964 # This will also quote numeric values. This should be harmless,
1965 # and protects against weird problems that occur when they really
1966 # _are_ strings such as article titles and string->number->string
1967 # conversion is not 1:1.
1968 return "'" . $this->strencode( $s ) . "'";
1973 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1974 * MySQL uses `backticks` while basically everything else uses double quotes.
1975 * Since MySQL is the odd one out here the double quotes are our generic
1976 * and we implement backticks in DatabaseMysql.
1981 public function addIdentifierQuotes( $s ) {
1982 return '"' . str_replace( '"', '""', $s ) . '"';
1986 * Returns if the given identifier looks quoted or not according to
1987 * the database convention for quoting identifiers .
1989 * @note Do not use this to determine if untrusted input is safe.
1990 * A malicious user can trick this function.
1991 * @param string $name
1994 public function isQuotedIdentifier( $name ) {
1995 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2002 protected function escapeLikeInternal( $s ) {
2003 return addcslashes( $s, '\%_' );
2006 public function buildLike() {
2007 $params = func_get_args();
2009 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2010 $params = $params[0];
2015 foreach ( $params as $value ) {
2016 if ( $value instanceof LikeMatch
) {
2017 $s .= $value->toString();
2019 $s .= $this->escapeLikeInternal( $value );
2023 return " LIKE {$this->addQuotes( $s )} ";
2026 public function anyChar() {
2027 return new LikeMatch( '_' );
2030 public function anyString() {
2031 return new LikeMatch( '%' );
2034 public function nextSequenceValue( $seqName ) {
2039 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2040 * is only needed because a) MySQL must be as efficient as possible due to
2041 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2042 * which index to pick. Anyway, other databases might have different
2043 * indexes on a given table. So don't bother overriding this unless you're
2045 * @param string $index
2048 public function useIndexClause( $index ) {
2053 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2054 * is only needed because a) MySQL must be as efficient as possible due to
2055 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2056 * which index to pick. Anyway, other databases might have different
2057 * indexes on a given table. So don't bother overriding this unless you're
2059 * @param string $index
2062 public function ignoreIndexClause( $index ) {
2066 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2067 $quotedTable = $this->tableName( $table );
2069 if ( count( $rows ) == 0 ) {
2074 if ( !is_array( reset( $rows ) ) ) {
2078 // @FXIME: this is not atomic, but a trx would break affectedRows()
2079 foreach ( $rows as $row ) {
2080 # Delete rows which collide
2081 if ( $uniqueIndexes ) {
2082 $sql = "DELETE FROM $quotedTable WHERE ";
2084 foreach ( $uniqueIndexes as $index ) {
2091 if ( is_array( $index ) ) {
2093 foreach ( $index as $col ) {
2099 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2102 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2106 $this->query( $sql, $fname );
2109 # Now insert the row
2110 $this->insert( $table, $row, $fname );
2115 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2118 * @param string $table Table name
2119 * @param array|string $rows Row(s) to insert
2120 * @param string $fname Caller function name
2122 * @return ResultWrapper
2124 protected function nativeReplace( $table, $rows, $fname ) {
2125 $table = $this->tableName( $table );
2128 if ( !is_array( reset( $rows ) ) ) {
2132 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2135 foreach ( $rows as $row ) {
2142 $sql .= '(' . $this->makeList( $row ) . ')';
2145 return $this->query( $sql, $fname );
2148 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2151 if ( !count( $rows ) ) {
2152 return true; // nothing to do
2155 if ( !is_array( reset( $rows ) ) ) {
2159 if ( count( $uniqueIndexes ) ) {
2160 $clauses = []; // list WHERE clauses that each identify a single row
2161 foreach ( $rows as $row ) {
2162 foreach ( $uniqueIndexes as $index ) {
2163 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2164 $rowKey = []; // unique key to this row
2165 foreach ( $index as $column ) {
2166 $rowKey[$column] = $row[$column];
2168 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2171 $where = [ $this->makeList( $clauses, LIST_OR
) ];
2176 $useTrx = !$this->mTrxLevel
;
2178 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2181 # Update any existing conflicting row(s)
2182 if ( $where !== false ) {
2183 $ok = $this->update( $table, $set, $where, $fname );
2187 # Now insert any non-conflicting row(s)
2188 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2189 } catch ( Exception
$e ) {
2191 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2196 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2202 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2206 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2209 $delTable = $this->tableName( $delTable );
2210 $joinTable = $this->tableName( $joinTable );
2211 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2212 if ( $conds != '*' ) {
2213 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2217 $this->query( $sql, $fname );
2221 * Returns the size of a text field, or -1 for "unlimited"
2223 * @param string $table
2224 * @param string $field
2227 public function textFieldSize( $table, $field ) {
2228 $table = $this->tableName( $table );
2229 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2230 $res = $this->query( $sql, __METHOD__
);
2231 $row = $this->fetchObject( $res );
2235 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2244 public function delete( $table, $conds, $fname = __METHOD__
) {
2246 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2249 $table = $this->tableName( $table );
2250 $sql = "DELETE FROM $table";
2252 if ( $conds != '*' ) {
2253 if ( is_array( $conds ) ) {
2254 $conds = $this->makeList( $conds, LIST_AND
);
2256 $sql .= ' WHERE ' . $conds;
2259 return $this->query( $sql, $fname );
2262 public function insertSelect(
2263 $destTable, $srcTable, $varMap, $conds,
2264 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2266 if ( $this->cliMode
) {
2267 // For massive migrations with downtime, we don't want to select everything
2268 // into memory and OOM, so do all this native on the server side if possible.
2269 return $this->nativeInsertSelect(
2280 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2281 // on only the master (without needing row-based-replication). It also makes it easy to
2282 // know how big the INSERT is going to be.
2284 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2285 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2287 $selectOptions[] = 'FOR UPDATE';
2288 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2294 foreach ( $res as $row ) {
2295 $rows[] = (array)$row;
2298 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2301 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2302 $fname = __METHOD__
,
2303 $insertOptions = [], $selectOptions = []
2305 $destTable = $this->tableName( $destTable );
2307 if ( !is_array( $insertOptions ) ) {
2308 $insertOptions = [ $insertOptions ];
2311 $insertOptions = $this->makeInsertOptions( $insertOptions );
2313 if ( !is_array( $selectOptions ) ) {
2314 $selectOptions = [ $selectOptions ];
2317 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2320 if ( is_array( $srcTable ) ) {
2321 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2323 $srcTable = $this->tableName( $srcTable );
2326 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2327 " SELECT $startOpts " . implode( ',', $varMap ) .
2328 " FROM $srcTable $useIndex $ignoreIndex ";
2330 if ( $conds != '*' ) {
2331 if ( is_array( $conds ) ) {
2332 $conds = $this->makeList( $conds, LIST_AND
);
2334 $sql .= " WHERE $conds";
2337 $sql .= " $tailOpts";
2339 return $this->query( $sql, $fname );
2343 * Construct a LIMIT query with optional offset. This is used for query
2344 * pages. The SQL should be adjusted so that only the first $limit rows
2345 * are returned. If $offset is provided as well, then the first $offset
2346 * rows should be discarded, and the next $limit rows should be returned.
2347 * If the result of the query is not ordered, then the rows to be returned
2348 * are theoretically arbitrary.
2350 * $sql is expected to be a SELECT, if that makes a difference.
2352 * The version provided by default works in MySQL and SQLite. It will very
2353 * likely need to be overridden for most other DBMSes.
2355 * @param string $sql SQL query we will append the limit too
2356 * @param int $limit The SQL limit
2357 * @param int|bool $offset The SQL offset (default false)
2358 * @throws DBUnexpectedError
2361 public function limitResult( $sql, $limit, $offset = false ) {
2362 if ( !is_numeric( $limit ) ) {
2363 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2366 return "$sql LIMIT "
2367 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2371 public function unionSupportsOrderAndLimit() {
2372 return true; // True for almost every DB supported
2375 public function unionQueries( $sqls, $all ) {
2376 $glue = $all ?
') UNION ALL (' : ') UNION (';
2378 return '(' . implode( $glue, $sqls ) . ')';
2381 public function conditional( $cond, $trueVal, $falseVal ) {
2382 if ( is_array( $cond ) ) {
2383 $cond = $this->makeList( $cond, LIST_AND
);
2386 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2389 public function strreplace( $orig, $old, $new ) {
2390 return "REPLACE({$orig}, {$old}, {$new})";
2393 public function getServerUptime() {
2397 public function wasDeadlock() {
2401 public function wasLockTimeout() {
2405 public function wasErrorReissuable() {
2409 public function wasReadOnlyError() {
2414 * Determines if the given query error was a connection drop
2417 * @param integer|string $errno
2420 public function wasConnectionError( $errno ) {
2425 * Perform a deadlock-prone transaction.
2427 * This function invokes a callback function to perform a set of write
2428 * queries. If a deadlock occurs during the processing, the transaction
2429 * will be rolled back and the callback function will be called again.
2431 * Avoid using this method outside of Job or Maintenance classes.
2434 * $dbw->deadlockLoop( callback, ... );
2436 * Extra arguments are passed through to the specified callback function.
2437 * This method requires that no transactions are already active to avoid
2438 * causing premature commits or exceptions.
2440 * Returns whatever the callback function returned on its successful,
2441 * iteration, or false on error, for example if the retry limit was
2445 * @throws DBUnexpectedError
2448 public function deadlockLoop() {
2449 $args = func_get_args();
2450 $function = array_shift( $args );
2451 $tries = self
::DEADLOCK_TRIES
;
2453 $this->begin( __METHOD__
);
2456 /** @var Exception $e */
2460 $retVal = call_user_func_array( $function, $args );
2462 } catch ( DBQueryError
$e ) {
2463 if ( $this->wasDeadlock() ) {
2464 // Retry after a randomized delay
2465 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2467 // Throw the error back up
2471 } while ( --$tries > 0 );
2473 if ( $tries <= 0 ) {
2474 // Too many deadlocks; give up
2475 $this->rollback( __METHOD__
);
2478 $this->commit( __METHOD__
);
2484 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2485 # Real waits are implemented in the subclass.
2489 public function getSlavePos() {
2494 public function getMasterPos() {
2499 public function serverIsReadOnly() {
2503 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2504 if ( !$this->mTrxLevel
) {
2505 throw new DBUnexpectedError( $this, "No transaction is active." );
2507 $this->mTrxEndCallbacks
[] = [ $callback, $fname ];
2510 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2511 $this->mTrxIdleCallbacks
[] = [ $callback, $fname ];
2512 if ( !$this->mTrxLevel
) {
2513 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2517 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2518 if ( $this->mTrxLevel
) {
2519 $this->mTrxPreCommitCallbacks
[] = [ $callback, $fname ];
2521 // If no transaction is active, then make one for this callback
2522 $this->startAtomic( __METHOD__
);
2524 call_user_func( $callback );
2525 $this->endAtomic( __METHOD__
);
2526 } catch ( Exception
$e ) {
2527 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2533 final public function setTransactionListener( $name, callable
$callback = null ) {
2535 $this->mTrxRecurringCallbacks
[$name] = $callback;
2537 unset( $this->mTrxRecurringCallbacks
[$name] );
2542 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2544 * This method should not be used outside of Database/LoadBalancer
2546 * @param bool $suppress
2549 final public function setTrxEndCallbackSuppression( $suppress ) {
2550 $this->mTrxEndCallbacksSuppressed
= $suppress;
2554 * Actually run and consume any "on transaction idle/resolution" callbacks.
2556 * This method should not be used outside of Database/LoadBalancer
2558 * @param integer $trigger IDatabase::TRIGGER_* constant
2562 public function runOnTransactionIdleCallbacks( $trigger ) {
2563 if ( $this->mTrxEndCallbacksSuppressed
) {
2567 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2568 /** @var Exception $e */
2569 $e = null; // first exception
2570 do { // callbacks may add callbacks :)
2571 $callbacks = array_merge(
2572 $this->mTrxIdleCallbacks
,
2573 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2575 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2576 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2577 foreach ( $callbacks as $callback ) {
2579 list( $phpCallback ) = $callback;
2580 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2581 call_user_func_array( $phpCallback, [ $trigger ] );
2583 $this->setFlag( DBO_TRX
); // restore automatic begin()
2585 $this->clearFlag( DBO_TRX
); // restore auto-commit
2587 } catch ( Exception
$ex ) {
2588 call_user_func( $this->errorLogger
, $ex );
2590 // Some callbacks may use startAtomic/endAtomic, so make sure
2591 // their transactions are ended so other callbacks don't fail
2592 if ( $this->trxLevel() ) {
2593 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2597 } while ( count( $this->mTrxIdleCallbacks
) );
2599 if ( $e instanceof Exception
) {
2600 throw $e; // re-throw any first exception
2605 * Actually run and consume any "on transaction pre-commit" callbacks.
2607 * This method should not be used outside of Database/LoadBalancer
2612 public function runOnTransactionPreCommitCallbacks() {
2613 $e = null; // first exception
2614 do { // callbacks may add callbacks :)
2615 $callbacks = $this->mTrxPreCommitCallbacks
;
2616 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2617 foreach ( $callbacks as $callback ) {
2619 list( $phpCallback ) = $callback;
2620 call_user_func( $phpCallback );
2621 } catch ( Exception
$ex ) {
2622 call_user_func( $this->errorLogger
, $ex );
2626 } while ( count( $this->mTrxPreCommitCallbacks
) );
2628 if ( $e instanceof Exception
) {
2629 throw $e; // re-throw any first exception
2634 * Actually run any "transaction listener" callbacks.
2636 * This method should not be used outside of Database/LoadBalancer
2638 * @param integer $trigger IDatabase::TRIGGER_* constant
2642 public function runTransactionListenerCallbacks( $trigger ) {
2643 if ( $this->mTrxEndCallbacksSuppressed
) {
2647 /** @var Exception $e */
2648 $e = null; // first exception
2650 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2652 $phpCallback( $trigger, $this );
2653 } catch ( Exception
$ex ) {
2654 call_user_func( $this->errorLogger
, $ex );
2659 if ( $e instanceof Exception
) {
2660 throw $e; // re-throw any first exception
2664 final public function startAtomic( $fname = __METHOD__
) {
2665 if ( !$this->mTrxLevel
) {
2666 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2667 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2668 // in all changes being in one transaction to keep requests transactional.
2669 if ( !$this->getFlag( DBO_TRX
) ) {
2670 $this->mTrxAutomaticAtomic
= true;
2674 $this->mTrxAtomicLevels
[] = $fname;
2677 final public function endAtomic( $fname = __METHOD__
) {
2678 if ( !$this->mTrxLevel
) {
2679 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2681 if ( !$this->mTrxAtomicLevels ||
2682 array_pop( $this->mTrxAtomicLevels
) !== $fname
2684 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2687 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2688 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2692 final public function doAtomicSection( $fname, callable
$callback ) {
2693 $this->startAtomic( $fname );
2695 $res = call_user_func_array( $callback, [ $this, $fname ] );
2696 } catch ( Exception
$e ) {
2697 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2700 $this->endAtomic( $fname );
2705 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2706 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2707 if ( $this->mTrxLevel
) {
2708 if ( $this->mTrxAtomicLevels
) {
2709 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2710 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2711 throw new DBUnexpectedError( $this, $msg );
2712 } elseif ( !$this->mTrxAutomatic
) {
2713 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2714 throw new DBUnexpectedError( $this, $msg );
2716 // @TODO: make this an exception at some point
2717 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2718 $this->queryLogger
->error( $msg );
2719 return; // join the main transaction set
2721 } elseif ( $this->getFlag( DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2722 // @TODO: make this an exception at some point
2723 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2724 $this->queryLogger
->error( $msg );
2725 return; // let any writes be in the main transaction
2728 // Avoid fatals if close() was called
2729 $this->assertOpen();
2731 $this->doBegin( $fname );
2732 $this->mTrxTimestamp
= microtime( true );
2733 $this->mTrxFname
= $fname;
2734 $this->mTrxDoneWrites
= false;
2735 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2736 $this->mTrxAutomaticAtomic
= false;
2737 $this->mTrxAtomicLevels
= [];
2738 $this->mTrxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2739 $this->mTrxWriteDuration
= 0.0;
2740 $this->mTrxWriteQueryCount
= 0;
2741 $this->mTrxWriteAdjDuration
= 0.0;
2742 $this->mTrxWriteAdjQueryCount
= 0;
2743 $this->mTrxWriteCallers
= [];
2744 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2745 // Get an estimate of the replica DB lag before then, treating estimate staleness
2746 // as lag itself just to be safe
2747 $status = $this->getApproximateLagStatus();
2748 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2752 * Issues the BEGIN command to the database server.
2754 * @see DatabaseBase::begin()
2755 * @param string $fname
2757 protected function doBegin( $fname ) {
2758 $this->query( 'BEGIN', $fname );
2759 $this->mTrxLevel
= 1;
2762 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2763 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2764 // There are still atomic sections open. This cannot be ignored
2765 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2766 throw new DBUnexpectedError(
2768 "$fname: Got COMMIT while atomic sections $levels are still open."
2772 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2773 if ( !$this->mTrxLevel
) {
2774 return; // nothing to do
2775 } elseif ( !$this->mTrxAutomatic
) {
2776 throw new DBUnexpectedError(
2778 "$fname: Flushing an explicit transaction, getting out of sync."
2782 if ( !$this->mTrxLevel
) {
2783 $this->queryLogger
->error( "$fname: No transaction to commit, something got out of sync." );
2784 return; // nothing to do
2785 } elseif ( $this->mTrxAutomatic
) {
2786 // @TODO: make this an exception at some point
2787 $msg = "$fname: Explicit commit of implicit transaction.";
2788 $this->queryLogger
->error( $msg );
2789 return; // wait for the main transaction set commit round
2793 // Avoid fatals if close() was called
2794 $this->assertOpen();
2796 $this->runOnTransactionPreCommitCallbacks();
2797 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2798 $this->doCommit( $fname );
2799 if ( $this->mTrxDoneWrites
) {
2800 $this->mDoneWrites
= microtime( true );
2801 $this->trxProfiler
->transactionWritingOut(
2802 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2805 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2806 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
2810 * Issues the COMMIT command to the database server.
2812 * @see DatabaseBase::commit()
2813 * @param string $fname
2815 protected function doCommit( $fname ) {
2816 if ( $this->mTrxLevel
) {
2817 $this->query( 'COMMIT', $fname );
2818 $this->mTrxLevel
= 0;
2822 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2823 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2824 if ( !$this->mTrxLevel
) {
2825 return; // nothing to do
2828 if ( !$this->mTrxLevel
) {
2829 $this->queryLogger
->error(
2830 "$fname: No transaction to rollback, something got out of sync." );
2831 return; // nothing to do
2832 } elseif ( $this->getFlag( DBO_TRX
) ) {
2833 throw new DBUnexpectedError(
2835 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2840 // Avoid fatals if close() was called
2841 $this->assertOpen();
2843 $this->doRollback( $fname );
2844 $this->mTrxAtomicLevels
= [];
2845 if ( $this->mTrxDoneWrites
) {
2846 $this->trxProfiler
->transactionWritingOut(
2847 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
2850 $this->mTrxIdleCallbacks
= []; // clear
2851 $this->mTrxPreCommitCallbacks
= []; // clear
2852 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
2853 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
2857 * Issues the ROLLBACK command to the database server.
2859 * @see DatabaseBase::rollback()
2860 * @param string $fname
2862 protected function doRollback( $fname ) {
2863 if ( $this->mTrxLevel
) {
2864 # Disconnects cause rollback anyway, so ignore those errors
2865 $ignoreErrors = true;
2866 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
2867 $this->mTrxLevel
= 0;
2871 public function flushSnapshot( $fname = __METHOD__
) {
2872 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
2873 // This only flushes transactions to clear snapshots, not to write data
2874 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
2875 throw new DBUnexpectedError(
2877 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
2881 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2884 public function explicitTrxActive() {
2885 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
2889 * Creates a new table with structure copied from existing table
2890 * Note that unlike most database abstraction functions, this function does not
2891 * automatically append database prefix, because it works at a lower
2892 * abstraction level.
2893 * The table names passed to this function shall not be quoted (this
2894 * function calls addIdentifierQuotes when needed).
2896 * @param string $oldName Name of table whose structure should be copied
2897 * @param string $newName Name of table to be created
2898 * @param bool $temporary Whether the new table should be temporary
2899 * @param string $fname Calling function name
2900 * @throws RuntimeException
2901 * @return bool True if operation was successful
2903 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
2906 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2909 function listTables( $prefix = null, $fname = __METHOD__
) {
2910 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2914 * Reset the views process cache set by listViews()
2917 final public function clearViewsCache() {
2918 $this->allViews
= null;
2922 * Lists all the VIEWs in the database
2924 * For caching purposes the list of all views should be stored in
2925 * $this->allViews. The process cache can be cleared with clearViewsCache()
2927 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
2928 * @param string $fname Name of calling function
2929 * @throws RuntimeException
2933 public function listViews( $prefix = null, $fname = __METHOD__
) {
2934 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2938 * Differentiates between a TABLE and a VIEW
2940 * @param string $name Name of the database-structure to test.
2941 * @throws RuntimeException
2945 public function isView( $name ) {
2946 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2949 public function timestamp( $ts = 0 ) {
2950 $t = new ConvertableTimestamp( $ts );
2951 // Let errors bubble up to avoid putting garbage in the DB
2952 return $t->getTimestamp( TS_MW
);
2955 public function timestampOrNull( $ts = null ) {
2956 if ( is_null( $ts ) ) {
2959 return $this->timestamp( $ts );
2964 * Take the result from a query, and wrap it in a ResultWrapper if
2965 * necessary. Boolean values are passed through as is, to indicate success
2966 * of write queries or failure.
2968 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2969 * resource, and it was necessary to call this function to convert it to
2970 * a wrapper. Nowadays, raw database objects are never exposed to external
2971 * callers, so this is unnecessary in external code.
2973 * @param bool|ResultWrapper|resource|object $result
2974 * @return bool|ResultWrapper
2976 protected function resultObject( $result ) {
2979 } elseif ( $result instanceof ResultWrapper
) {
2981 } elseif ( $result === true ) {
2982 // Successful write query
2985 return new ResultWrapper( $this, $result );
2989 public function ping( &$rtt = null ) {
2990 // Avoid hitting the server if it was hit recently
2991 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
2992 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
2993 $rtt = $this->mRTTEstimate
;
2994 return true; // don't care about $rtt
2998 // This will reconnect if possible or return false if not
2999 $this->clearFlag( DBO_TRX
, self
::REMEMBER_PRIOR
);
3000 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3001 $this->restoreFlags( self
::RESTORE_PRIOR
);
3004 $rtt = $this->mRTTEstimate
;
3013 protected function reconnect() {
3014 $this->closeConnection();
3015 $this->mOpened
= false;
3016 $this->mConn
= false;
3018 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3019 $this->lastPing
= microtime( true );
3021 } catch ( DBConnectionError
$e ) {
3028 public function getSessionLagStatus() {
3029 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3033 * Get the replica DB lag when the current transaction started
3035 * This is useful when transactions might use snapshot isolation
3036 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3037 * is this lag plus transaction duration. If they don't, it is still
3038 * safe to be pessimistic. This returns null if there is no transaction.
3040 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3043 public function getTransactionLagStatus() {
3044 return $this->mTrxLevel
3045 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3050 * Get a replica DB lag estimate for this server
3052 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3055 public function getApproximateLagStatus() {
3057 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3058 'since' => microtime( true )
3063 * Merge the result of getSessionLagStatus() for several DBs
3064 * using the most pessimistic values to estimate the lag of
3065 * any data derived from them in combination
3067 * This is information is useful for caching modules
3069 * @see WANObjectCache::set()
3070 * @see WANObjectCache::getWithSetCallback()
3072 * @param IDatabase $db1
3073 * @param IDatabase ...
3074 * @return array Map of values:
3075 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3076 * - since: oldest UNIX timestamp of any of the DB lag estimates
3077 * - pending: whether any of the DBs have uncommitted changes
3080 public static function getCacheSetOptions( IDatabase
$db1 ) {
3081 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3082 foreach ( func_get_args() as $db ) {
3083 /** @var IDatabase $db */
3084 $status = $db->getSessionLagStatus();
3085 if ( $status['lag'] === false ) {
3086 $res['lag'] = false;
3087 } elseif ( $res['lag'] !== false ) {
3088 $res['lag'] = max( $res['lag'], $status['lag'] );
3090 $res['since'] = min( $res['since'], $status['since'] );
3091 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3097 public function getLag() {
3101 function maxListLen() {
3105 public function encodeBlob( $b ) {
3109 public function decodeBlob( $b ) {
3110 if ( $b instanceof Blob
) {
3116 public function setSessionOptions( array $options ) {
3120 * Read and execute SQL commands from a file.
3122 * Returns true on success, error string or exception on failure (depending
3123 * on object's error ignore settings).
3125 * @param string $filename File name to open
3126 * @param bool|callable $lineCallback Optional function called before reading each line
3127 * @param bool|callable $resultCallback Optional function called for each MySQL result
3128 * @param bool|string $fname Calling function name or false if name should be
3129 * generated dynamically using $filename
3130 * @param bool|callable $inputCallback Optional function called for each
3131 * complete line sent
3132 * @return bool|string
3135 public function sourceFile(
3136 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3138 MediaWiki\
suppressWarnings();
3139 $fp = fopen( $filename, 'r' );
3140 MediaWiki\restoreWarnings
();
3142 if ( false === $fp ) {
3143 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3147 $fname = __METHOD__
. "( $filename )";
3151 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3152 } catch ( Exception
$e ) {
3162 public function setSchemaVars( $vars ) {
3163 $this->mSchemaVars
= $vars;
3167 * Read and execute commands from an open file handle.
3169 * Returns true on success, error string or exception on failure (depending
3170 * on object's error ignore settings).
3172 * @param resource $fp File handle
3173 * @param bool|callable $lineCallback Optional function called before reading each query
3174 * @param bool|callable $resultCallback Optional function called for each MySQL result
3175 * @param string $fname Calling function name
3176 * @param bool|callable $inputCallback Optional function called for each complete query sent
3177 * @return bool|string
3179 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3180 $fname = __METHOD__
, $inputCallback = false
3184 while ( !feof( $fp ) ) {
3185 if ( $lineCallback ) {
3186 call_user_func( $lineCallback );
3189 $line = trim( fgets( $fp ) );
3191 if ( $line == '' ) {
3195 if ( '-' == $line[0] && '-' == $line[1] ) {
3203 $done = $this->streamStatementEnd( $cmd, $line );
3207 if ( $done ||
feof( $fp ) ) {
3208 $cmd = $this->replaceVars( $cmd );
3210 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3211 $res = $this->query( $cmd, $fname );
3213 if ( $resultCallback ) {
3214 call_user_func( $resultCallback, $res, $this );
3217 if ( false === $res ) {
3218 $err = $this->lastError();
3220 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3231 * Called by sourceStream() to check if we've reached a statement end
3233 * @param string $sql SQL assembled so far
3234 * @param string $newLine New line about to be added to $sql
3235 * @return bool Whether $newLine contains end of the statement
3237 public function streamStatementEnd( &$sql, &$newLine ) {
3238 if ( $this->delimiter
) {
3240 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3241 if ( $newLine != $prev ) {
3250 * Database independent variable replacement. Replaces a set of variables
3251 * in an SQL statement with their contents as given by $this->getSchemaVars().
3253 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3255 * - '{$var}' should be used for text and is passed through the database's
3257 * - `{$var}` should be used for identifiers (e.g. table and database names).
3258 * It is passed through the database's addIdentifierQuotes method which
3259 * can be overridden if the database uses something other than backticks.
3260 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3261 * database's tableName method.
3262 * - / *i* / passes the name that follows through the database's indexName method.
3263 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3264 * its use should be avoided. In 1.24 and older, string encoding was applied.
3266 * @param string $ins SQL statement to replace variables in
3267 * @return string The new SQL statement with variables replaced
3269 protected function replaceVars( $ins ) {
3270 $vars = $this->getSchemaVars();
3271 return preg_replace_callback(
3273 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3274 \'\{\$ (\w+) }\' | # 3. addQuotes
3275 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3276 /\*\$ (\w+) \*/ # 5. leave unencoded
3278 function ( $m ) use ( $vars ) {
3279 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3280 // check for both nonexistent keys *and* the empty string.
3281 if ( isset( $m[1] ) && $m[1] !== '' ) {
3282 if ( $m[1] === 'i' ) {
3283 return $this->indexName( $m[2] );
3285 return $this->tableName( $m[2] );
3287 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3288 return $this->addQuotes( $vars[$m[3]] );
3289 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3290 return $this->addIdentifierQuotes( $vars[$m[4]] );
3291 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3292 return $vars[$m[5]];
3302 * Get schema variables. If none have been set via setSchemaVars(), then
3303 * use some defaults from the current object.
3307 protected function getSchemaVars() {
3308 if ( $this->mSchemaVars
) {
3309 return $this->mSchemaVars
;
3311 return $this->getDefaultSchemaVars();
3316 * Get schema variables to use if none have been set via setSchemaVars().
3318 * Override this in derived classes to provide variables for tables.sql
3319 * and SQL patch files.
3323 protected function getDefaultSchemaVars() {
3327 public function lockIsFree( $lockName, $method ) {
3331 public function lock( $lockName, $method, $timeout = 5 ) {
3332 $this->mNamedLocksHeld
[$lockName] = 1;
3337 public function unlock( $lockName, $method ) {
3338 unset( $this->mNamedLocksHeld
[$lockName] );
3343 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3344 if ( $this->writesOrCallbacksPending() ) {
3345 // This only flushes transactions to clear snapshots, not to write data
3346 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3347 throw new DBUnexpectedError(
3349 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
3353 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3357 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3358 if ( $this->trxLevel() ) {
3359 // There is a good chance an exception was thrown, causing any early return
3360 // from the caller. Let any error handler get a chance to issue rollback().
3361 // If there isn't one, let the error bubble up and trigger server-side rollback.
3362 $this->onTransactionResolution(
3363 function () use ( $lockKey, $fname ) {
3364 $this->unlock( $lockKey, $fname );
3369 $this->unlock( $lockKey, $fname );
3373 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3378 public function namedLocksEnqueue() {
3383 * Lock specific tables
3385 * @param array $read Array of tables to lock for read access
3386 * @param array $write Array of tables to lock for write access
3387 * @param string $method Name of caller
3388 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3391 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3396 * Unlock specific tables
3398 * @param string $method The caller
3401 public function unlockTables( $method ) {
3407 * @param string $tableName
3408 * @param string $fName
3409 * @return bool|ResultWrapper
3412 public function dropTable( $tableName, $fName = __METHOD__
) {
3413 if ( !$this->tableExists( $tableName, $fName ) ) {
3416 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3418 return $this->query( $sql, $fName );
3421 public function getInfinity() {
3425 public function encodeExpiry( $expiry ) {
3426 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3427 ?
$this->getInfinity()
3428 : $this->timestamp( $expiry );
3431 public function decodeExpiry( $expiry, $format = TS_MW
) {
3432 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3437 $t = new ConvertableTimestamp( $expiry );
3439 return $t->getTimestamp( $format );
3440 } catch ( TimestampException
$e ) {
3445 public function setBigSelects( $value = true ) {
3449 public function isReadOnly() {
3450 return ( $this->getReadOnlyReason() !== false );
3454 * @return string|bool Reason this DB is read-only or false if it is not
3456 protected function getReadOnlyReason() {
3457 $reason = $this->getLBInfo( 'readOnlyReason' );
3459 return is_string( $reason ) ?
$reason : false;
3462 public function setTableAliases( array $aliases ) {
3463 $this->tableAliases
= $aliases;
3470 public function __toString() {
3471 return (string)$this->mConn
;
3475 * Called by serialize. Throw an exception when DB connection is serialized.
3476 * This causes problems on some database engines because the connection is
3477 * not restored on unserialize.
3479 public function __sleep() {
3480 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3481 'the connection is not restored on wakeup.' );
3485 * Run a few simple sanity checks
3487 public function __destruct() {
3488 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3489 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3492 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3493 if ( $danglingWriters ) {
3494 $fnames = implode( ', ', $danglingWriters );
3495 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );