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 = ';';
117 * Either 1 if a transaction is active or 0 otherwise.
118 * The other Trx fields may not be meaningfull if this is 0.
122 protected $mTrxLevel = 0;
124 * Either a short hexidecimal string if a transaction is active or ""
127 * @see DatabaseBase::mTrxLevel
129 protected $mTrxShortId = '';
131 * The UNIX time that the transaction started. Callers can assume that if
132 * snapshot isolation is used, then the data is *at least* up to date to that
133 * point (possibly more up-to-date since the first SELECT defines the snapshot).
136 * @see DatabaseBase::mTrxLevel
138 private $mTrxTimestamp = null;
139 /** @var float Lag estimate at the time of BEGIN */
140 private $mTrxReplicaLag = null;
142 * Remembers the function name given for starting the most recent transaction via begin().
143 * Used to provide additional context for error reporting.
146 * @see DatabaseBase::mTrxLevel
148 private $mTrxFname = null;
150 * Record if possible write queries were done in the last transaction started
153 * @see DatabaseBase::mTrxLevel
155 private $mTrxDoneWrites = false;
157 * Record if the current transaction was started implicitly due to DBO_TRX being set.
160 * @see DatabaseBase::mTrxLevel
162 private $mTrxAutomatic = false;
164 * Array of levels of atomicity within transactions
168 private $mTrxAtomicLevels = [];
170 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
174 private $mTrxAutomaticAtomic = false;
176 * Track the write query callers of the current transaction
180 private $mTrxWriteCallers = [];
182 * @var float Seconds spent in write queries for the current transaction
184 private $mTrxWriteDuration = 0.0;
186 * @var integer Number of write queries for the current transaction
188 private $mTrxWriteQueryCount = 0;
190 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
192 private $mTrxWriteAdjDuration = 0.0;
194 * @var integer Number of write queries counted in mTrxWriteAdjDuration
196 private $mTrxWriteAdjQueryCount = 0;
198 * @var float RTT time estimate
200 private $mRTTEstimate = 0.0;
202 /** @var array Map of (name => 1) for locks obtained via lock() */
203 private $mNamedLocksHeld = [];
205 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
206 private $lazyMasterHandle;
210 * @var resource File handle for upgrade
212 protected $fileHandle = null;
216 * @var string[] Process cache of VIEWs names in the database
218 protected $allViews = null;
220 /** @var float UNIX timestamp */
221 protected $lastPing = 0.0;
223 /** @var int[] Prior mFlags values */
224 private $priorFlags = [];
228 /** @var TransactionProfiler */
229 protected $trxProfiler;
234 * FIXME: It is possible to construct a Database object with no associated
235 * connection object, by specifying no parameters to __construct(). This
236 * feature is deprecated and should be removed.
238 * IDatabase classes should not be constructed directly in external
239 * code. DatabaseBase::factory() should be used instead.
241 * @param array $params Parameters passed from DatabaseBase::factory()
243 function __construct( array $params ) {
244 $server = $params['host'];
245 $user = $params['user'];
246 $password = $params['password'];
247 $dbName = $params['dbname'];
248 $flags = $params['flags'];
250 $this->mSchema
= $params['schema'];
251 $this->mTablePrefix
= $params['tablePrefix'];
253 $this->cliMode
= isset( $params['cliMode'] )
255 : ( PHP_SAPI
=== 'cli' );
256 $this->agent
= isset( $params['agent'] )
257 ?
str_replace( '/', '-', $params['agent'] ) // escape for comment
260 $this->mFlags
= $flags;
261 if ( $this->mFlags
& DBO_DEFAULT
) {
262 if ( $this->cliMode
) {
263 $this->mFlags
&= ~DBO_TRX
;
265 $this->mFlags |
= DBO_TRX
;
269 $this->mSessionVars
= $params['variables'];
271 $this->srvCache
= isset( $params['srvCache'] )
272 ?
$params['srvCache']
273 : new HashBagOStuff();
275 $this->profiler
= isset( $params['profiler'] )
276 ?
$params['profiler']
277 : Profiler
::instance(); // @TODO: remove global state
278 $this->trxProfiler
= isset( $params['trxProfiler'] )
279 ?
$params['trxProfiler']
280 : new TransactionProfiler();
281 $this->connLogger
= isset( $params['connLogger'] )
282 ?
$params['connLogger']
283 : new \Psr\Log\
NullLogger();
284 $this->queryLogger
= isset( $params['queryLogger'] )
285 ?
$params['queryLogger']
286 : new \Psr\Log\
NullLogger();
289 $this->open( $server, $user, $password, $dbName );
294 * Given a DB type, construct the name of the appropriate child class of
295 * IDatabase. This is designed to replace all of the manual stuff like:
296 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
297 * as well as validate against the canonical list of DB types we have
299 * This factory function is mostly useful for when you need to connect to a
300 * database other than the MediaWiki default (such as for external auth,
301 * an extension, et cetera). Do not use this to connect to the MediaWiki
302 * database. Example uses in core:
303 * @see LoadBalancer::reallyOpenConnection()
304 * @see ForeignDBRepo::getMasterDB()
305 * @see WebInstallerDBConnect::execute()
309 * @param string $dbType A possible DB type
310 * @param array $p An array of options to pass to the constructor.
311 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
312 * @return IDatabase|null If the database driver or extension cannot be found
313 * @throws InvalidArgumentException If the database driver or extension cannot be found
315 final public static function factory( $dbType, $p = [] ) {
316 $canonicalDBTypes = [
317 'mysql' => [ 'mysqli', 'mysql' ],
325 $dbType = strtolower( $dbType );
326 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
327 $possibleDrivers = $canonicalDBTypes[$dbType];
328 if ( !empty( $p['driver'] ) ) {
329 if ( in_array( $p['driver'], $possibleDrivers ) ) {
330 $driver = $p['driver'];
332 throw new InvalidArgumentException( __METHOD__
.
333 " type '$dbType' does not support driver '{$p['driver']}'" );
336 foreach ( $possibleDrivers as $posDriver ) {
337 if ( extension_loaded( $posDriver ) ) {
338 $driver = $posDriver;
346 if ( $driver === false ) {
347 throw new InvalidArgumentException( __METHOD__
.
348 " no viable database extension found for type '$dbType'" );
351 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
352 // and everything else doesn't use a schema (e.g. null)
353 // Although postgres and oracle support schemas, we don't use them (yet)
354 // to maintain backwards compatibility
356 'mssql' => 'get from global',
359 $class = 'Database' . ucfirst( $driver );
360 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
361 // Resolve some defaults for b/c
362 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
363 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
364 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
365 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
366 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
367 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
368 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
369 if ( !isset( $p['schema'] ) ) {
370 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : '';
372 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
374 $conn = new $class( $p );
375 if ( isset( $p['connLogger'] ) ) {
376 $conn->connLogger
= $p['connLogger'];
378 if ( isset( $p['queryLogger'] ) ) {
379 $conn->queryLogger
= $p['queryLogger'];
381 if ( isset( $p['errorLogger'] ) ) {
382 $conn->errorLogger
= $p['errorLogger'];
384 $conn->errorLogger
= function ( Exception
$e ) {
385 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_WARNING
);
395 public function setLogger( LoggerInterface
$logger ) {
396 $this->queryLogger
= $logger;
399 public function getServerInfo() {
400 return $this->getServerVersion();
403 public function bufferResults( $buffer = null ) {
404 $res = !$this->getFlag( DBO_NOBUFFER
);
405 if ( $buffer !== null ) {
406 $buffer ?
$this->clearFlag( DBO_NOBUFFER
) : $this->setFlag( DBO_NOBUFFER
);
413 * Turns on (false) or off (true) the automatic generation and sending
414 * of a "we're sorry, but there has been a database error" page on
415 * database errors. Default is on (false). When turned off, the
416 * code should use lastErrno() and lastError() to handle the
417 * situation as appropriate.
419 * Do not use this function outside of the Database classes.
421 * @param null|bool $ignoreErrors
422 * @return bool The previous value of the flag.
424 protected function ignoreErrors( $ignoreErrors = null ) {
425 $res = $this->getFlag( DBO_IGNORE
);
426 if ( $ignoreErrors !== null ) {
427 $ignoreErrors ?
$this->setFlag( DBO_IGNORE
) : $this->clearFlag( DBO_IGNORE
);
433 public function trxLevel() {
434 return $this->mTrxLevel
;
437 public function trxTimestamp() {
438 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
441 public function tablePrefix( $prefix = null ) {
442 $old = $this->mTablePrefix
;
443 if ( $prefix !== null ) {
444 $this->mTablePrefix
= $prefix;
450 public function dbSchema( $schema = null ) {
451 $old = $this->mSchema
;
452 if ( $schema !== null ) {
453 $this->mSchema
= $schema;
460 * Set the filehandle to copy write statements to.
462 * @param resource $fh File handle
464 public function setFileHandle( $fh ) {
465 $this->fileHandle
= $fh;
468 public function getLBInfo( $name = null ) {
469 if ( is_null( $name ) ) {
470 return $this->mLBInfo
;
472 if ( array_key_exists( $name, $this->mLBInfo
) ) {
473 return $this->mLBInfo
[$name];
480 public function setLBInfo( $name, $value = null ) {
481 if ( is_null( $value ) ) {
482 $this->mLBInfo
= $name;
484 $this->mLBInfo
[$name] = $value;
488 public function setLazyMasterHandle( IDatabase
$conn ) {
489 $this->lazyMasterHandle
= $conn;
493 * @return IDatabase|null
494 * @see setLazyMasterHandle()
497 public function getLazyMasterHandle() {
498 return $this->lazyMasterHandle
;
502 * @param TransactionProfiler $profiler
505 public function setTransactionProfiler( TransactionProfiler
$profiler ) {
506 $this->trxProfiler
= $profiler;
509 public function implicitGroupby() {
513 public function implicitOrderby() {
517 public function lastQuery() {
518 return $this->mLastQuery
;
521 public function doneWrites() {
522 return (bool)$this->mDoneWrites
;
525 public function lastDoneWrites() {
526 return $this->mDoneWrites ?
: false;
529 public function writesPending() {
530 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
533 public function writesOrCallbacksPending() {
534 return $this->mTrxLevel
&& (
535 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
539 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
540 if ( !$this->mTrxLevel
) {
542 } elseif ( !$this->mTrxDoneWrites
) {
547 case self
::ESTIMATE_DB_APPLY
:
549 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
550 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
551 // For omitted queries, make them count as something at least
552 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
553 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
556 default: // everything
557 return $this->mTrxWriteDuration
;
561 public function pendingWriteCallers() {
562 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
565 protected function pendingWriteAndCallbackCallers() {
566 if ( !$this->mTrxLevel
) {
570 $fnames = $this->mTrxWriteCallers
;
572 $this->mTrxIdleCallbacks
,
573 $this->mTrxPreCommitCallbacks
,
574 $this->mTrxEndCallbacks
576 foreach ( $callbacks as $callback ) {
577 $fnames[] = $callback[1];
584 public function isOpen() {
585 return $this->mOpened
;
588 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
589 if ( $remember === self
::REMEMBER_PRIOR
) {
590 array_push( $this->priorFlags
, $this->mFlags
);
592 $this->mFlags |
= $flag;
595 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
596 if ( $remember === self
::REMEMBER_PRIOR
) {
597 array_push( $this->priorFlags
, $this->mFlags
);
599 $this->mFlags
&= ~
$flag;
602 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
603 if ( !$this->priorFlags
) {
607 if ( $state === self
::RESTORE_INITIAL
) {
608 $this->mFlags
= reset( $this->priorFlags
);
609 $this->priorFlags
= [];
611 $this->mFlags
= array_pop( $this->priorFlags
);
615 public function getFlag( $flag ) {
616 return !!( $this->mFlags
& $flag );
619 public function getProperty( $name ) {
623 public function getDomainID() {
624 if ( $this->mTablePrefix
!= '' ) {
625 return "{$this->mDBname}-{$this->mTablePrefix}";
627 return $this->mDBname
;
631 final public function getWikiID() {
632 return $this->getDomainID();
636 * Get information about an index into an object
637 * @param string $table Table name
638 * @param string $index Index name
639 * @param string $fname Calling function name
640 * @return mixed Database-specific index description class or false if the index does not exist
642 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
645 * Wrapper for addslashes()
647 * @param string $s String to be slashed.
648 * @return string Slashed string.
650 abstract function strencode( $s );
652 protected function installErrorHandler() {
653 $this->mPHPError
= false;
654 $this->htmlErrors
= ini_set( 'html_errors', '0' );
655 set_error_handler( [ $this, 'connectionerrorLogger' ] );
659 * @return bool|string
661 protected function restoreErrorHandler() {
662 restore_error_handler();
663 if ( $this->htmlErrors
!== false ) {
664 ini_set( 'html_errors', $this->htmlErrors
);
666 if ( $this->mPHPError
) {
667 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
668 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
678 * @param string $errstr
680 public function connectionerrorLogger( $errno, $errstr ) {
681 $this->mPHPError
= $errstr;
685 * Create a log context to pass to PSR logging functions.
687 * @param array $extras Additional data to add to context
690 protected function getLogContext( array $extras = [] ) {
693 'db_server' => $this->mServer
,
694 'db_name' => $this->mDBname
,
695 'db_user' => $this->mUser
,
701 public function close() {
702 if ( $this->mConn
) {
703 if ( $this->trxLevel() ) {
704 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
707 $closed = $this->closeConnection();
708 $this->mConn
= false;
709 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
710 throw new RuntimeException( "Transaction callbacks still pending." );
714 $this->mOpened
= false;
720 * Make sure isOpen() returns true as a sanity check
722 * @throws DBUnexpectedError
724 protected function assertOpen() {
725 if ( !$this->isOpen() ) {
726 throw new DBUnexpectedError( $this, "DB connection was already closed." );
731 * Closes underlying database connection
733 * @return bool Whether connection was closed successfully
735 abstract protected function closeConnection();
737 function reportConnectionError( $error = 'Unknown error' ) {
738 $myError = $this->lastError();
744 throw new DBConnectionError( $this, $error );
748 * The DBMS-dependent part of query()
750 * @param string $sql SQL query.
751 * @return ResultWrapper|bool Result object to feed to fetchObject,
752 * fetchRow, ...; or false on failure
754 abstract protected function doQuery( $sql );
757 * Determine whether a query writes to the DB.
758 * Should return true if unsure.
763 protected function isWriteQuery( $sql ) {
765 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
770 * @return string|null
772 protected function getQueryVerb( $sql ) {
773 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
777 * Determine whether a SQL statement is sensitive to isolation level.
778 * A SQL statement is considered transactable if its result could vary
779 * depending on the transaction isolation level. Operational commands
780 * such as 'SET' and 'SHOW' are not considered to be transactable.
785 protected function isTransactableQuery( $sql ) {
786 $verb = $this->getQueryVerb( $sql );
787 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
790 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
791 $priorWritesPending = $this->writesOrCallbacksPending();
792 $this->mLastQuery
= $sql;
794 $isWrite = $this->isWriteQuery( $sql );
796 $reason = $this->getReadOnlyReason();
797 if ( $reason !== false ) {
798 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
800 # Set a flag indicating that writes have been done
801 $this->mDoneWrites
= microtime( true );
804 // Add trace comment to the begin of the sql string, right after the operator.
805 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
806 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
808 # Start implicit transactions that wrap the request if DBO_TRX is enabled
809 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
)
810 && $this->isTransactableQuery( $sql )
812 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
813 $this->mTrxAutomatic
= true;
816 # Keep track of whether the transaction has write queries pending
817 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
818 $this->mTrxDoneWrites
= true;
819 $this->trxProfiler
->transactionWritingIn(
820 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
823 if ( $this->getFlag( DBO_DEBUG
) ) {
824 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
827 # Avoid fatals if close() was called
830 # Send the query to the server
831 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
833 # Try reconnecting if the connection was lost
834 if ( false === $ret && $this->wasErrorReissuable() ) {
835 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
836 # Stash the last error values before anything might clear them
837 $lastError = $this->lastError();
838 $lastErrno = $this->lastErrno();
839 # Update state tracking to reflect transaction loss due to disconnection
840 $this->handleTransactionLoss();
841 if ( $this->reconnect() ) {
842 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
843 $this->connLogger
->warning( $msg );
844 $this->queryLogger
->warning(
845 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
847 if ( !$recoverable ) {
848 # Callers may catch the exception and continue to use the DB
849 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
851 # Should be safe to silently retry the query
852 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
855 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
856 $this->connLogger
->error( $msg );
860 if ( false === $ret ) {
861 # Deadlocks cause the entire transaction to abort, not just the statement.
862 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
863 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
864 if ( $this->wasDeadlock() ) {
865 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
866 $tempIgnore = false; // not recoverable
868 # Update state tracking to reflect transaction loss
869 $this->handleTransactionLoss();
872 $this->reportQueryError(
873 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
876 $res = $this->resultObject( $ret );
881 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
882 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
883 # generalizeSQL() will probably cut down the query to reasonable
884 # logging size most of the time. The substr is really just a sanity check.
886 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
888 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
891 # Include query transaction state
892 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
894 $startTime = microtime( true );
895 $this->profiler
->profileIn( $queryProf );
896 $ret = $this->doQuery( $commentedSql );
897 $this->profiler
->profileOut( $queryProf );
898 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
900 unset( $queryProfSection ); // profile out (if set)
902 if ( $ret !== false ) {
903 $this->lastPing
= $startTime;
904 if ( $isWrite && $this->mTrxLevel
) {
905 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
906 $this->mTrxWriteCallers
[] = $fname;
910 if ( $sql === self
::PING_QUERY
) {
911 $this->mRTTEstimate
= $queryRuntime;
914 $this->trxProfiler
->recordQueryCompletion(
915 $queryProf, $startTime, $isWrite, $this->affectedRows()
917 MWDebug
::query( $sql, $fname, $isMaster, $queryRuntime );
923 * Update the estimated run-time of a query, not counting large row lock times
925 * LoadBalancer can be set to rollback transactions that will create huge replication
926 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
927 * queries, like inserting a row can take a long time due to row locking. This method
928 * uses some simple heuristics to discount those cases.
930 * @param string $sql A SQL write query
931 * @param float $runtime Total runtime, including RTT
933 private function updateTrxWriteQueryTime( $sql, $runtime ) {
934 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
935 $indicativeOfReplicaRuntime = true;
936 if ( $runtime > self
::SLOW_WRITE_SEC
) {
937 $verb = $this->getQueryVerb( $sql );
938 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
939 if ( $verb === 'INSERT' ) {
940 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
941 } elseif ( $verb === 'REPLACE' ) {
942 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
946 $this->mTrxWriteDuration +
= $runtime;
947 $this->mTrxWriteQueryCount +
= 1;
948 if ( $indicativeOfReplicaRuntime ) {
949 $this->mTrxWriteAdjDuration +
= $runtime;
950 $this->mTrxWriteAdjQueryCount +
= 1;
954 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
955 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
956 # Dropped connections also mean that named locks are automatically released.
957 # Only allow error suppression in autocommit mode or when the lost transaction
958 # didn't matter anyway (aside from DBO_TRX snapshot loss).
959 if ( $this->mNamedLocksHeld
) {
960 return false; // possible critical section violation
961 } elseif ( $sql === 'COMMIT' ) {
962 return !$priorWritesPending; // nothing written anyway? (T127428)
963 } elseif ( $sql === 'ROLLBACK' ) {
964 return true; // transaction lost...which is also what was requested :)
965 } elseif ( $this->explicitTrxActive() ) {
966 return false; // don't drop atomocity
967 } elseif ( $priorWritesPending ) {
968 return false; // prior writes lost from implicit transaction
974 private function handleTransactionLoss() {
975 $this->mTrxLevel
= 0;
976 $this->mTrxIdleCallbacks
= []; // bug 65263
977 $this->mTrxPreCommitCallbacks
= []; // bug 65263
979 // Handle callbacks in mTrxEndCallbacks
980 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
981 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
983 } catch ( Exception
$e ) {
984 // Already logged; move on...
989 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
990 if ( $this->ignoreErrors() ||
$tempIgnore ) {
991 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
993 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
994 $this->queryLogger
->error(
995 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
996 $this->getLogContext( [
997 'method' => __METHOD__
,
1000 'sql1line' => $sql1line,
1004 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1005 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1009 public function freeResult( $res ) {
1012 public function selectField(
1013 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1015 if ( $var === '*' ) { // sanity
1016 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1019 if ( !is_array( $options ) ) {
1020 $options = [ $options ];
1023 $options['LIMIT'] = 1;
1025 $res = $this->select( $table, $var, $cond, $fname, $options );
1026 if ( $res === false ||
!$this->numRows( $res ) ) {
1030 $row = $this->fetchRow( $res );
1032 if ( $row !== false ) {
1033 return reset( $row );
1039 public function selectFieldValues(
1040 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1042 if ( $var === '*' ) { // sanity
1043 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1044 } elseif ( !is_string( $var ) ) { // sanity
1045 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1048 if ( !is_array( $options ) ) {
1049 $options = [ $options ];
1052 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1053 if ( $res === false ) {
1058 foreach ( $res as $row ) {
1059 $values[] = $row->$var;
1066 * Returns an optional USE INDEX clause to go after the table, and a
1067 * string to go at the end of the query.
1069 * @param array $options Associative array of options to be turned into
1070 * an SQL query, valid keys are listed in the function.
1072 * @see DatabaseBase::select()
1074 public function makeSelectOptions( $options ) {
1075 $preLimitTail = $postLimitTail = '';
1080 foreach ( $options as $key => $option ) {
1081 if ( is_numeric( $key ) ) {
1082 $noKeyOptions[$option] = true;
1086 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1088 $preLimitTail .= $this->makeOrderBy( $options );
1090 // if (isset($options['LIMIT'])) {
1091 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1092 // isset($options['OFFSET']) ? $options['OFFSET']
1096 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1097 $postLimitTail .= ' FOR UPDATE';
1100 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1101 $postLimitTail .= ' LOCK IN SHARE MODE';
1104 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1105 $startOpts .= 'DISTINCT';
1108 # Various MySQL extensions
1109 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1110 $startOpts .= ' /*! STRAIGHT_JOIN */';
1113 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1114 $startOpts .= ' HIGH_PRIORITY';
1117 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1118 $startOpts .= ' SQL_BIG_RESULT';
1121 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1122 $startOpts .= ' SQL_BUFFER_RESULT';
1125 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1126 $startOpts .= ' SQL_SMALL_RESULT';
1129 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1130 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1133 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1134 $startOpts .= ' SQL_CACHE';
1137 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1138 $startOpts .= ' SQL_NO_CACHE';
1141 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1142 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1146 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1147 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1152 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1156 * Returns an optional GROUP BY with an optional HAVING
1158 * @param array $options Associative array of options
1160 * @see DatabaseBase::select()
1163 public function makeGroupByWithHaving( $options ) {
1165 if ( isset( $options['GROUP BY'] ) ) {
1166 $gb = is_array( $options['GROUP BY'] )
1167 ?
implode( ',', $options['GROUP BY'] )
1168 : $options['GROUP BY'];
1169 $sql .= ' GROUP BY ' . $gb;
1171 if ( isset( $options['HAVING'] ) ) {
1172 $having = is_array( $options['HAVING'] )
1173 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1174 : $options['HAVING'];
1175 $sql .= ' HAVING ' . $having;
1182 * Returns an optional ORDER BY
1184 * @param array $options Associative array of options
1186 * @see DatabaseBase::select()
1189 public function makeOrderBy( $options ) {
1190 if ( isset( $options['ORDER BY'] ) ) {
1191 $ob = is_array( $options['ORDER BY'] )
1192 ?
implode( ',', $options['ORDER BY'] )
1193 : $options['ORDER BY'];
1195 return ' ORDER BY ' . $ob;
1201 // See IDatabase::select for the docs for this function
1202 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1203 $options = [], $join_conds = [] ) {
1204 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1206 return $this->query( $sql, $fname );
1209 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1210 $options = [], $join_conds = []
1212 if ( is_array( $vars ) ) {
1213 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1216 $options = (array)$options;
1217 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1218 ?
$options['USE INDEX']
1220 $ignoreIndexes = ( isset( $options['IGNORE INDEX'] ) && is_array( $options['IGNORE INDEX'] ) )
1221 ?
$options['IGNORE INDEX']
1224 if ( is_array( $table ) ) {
1226 $this->tableNamesWithIndexClauseOrJOIN( $table, $useIndexes, $ignoreIndexes, $join_conds );
1227 } elseif ( $table != '' ) {
1228 if ( $table[0] == ' ' ) {
1229 $from = ' FROM ' . $table;
1232 $this->tableNamesWithIndexClauseOrJOIN( [ $table ], $useIndexes, $ignoreIndexes, [] );
1238 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1239 $this->makeSelectOptions( $options );
1241 if ( !empty( $conds ) ) {
1242 if ( is_array( $conds ) ) {
1243 $conds = $this->makeList( $conds, LIST_AND
);
1245 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex WHERE $conds $preLimitTail";
1247 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1250 if ( isset( $options['LIMIT'] ) ) {
1251 $sql = $this->limitResult( $sql, $options['LIMIT'],
1252 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1254 $sql = "$sql $postLimitTail";
1256 if ( isset( $options['EXPLAIN'] ) ) {
1257 $sql = 'EXPLAIN ' . $sql;
1263 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1264 $options = [], $join_conds = []
1266 $options = (array)$options;
1267 $options['LIMIT'] = 1;
1268 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1270 if ( $res === false ) {
1274 if ( !$this->numRows( $res ) ) {
1278 $obj = $this->fetchObject( $res );
1283 public function estimateRowCount(
1284 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1287 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1290 $row = $this->fetchRow( $res );
1291 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1297 public function selectRowCount(
1298 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1301 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1302 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1305 $row = $this->fetchRow( $res );
1306 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1313 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1314 * It's only slightly flawed. Don't use for anything important.
1316 * @param string $sql A SQL Query
1320 protected static function generalizeSQL( $sql ) {
1321 # This does the same as the regexp below would do, but in such a way
1322 # as to avoid crashing php on some large strings.
1323 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1325 $sql = str_replace( "\\\\", '', $sql );
1326 $sql = str_replace( "\\'", '', $sql );
1327 $sql = str_replace( "\\\"", '', $sql );
1328 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1329 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1331 # All newlines, tabs, etc replaced by single space
1332 $sql = preg_replace( '/\s+/', ' ', $sql );
1335 # except the ones surrounded by characters, e.g. l10n
1336 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1337 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1342 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1343 $info = $this->fieldInfo( $table, $field );
1348 public function indexExists( $table, $index, $fname = __METHOD__
) {
1349 if ( !$this->tableExists( $table ) ) {
1353 $info = $this->indexInfo( $table, $index, $fname );
1354 if ( is_null( $info ) ) {
1357 return $info !== false;
1361 public function tableExists( $table, $fname = __METHOD__
) {
1362 $table = $this->tableName( $table );
1363 $old = $this->ignoreErrors( true );
1364 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1365 $this->ignoreErrors( $old );
1370 public function indexUnique( $table, $index ) {
1371 $indexInfo = $this->indexInfo( $table, $index );
1373 if ( !$indexInfo ) {
1377 return !$indexInfo[0]->Non_unique
;
1381 * Helper for DatabaseBase::insert().
1383 * @param array $options
1386 protected function makeInsertOptions( $options ) {
1387 return implode( ' ', $options );
1390 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1391 # No rows to insert, easy just return now
1392 if ( !count( $a ) ) {
1396 $table = $this->tableName( $table );
1398 if ( !is_array( $options ) ) {
1399 $options = [ $options ];
1403 if ( isset( $options['fileHandle'] ) ) {
1404 $fh = $options['fileHandle'];
1406 $options = $this->makeInsertOptions( $options );
1408 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1410 $keys = array_keys( $a[0] );
1413 $keys = array_keys( $a );
1416 $sql = 'INSERT ' . $options .
1417 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1421 foreach ( $a as $row ) {
1427 $sql .= '(' . $this->makeList( $row ) . ')';
1430 $sql .= '(' . $this->makeList( $a ) . ')';
1433 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1435 } elseif ( $fh !== null ) {
1439 return (bool)$this->query( $sql, $fname );
1443 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1445 * @param array $options
1448 protected function makeUpdateOptionsArray( $options ) {
1449 if ( !is_array( $options ) ) {
1450 $options = [ $options ];
1455 if ( in_array( 'IGNORE', $options ) ) {
1463 * Make UPDATE options for the DatabaseBase::update function
1465 * @param array $options The options passed to DatabaseBase::update
1468 protected function makeUpdateOptions( $options ) {
1469 $opts = $this->makeUpdateOptionsArray( $options );
1471 return implode( ' ', $opts );
1474 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1475 $table = $this->tableName( $table );
1476 $opts = $this->makeUpdateOptions( $options );
1477 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1479 if ( $conds !== [] && $conds !== '*' ) {
1480 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1483 return $this->query( $sql, $fname );
1486 public function makeList( $a, $mode = LIST_COMMA
) {
1487 if ( !is_array( $a ) ) {
1488 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1494 foreach ( $a as $field => $value ) {
1496 if ( $mode == LIST_AND
) {
1498 } elseif ( $mode == LIST_OR
) {
1507 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1508 $list .= "($value)";
1509 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1511 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1512 // Remove null from array to be handled separately if found
1513 $includeNull = false;
1514 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1515 $includeNull = true;
1516 unset( $value[$nullKey] );
1518 if ( count( $value ) == 0 && !$includeNull ) {
1519 throw new InvalidArgumentException( __METHOD__
. ": empty input for field $field" );
1520 } elseif ( count( $value ) == 0 ) {
1521 // only check if $field is null
1522 $list .= "$field IS NULL";
1524 // IN clause contains at least one valid element
1525 if ( $includeNull ) {
1526 // Group subconditions to ensure correct precedence
1529 if ( count( $value ) == 1 ) {
1530 // Special-case single values, as IN isn't terribly efficient
1531 // Don't necessarily assume the single key is 0; we don't
1532 // enforce linear numeric ordering on other arrays here.
1533 $value = array_values( $value )[0];
1534 $list .= $field . " = " . $this->addQuotes( $value );
1536 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1538 // if null present in array, append IS NULL
1539 if ( $includeNull ) {
1540 $list .= " OR $field IS NULL)";
1543 } elseif ( $value === null ) {
1544 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1545 $list .= "$field IS ";
1546 } elseif ( $mode == LIST_SET
) {
1547 $list .= "$field = ";
1551 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1552 $list .= "$field = ";
1554 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1561 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1564 foreach ( $data as $base => $sub ) {
1565 if ( count( $sub ) ) {
1566 $conds[] = $this->makeList(
1567 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1573 return $this->makeList( $conds, LIST_OR
);
1575 // Nothing to search for...
1581 * Return aggregated value alias
1583 * @param array $valuedata
1584 * @param string $valuename
1588 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1592 public function bitNot( $field ) {
1596 public function bitAnd( $fieldLeft, $fieldRight ) {
1597 return "($fieldLeft & $fieldRight)";
1600 public function bitOr( $fieldLeft, $fieldRight ) {
1601 return "($fieldLeft | $fieldRight)";
1604 public function buildConcat( $stringList ) {
1605 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1608 public function buildGroupConcatField(
1609 $delim, $table, $field, $conds = '', $join_conds = []
1611 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1613 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1617 * @param string $field Field or column to cast
1621 public function buildStringCast( $field ) {
1625 public function selectDB( $db ) {
1626 # Stub. Shouldn't cause serious problems if it's not overridden, but
1627 # if your database engine supports a concept similar to MySQL's
1628 # databases you may as well.
1629 $this->mDBname
= $db;
1634 public function getDBname() {
1635 return $this->mDBname
;
1638 public function getServer() {
1639 return $this->mServer
;
1643 * Format a table name ready for use in constructing an SQL query
1645 * This does two important things: it quotes the table names to clean them up,
1646 * and it adds a table prefix if only given a table name with no quotes.
1648 * All functions of this object which require a table name call this function
1649 * themselves. Pass the canonical name to such functions. This is only needed
1650 * when calling query() directly.
1652 * @note This function does not sanitize user input. It is not safe to use
1653 * this function to escape user input.
1654 * @param string $name Database table name
1655 * @param string $format One of:
1656 * quoted - Automatically pass the table name through addIdentifierQuotes()
1657 * so that it can be used in a query.
1658 * raw - Do not add identifier quotes to the table name
1659 * @return string Full database name
1661 public function tableName( $name, $format = 'quoted' ) {
1662 # Skip the entire process when we have a string quoted on both ends.
1663 # Note that we check the end so that we will still quote any use of
1664 # use of `database`.table. But won't break things if someone wants
1665 # to query a database table with a dot in the name.
1666 if ( $this->isQuotedIdentifier( $name ) ) {
1670 # Lets test for any bits of text that should never show up in a table
1671 # name. Basically anything like JOIN or ON which are actually part of
1672 # SQL queries, but may end up inside of the table value to combine
1673 # sql. Such as how the API is doing.
1674 # Note that we use a whitespace test rather than a \b test to avoid
1675 # any remote case where a word like on may be inside of a table name
1676 # surrounded by symbols which may be considered word breaks.
1677 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1681 # Split database and table into proper variables.
1682 # We reverse the explode so that database.table and table both output
1683 # the correct table.
1684 $dbDetails = explode( '.', $name, 3 );
1685 if ( count( $dbDetails ) == 3 ) {
1686 list( $database, $schema, $table ) = $dbDetails;
1687 # We don't want any prefix added in this case
1689 } elseif ( count( $dbDetails ) == 2 ) {
1690 list( $database, $table ) = $dbDetails;
1691 # We don't want any prefix added in this case
1692 # In dbs that support it, $database may actually be the schema
1693 # but that doesn't affect any of the functionality here
1697 list( $table ) = $dbDetails;
1698 if ( isset( $this->tableAliases
[$table] ) ) {
1699 $database = $this->tableAliases
[$table]['dbname'];
1700 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1701 ?
$this->tableAliases
[$table]['schema']
1703 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1704 ?
$this->tableAliases
[$table]['prefix']
1705 : $this->mTablePrefix
;
1708 $schema = $this->mSchema
; # Default schema
1709 $prefix = $this->mTablePrefix
; # Default prefix
1713 # Quote $table and apply the prefix if not quoted.
1714 # $tableName might be empty if this is called from Database::replaceVars()
1715 $tableName = "{$prefix}{$table}";
1716 if ( $format == 'quoted'
1717 && !$this->isQuotedIdentifier( $tableName ) && $tableName !== ''
1719 $tableName = $this->addIdentifierQuotes( $tableName );
1722 # Quote $schema and merge it with the table name if needed
1723 if ( strlen( $schema ) ) {
1724 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1725 $schema = $this->addIdentifierQuotes( $schema );
1727 $tableName = $schema . '.' . $tableName;
1730 # Quote $database and merge it with the table name if needed
1731 if ( $database !== '' ) {
1732 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1733 $database = $this->addIdentifierQuotes( $database );
1735 $tableName = $database . '.' . $tableName;
1742 * Fetch a number of table names into an array
1743 * This is handy when you need to construct SQL for joins
1746 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1747 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1748 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1752 public function tableNames() {
1753 $inArray = func_get_args();
1756 foreach ( $inArray as $name ) {
1757 $retVal[$name] = $this->tableName( $name );
1764 * Fetch a number of table names into an zero-indexed numerical array
1765 * This is handy when you need to construct SQL for joins
1768 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1769 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1770 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1774 public function tableNamesN() {
1775 $inArray = func_get_args();
1778 foreach ( $inArray as $name ) {
1779 $retVal[] = $this->tableName( $name );
1786 * Get an aliased table name
1787 * e.g. tableName AS newTableName
1789 * @param string $name Table name, see tableName()
1790 * @param string|bool $alias Alias (optional)
1791 * @return string SQL name for aliased table. Will not alias a table to its own name
1793 public function tableNameWithAlias( $name, $alias = false ) {
1794 if ( !$alias ||
$alias == $name ) {
1795 return $this->tableName( $name );
1797 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1802 * Gets an array of aliased table names
1804 * @param array $tables [ [alias] => table ]
1805 * @return string[] See tableNameWithAlias()
1807 public function tableNamesWithAlias( $tables ) {
1809 foreach ( $tables as $alias => $table ) {
1810 if ( is_numeric( $alias ) ) {
1813 $retval[] = $this->tableNameWithAlias( $table, $alias );
1820 * Get an aliased field name
1821 * e.g. fieldName AS newFieldName
1823 * @param string $name Field name
1824 * @param string|bool $alias Alias (optional)
1825 * @return string SQL name for aliased field. Will not alias a field to its own name
1827 public function fieldNameWithAlias( $name, $alias = false ) {
1828 if ( !$alias ||
(string)$alias === (string)$name ) {
1831 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1836 * Gets an array of aliased field names
1838 * @param array $fields [ [alias] => field ]
1839 * @return string[] See fieldNameWithAlias()
1841 public function fieldNamesWithAlias( $fields ) {
1843 foreach ( $fields as $alias => $field ) {
1844 if ( is_numeric( $alias ) ) {
1847 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1854 * Get the aliased table name clause for a FROM clause
1855 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
1857 * @param array $tables ( [alias] => table )
1858 * @param array $use_index Same as for select()
1859 * @param array $ignore_index Same as for select()
1860 * @param array $join_conds Same as for select()
1863 protected function tableNamesWithIndexClauseOrJOIN(
1864 $tables, $use_index = [], $ignore_index = [], $join_conds = []
1868 $use_index = (array)$use_index;
1869 $ignore_index = (array)$ignore_index;
1870 $join_conds = (array)$join_conds;
1872 foreach ( $tables as $alias => $table ) {
1873 if ( !is_string( $alias ) ) {
1874 // No alias? Set it equal to the table name
1877 // Is there a JOIN clause for this table?
1878 if ( isset( $join_conds[$alias] ) ) {
1879 list( $joinType, $conds ) = $join_conds[$alias];
1880 $tableClause = $joinType;
1881 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1882 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1883 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1885 $tableClause .= ' ' . $use;
1888 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
1889 $ignore = $this->ignoreIndexClause( implode( ',', (array)$ignore_index[$alias] ) );
1890 if ( $ignore != '' ) {
1891 $tableClause .= ' ' . $ignore;
1894 $on = $this->makeList( (array)$conds, LIST_AND
);
1896 $tableClause .= ' ON (' . $on . ')';
1899 $retJOIN[] = $tableClause;
1900 } elseif ( isset( $use_index[$alias] ) ) {
1901 // Is there an INDEX clause for this table?
1902 $tableClause = $this->tableNameWithAlias( $table, $alias );
1903 $tableClause .= ' ' . $this->useIndexClause(
1904 implode( ',', (array)$use_index[$alias] )
1907 $ret[] = $tableClause;
1908 } elseif ( isset( $ignore_index[$alias] ) ) {
1909 // Is there an INDEX clause for this table?
1910 $tableClause = $this->tableNameWithAlias( $table, $alias );
1911 $tableClause .= ' ' . $this->ignoreIndexClause(
1912 implode( ',', (array)$ignore_index[$alias] )
1915 $ret[] = $tableClause;
1917 $tableClause = $this->tableNameWithAlias( $table, $alias );
1919 $ret[] = $tableClause;
1923 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1924 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1925 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1927 // Compile our final table clause
1928 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
1932 * Get the name of an index in a given table.
1934 * @param string $index
1937 protected function indexName( $index ) {
1938 // Backwards-compatibility hack
1940 'ar_usertext_timestamp' => 'usertext_timestamp',
1941 'un_user_id' => 'user_id',
1942 'un_user_ip' => 'user_ip',
1945 if ( isset( $renamed[$index] ) ) {
1946 return $renamed[$index];
1952 public function addQuotes( $s ) {
1953 if ( $s instanceof Blob
) {
1956 if ( $s === null ) {
1959 # This will also quote numeric values. This should be harmless,
1960 # and protects against weird problems that occur when they really
1961 # _are_ strings such as article titles and string->number->string
1962 # conversion is not 1:1.
1963 return "'" . $this->strencode( $s ) . "'";
1968 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1969 * MySQL uses `backticks` while basically everything else uses double quotes.
1970 * Since MySQL is the odd one out here the double quotes are our generic
1971 * and we implement backticks in DatabaseMysql.
1976 public function addIdentifierQuotes( $s ) {
1977 return '"' . str_replace( '"', '""', $s ) . '"';
1981 * Returns if the given identifier looks quoted or not according to
1982 * the database convention for quoting identifiers .
1984 * @note Do not use this to determine if untrusted input is safe.
1985 * A malicious user can trick this function.
1986 * @param string $name
1989 public function isQuotedIdentifier( $name ) {
1990 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
1997 protected function escapeLikeInternal( $s ) {
1998 return addcslashes( $s, '\%_' );
2001 public function buildLike() {
2002 $params = func_get_args();
2004 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2005 $params = $params[0];
2010 foreach ( $params as $value ) {
2011 if ( $value instanceof LikeMatch
) {
2012 $s .= $value->toString();
2014 $s .= $this->escapeLikeInternal( $value );
2018 return " LIKE {$this->addQuotes( $s )} ";
2021 public function anyChar() {
2022 return new LikeMatch( '_' );
2025 public function anyString() {
2026 return new LikeMatch( '%' );
2029 public function nextSequenceValue( $seqName ) {
2034 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2035 * is only needed because a) MySQL must be as efficient as possible due to
2036 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2037 * which index to pick. Anyway, other databases might have different
2038 * indexes on a given table. So don't bother overriding this unless you're
2040 * @param string $index
2043 public function useIndexClause( $index ) {
2048 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2049 * is only needed because a) MySQL must be as efficient as possible due to
2050 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2051 * which index to pick. Anyway, other databases might have different
2052 * indexes on a given table. So don't bother overriding this unless you're
2054 * @param string $index
2057 public function ignoreIndexClause( $index ) {
2061 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2062 $quotedTable = $this->tableName( $table );
2064 if ( count( $rows ) == 0 ) {
2069 if ( !is_array( reset( $rows ) ) ) {
2073 // @FXIME: this is not atomic, but a trx would break affectedRows()
2074 foreach ( $rows as $row ) {
2075 # Delete rows which collide
2076 if ( $uniqueIndexes ) {
2077 $sql = "DELETE FROM $quotedTable WHERE ";
2079 foreach ( $uniqueIndexes as $index ) {
2086 if ( is_array( $index ) ) {
2088 foreach ( $index as $col ) {
2094 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2097 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2101 $this->query( $sql, $fname );
2104 # Now insert the row
2105 $this->insert( $table, $row, $fname );
2110 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2113 * @param string $table Table name
2114 * @param array|string $rows Row(s) to insert
2115 * @param string $fname Caller function name
2117 * @return ResultWrapper
2119 protected function nativeReplace( $table, $rows, $fname ) {
2120 $table = $this->tableName( $table );
2123 if ( !is_array( reset( $rows ) ) ) {
2127 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2130 foreach ( $rows as $row ) {
2137 $sql .= '(' . $this->makeList( $row ) . ')';
2140 return $this->query( $sql, $fname );
2143 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2146 if ( !count( $rows ) ) {
2147 return true; // nothing to do
2150 if ( !is_array( reset( $rows ) ) ) {
2154 if ( count( $uniqueIndexes ) ) {
2155 $clauses = []; // list WHERE clauses that each identify a single row
2156 foreach ( $rows as $row ) {
2157 foreach ( $uniqueIndexes as $index ) {
2158 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2159 $rowKey = []; // unique key to this row
2160 foreach ( $index as $column ) {
2161 $rowKey[$column] = $row[$column];
2163 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2166 $where = [ $this->makeList( $clauses, LIST_OR
) ];
2171 $useTrx = !$this->mTrxLevel
;
2173 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2176 # Update any existing conflicting row(s)
2177 if ( $where !== false ) {
2178 $ok = $this->update( $table, $set, $where, $fname );
2182 # Now insert any non-conflicting row(s)
2183 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2184 } catch ( Exception
$e ) {
2186 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2191 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2197 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2201 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2204 $delTable = $this->tableName( $delTable );
2205 $joinTable = $this->tableName( $joinTable );
2206 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2207 if ( $conds != '*' ) {
2208 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2212 $this->query( $sql, $fname );
2216 * Returns the size of a text field, or -1 for "unlimited"
2218 * @param string $table
2219 * @param string $field
2222 public function textFieldSize( $table, $field ) {
2223 $table = $this->tableName( $table );
2224 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2225 $res = $this->query( $sql, __METHOD__
);
2226 $row = $this->fetchObject( $res );
2230 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2239 public function delete( $table, $conds, $fname = __METHOD__
) {
2241 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2244 $table = $this->tableName( $table );
2245 $sql = "DELETE FROM $table";
2247 if ( $conds != '*' ) {
2248 if ( is_array( $conds ) ) {
2249 $conds = $this->makeList( $conds, LIST_AND
);
2251 $sql .= ' WHERE ' . $conds;
2254 return $this->query( $sql, $fname );
2257 public function insertSelect(
2258 $destTable, $srcTable, $varMap, $conds,
2259 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2261 if ( $this->cliMode
) {
2262 // For massive migrations with downtime, we don't want to select everything
2263 // into memory and OOM, so do all this native on the server side if possible.
2264 return $this->nativeInsertSelect(
2275 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2276 // on only the master (without needing row-based-replication). It also makes it easy to
2277 // know how big the INSERT is going to be.
2279 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2280 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2282 $selectOptions[] = 'FOR UPDATE';
2283 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2289 foreach ( $res as $row ) {
2290 $rows[] = (array)$row;
2293 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2296 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2297 $fname = __METHOD__
,
2298 $insertOptions = [], $selectOptions = []
2300 $destTable = $this->tableName( $destTable );
2302 if ( !is_array( $insertOptions ) ) {
2303 $insertOptions = [ $insertOptions ];
2306 $insertOptions = $this->makeInsertOptions( $insertOptions );
2308 if ( !is_array( $selectOptions ) ) {
2309 $selectOptions = [ $selectOptions ];
2312 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2315 if ( is_array( $srcTable ) ) {
2316 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2318 $srcTable = $this->tableName( $srcTable );
2321 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2322 " SELECT $startOpts " . implode( ',', $varMap ) .
2323 " FROM $srcTable $useIndex $ignoreIndex ";
2325 if ( $conds != '*' ) {
2326 if ( is_array( $conds ) ) {
2327 $conds = $this->makeList( $conds, LIST_AND
);
2329 $sql .= " WHERE $conds";
2332 $sql .= " $tailOpts";
2334 return $this->query( $sql, $fname );
2338 * Construct a LIMIT query with optional offset. This is used for query
2339 * pages. The SQL should be adjusted so that only the first $limit rows
2340 * are returned. If $offset is provided as well, then the first $offset
2341 * rows should be discarded, and the next $limit rows should be returned.
2342 * If the result of the query is not ordered, then the rows to be returned
2343 * are theoretically arbitrary.
2345 * $sql is expected to be a SELECT, if that makes a difference.
2347 * The version provided by default works in MySQL and SQLite. It will very
2348 * likely need to be overridden for most other DBMSes.
2350 * @param string $sql SQL query we will append the limit too
2351 * @param int $limit The SQL limit
2352 * @param int|bool $offset The SQL offset (default false)
2353 * @throws DBUnexpectedError
2356 public function limitResult( $sql, $limit, $offset = false ) {
2357 if ( !is_numeric( $limit ) ) {
2358 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2361 return "$sql LIMIT "
2362 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2366 public function unionSupportsOrderAndLimit() {
2367 return true; // True for almost every DB supported
2370 public function unionQueries( $sqls, $all ) {
2371 $glue = $all ?
') UNION ALL (' : ') UNION (';
2373 return '(' . implode( $glue, $sqls ) . ')';
2376 public function conditional( $cond, $trueVal, $falseVal ) {
2377 if ( is_array( $cond ) ) {
2378 $cond = $this->makeList( $cond, LIST_AND
);
2381 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2384 public function strreplace( $orig, $old, $new ) {
2385 return "REPLACE({$orig}, {$old}, {$new})";
2388 public function getServerUptime() {
2392 public function wasDeadlock() {
2396 public function wasLockTimeout() {
2400 public function wasErrorReissuable() {
2404 public function wasReadOnlyError() {
2409 * Determines if the given query error was a connection drop
2412 * @param integer|string $errno
2415 public function wasConnectionError( $errno ) {
2420 * Perform a deadlock-prone transaction.
2422 * This function invokes a callback function to perform a set of write
2423 * queries. If a deadlock occurs during the processing, the transaction
2424 * will be rolled back and the callback function will be called again.
2426 * Avoid using this method outside of Job or Maintenance classes.
2429 * $dbw->deadlockLoop( callback, ... );
2431 * Extra arguments are passed through to the specified callback function.
2432 * This method requires that no transactions are already active to avoid
2433 * causing premature commits or exceptions.
2435 * Returns whatever the callback function returned on its successful,
2436 * iteration, or false on error, for example if the retry limit was
2440 * @throws DBUnexpectedError
2443 public function deadlockLoop() {
2444 $args = func_get_args();
2445 $function = array_shift( $args );
2446 $tries = self
::DEADLOCK_TRIES
;
2448 $this->begin( __METHOD__
);
2451 /** @var Exception $e */
2455 $retVal = call_user_func_array( $function, $args );
2457 } catch ( DBQueryError
$e ) {
2458 if ( $this->wasDeadlock() ) {
2459 // Retry after a randomized delay
2460 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2462 // Throw the error back up
2466 } while ( --$tries > 0 );
2468 if ( $tries <= 0 ) {
2469 // Too many deadlocks; give up
2470 $this->rollback( __METHOD__
);
2473 $this->commit( __METHOD__
);
2479 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2480 # Real waits are implemented in the subclass.
2484 public function getSlavePos() {
2489 public function getMasterPos() {
2494 public function serverIsReadOnly() {
2498 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2499 if ( !$this->mTrxLevel
) {
2500 throw new DBUnexpectedError( $this, "No transaction is active." );
2502 $this->mTrxEndCallbacks
[] = [ $callback, $fname ];
2505 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2506 $this->mTrxIdleCallbacks
[] = [ $callback, $fname ];
2507 if ( !$this->mTrxLevel
) {
2508 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2512 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2513 if ( $this->mTrxLevel
) {
2514 $this->mTrxPreCommitCallbacks
[] = [ $callback, $fname ];
2516 // If no transaction is active, then make one for this callback
2517 $this->startAtomic( __METHOD__
);
2519 call_user_func( $callback );
2520 $this->endAtomic( __METHOD__
);
2521 } catch ( Exception
$e ) {
2522 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2528 final public function setTransactionListener( $name, callable
$callback = null ) {
2530 $this->mTrxRecurringCallbacks
[$name] = $callback;
2532 unset( $this->mTrxRecurringCallbacks
[$name] );
2537 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2539 * This method should not be used outside of Database/LoadBalancer
2541 * @param bool $suppress
2544 final public function setTrxEndCallbackSuppression( $suppress ) {
2545 $this->mTrxEndCallbacksSuppressed
= $suppress;
2549 * Actually run and consume any "on transaction idle/resolution" callbacks.
2551 * This method should not be used outside of Database/LoadBalancer
2553 * @param integer $trigger IDatabase::TRIGGER_* constant
2557 public function runOnTransactionIdleCallbacks( $trigger ) {
2558 if ( $this->mTrxEndCallbacksSuppressed
) {
2562 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2563 /** @var Exception $e */
2564 $e = null; // first exception
2565 do { // callbacks may add callbacks :)
2566 $callbacks = array_merge(
2567 $this->mTrxIdleCallbacks
,
2568 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2570 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2571 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2572 foreach ( $callbacks as $callback ) {
2574 list( $phpCallback ) = $callback;
2575 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2576 call_user_func_array( $phpCallback, [ $trigger ] );
2578 $this->setFlag( DBO_TRX
); // restore automatic begin()
2580 $this->clearFlag( DBO_TRX
); // restore auto-commit
2582 } catch ( Exception
$ex ) {
2583 call_user_func( $this->errorLogger
, $ex );
2585 // Some callbacks may use startAtomic/endAtomic, so make sure
2586 // their transactions are ended so other callbacks don't fail
2587 if ( $this->trxLevel() ) {
2588 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2592 } while ( count( $this->mTrxIdleCallbacks
) );
2594 if ( $e instanceof Exception
) {
2595 throw $e; // re-throw any first exception
2600 * Actually run and consume any "on transaction pre-commit" callbacks.
2602 * This method should not be used outside of Database/LoadBalancer
2607 public function runOnTransactionPreCommitCallbacks() {
2608 $e = null; // first exception
2609 do { // callbacks may add callbacks :)
2610 $callbacks = $this->mTrxPreCommitCallbacks
;
2611 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2612 foreach ( $callbacks as $callback ) {
2614 list( $phpCallback ) = $callback;
2615 call_user_func( $phpCallback );
2616 } catch ( Exception
$ex ) {
2617 call_user_func( $this->errorLogger
, $ex );
2621 } while ( count( $this->mTrxPreCommitCallbacks
) );
2623 if ( $e instanceof Exception
) {
2624 throw $e; // re-throw any first exception
2629 * Actually run any "transaction listener" callbacks.
2631 * This method should not be used outside of Database/LoadBalancer
2633 * @param integer $trigger IDatabase::TRIGGER_* constant
2637 public function runTransactionListenerCallbacks( $trigger ) {
2638 if ( $this->mTrxEndCallbacksSuppressed
) {
2642 /** @var Exception $e */
2643 $e = null; // first exception
2645 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2647 $phpCallback( $trigger, $this );
2648 } catch ( Exception
$ex ) {
2649 call_user_func( $this->errorLogger
, $ex );
2654 if ( $e instanceof Exception
) {
2655 throw $e; // re-throw any first exception
2659 final public function startAtomic( $fname = __METHOD__
) {
2660 if ( !$this->mTrxLevel
) {
2661 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2662 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2663 // in all changes being in one transaction to keep requests transactional.
2664 if ( !$this->getFlag( DBO_TRX
) ) {
2665 $this->mTrxAutomaticAtomic
= true;
2669 $this->mTrxAtomicLevels
[] = $fname;
2672 final public function endAtomic( $fname = __METHOD__
) {
2673 if ( !$this->mTrxLevel
) {
2674 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2676 if ( !$this->mTrxAtomicLevels ||
2677 array_pop( $this->mTrxAtomicLevels
) !== $fname
2679 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2682 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2683 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2687 final public function doAtomicSection( $fname, callable
$callback ) {
2688 $this->startAtomic( $fname );
2690 $res = call_user_func_array( $callback, [ $this, $fname ] );
2691 } catch ( Exception
$e ) {
2692 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2695 $this->endAtomic( $fname );
2700 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2701 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2702 if ( $this->mTrxLevel
) {
2703 if ( $this->mTrxAtomicLevels
) {
2704 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2705 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2706 throw new DBUnexpectedError( $this, $msg );
2707 } elseif ( !$this->mTrxAutomatic
) {
2708 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2709 throw new DBUnexpectedError( $this, $msg );
2711 // @TODO: make this an exception at some point
2712 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2713 $this->queryLogger
->error( $msg );
2714 return; // join the main transaction set
2716 } elseif ( $this->getFlag( DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2717 // @TODO: make this an exception at some point
2718 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2719 $this->queryLogger
->error( $msg );
2720 return; // let any writes be in the main transaction
2723 // Avoid fatals if close() was called
2724 $this->assertOpen();
2726 $this->doBegin( $fname );
2727 $this->mTrxTimestamp
= microtime( true );
2728 $this->mTrxFname
= $fname;
2729 $this->mTrxDoneWrites
= false;
2730 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2731 $this->mTrxAutomaticAtomic
= false;
2732 $this->mTrxAtomicLevels
= [];
2733 $this->mTrxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2734 $this->mTrxWriteDuration
= 0.0;
2735 $this->mTrxWriteQueryCount
= 0;
2736 $this->mTrxWriteAdjDuration
= 0.0;
2737 $this->mTrxWriteAdjQueryCount
= 0;
2738 $this->mTrxWriteCallers
= [];
2739 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2740 // Get an estimate of the replica DB lag before then, treating estimate staleness
2741 // as lag itself just to be safe
2742 $status = $this->getApproximateLagStatus();
2743 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2747 * Issues the BEGIN command to the database server.
2749 * @see DatabaseBase::begin()
2750 * @param string $fname
2752 protected function doBegin( $fname ) {
2753 $this->query( 'BEGIN', $fname );
2754 $this->mTrxLevel
= 1;
2757 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2758 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2759 // There are still atomic sections open. This cannot be ignored
2760 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2761 throw new DBUnexpectedError(
2763 "$fname: Got COMMIT while atomic sections $levels are still open."
2767 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2768 if ( !$this->mTrxLevel
) {
2769 return; // nothing to do
2770 } elseif ( !$this->mTrxAutomatic
) {
2771 throw new DBUnexpectedError(
2773 "$fname: Flushing an explicit transaction, getting out of sync."
2777 if ( !$this->mTrxLevel
) {
2778 $this->queryLogger
->error( "$fname: No transaction to commit, something got out of sync." );
2779 return; // nothing to do
2780 } elseif ( $this->mTrxAutomatic
) {
2781 // @TODO: make this an exception at some point
2782 $msg = "$fname: Explicit commit of implicit transaction.";
2783 $this->queryLogger
->error( $msg );
2784 return; // wait for the main transaction set commit round
2788 // Avoid fatals if close() was called
2789 $this->assertOpen();
2791 $this->runOnTransactionPreCommitCallbacks();
2792 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2793 $this->doCommit( $fname );
2794 if ( $this->mTrxDoneWrites
) {
2795 $this->mDoneWrites
= microtime( true );
2796 $this->trxProfiler
->transactionWritingOut(
2797 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2800 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2801 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
2805 * Issues the COMMIT command to the database server.
2807 * @see DatabaseBase::commit()
2808 * @param string $fname
2810 protected function doCommit( $fname ) {
2811 if ( $this->mTrxLevel
) {
2812 $this->query( 'COMMIT', $fname );
2813 $this->mTrxLevel
= 0;
2817 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2818 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2819 if ( !$this->mTrxLevel
) {
2820 return; // nothing to do
2823 if ( !$this->mTrxLevel
) {
2824 $this->queryLogger
->error(
2825 "$fname: No transaction to rollback, something got out of sync." );
2826 return; // nothing to do
2827 } elseif ( $this->getFlag( DBO_TRX
) ) {
2828 throw new DBUnexpectedError(
2830 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2835 // Avoid fatals if close() was called
2836 $this->assertOpen();
2838 $this->doRollback( $fname );
2839 $this->mTrxAtomicLevels
= [];
2840 if ( $this->mTrxDoneWrites
) {
2841 $this->trxProfiler
->transactionWritingOut(
2842 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
2845 $this->mTrxIdleCallbacks
= []; // clear
2846 $this->mTrxPreCommitCallbacks
= []; // clear
2847 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
2848 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
2852 * Issues the ROLLBACK command to the database server.
2854 * @see DatabaseBase::rollback()
2855 * @param string $fname
2857 protected function doRollback( $fname ) {
2858 if ( $this->mTrxLevel
) {
2859 # Disconnects cause rollback anyway, so ignore those errors
2860 $ignoreErrors = true;
2861 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
2862 $this->mTrxLevel
= 0;
2866 public function flushSnapshot( $fname = __METHOD__
) {
2867 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
2868 // This only flushes transactions to clear snapshots, not to write data
2869 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
2870 throw new DBUnexpectedError(
2872 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
2876 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2879 public function explicitTrxActive() {
2880 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
2884 * Creates a new table with structure copied from existing table
2885 * Note that unlike most database abstraction functions, this function does not
2886 * automatically append database prefix, because it works at a lower
2887 * abstraction level.
2888 * The table names passed to this function shall not be quoted (this
2889 * function calls addIdentifierQuotes when needed).
2891 * @param string $oldName Name of table whose structure should be copied
2892 * @param string $newName Name of table to be created
2893 * @param bool $temporary Whether the new table should be temporary
2894 * @param string $fname Calling function name
2895 * @throws RuntimeException
2896 * @return bool True if operation was successful
2898 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
2901 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2904 function listTables( $prefix = null, $fname = __METHOD__
) {
2905 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2909 * Reset the views process cache set by listViews()
2912 final public function clearViewsCache() {
2913 $this->allViews
= null;
2917 * Lists all the VIEWs in the database
2919 * For caching purposes the list of all views should be stored in
2920 * $this->allViews. The process cache can be cleared with clearViewsCache()
2922 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
2923 * @param string $fname Name of calling function
2924 * @throws RuntimeException
2928 public function listViews( $prefix = null, $fname = __METHOD__
) {
2929 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2933 * Differentiates between a TABLE and a VIEW
2935 * @param string $name Name of the database-structure to test.
2936 * @throws RuntimeException
2940 public function isView( $name ) {
2941 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2944 public function timestamp( $ts = 0 ) {
2945 $t = new ConvertableTimestamp( $ts );
2946 // Let errors bubble up to avoid putting garbage in the DB
2947 return $t->getTimestamp( TS_MW
);
2950 public function timestampOrNull( $ts = null ) {
2951 if ( is_null( $ts ) ) {
2954 return $this->timestamp( $ts );
2959 * Take the result from a query, and wrap it in a ResultWrapper if
2960 * necessary. Boolean values are passed through as is, to indicate success
2961 * of write queries or failure.
2963 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2964 * resource, and it was necessary to call this function to convert it to
2965 * a wrapper. Nowadays, raw database objects are never exposed to external
2966 * callers, so this is unnecessary in external code.
2968 * @param bool|ResultWrapper|resource|object $result
2969 * @return bool|ResultWrapper
2971 protected function resultObject( $result ) {
2974 } elseif ( $result instanceof ResultWrapper
) {
2976 } elseif ( $result === true ) {
2977 // Successful write query
2980 return new ResultWrapper( $this, $result );
2984 public function ping( &$rtt = null ) {
2985 // Avoid hitting the server if it was hit recently
2986 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
2987 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
2988 $rtt = $this->mRTTEstimate
;
2989 return true; // don't care about $rtt
2993 // This will reconnect if possible or return false if not
2994 $this->clearFlag( DBO_TRX
, self
::REMEMBER_PRIOR
);
2995 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
2996 $this->restoreFlags( self
::RESTORE_PRIOR
);
2999 $rtt = $this->mRTTEstimate
;
3008 protected function reconnect() {
3009 $this->closeConnection();
3010 $this->mOpened
= false;
3011 $this->mConn
= false;
3013 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3014 $this->lastPing
= microtime( true );
3016 } catch ( DBConnectionError
$e ) {
3023 public function getSessionLagStatus() {
3024 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3028 * Get the replica DB lag when the current transaction started
3030 * This is useful when transactions might use snapshot isolation
3031 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3032 * is this lag plus transaction duration. If they don't, it is still
3033 * safe to be pessimistic. This returns null if there is no transaction.
3035 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3038 public function getTransactionLagStatus() {
3039 return $this->mTrxLevel
3040 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3045 * Get a replica DB lag estimate for this server
3047 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3050 public function getApproximateLagStatus() {
3052 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3053 'since' => microtime( true )
3058 * Merge the result of getSessionLagStatus() for several DBs
3059 * using the most pessimistic values to estimate the lag of
3060 * any data derived from them in combination
3062 * This is information is useful for caching modules
3064 * @see WANObjectCache::set()
3065 * @see WANObjectCache::getWithSetCallback()
3067 * @param IDatabase $db1
3068 * @param IDatabase ...
3069 * @return array Map of values:
3070 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3071 * - since: oldest UNIX timestamp of any of the DB lag estimates
3072 * - pending: whether any of the DBs have uncommitted changes
3075 public static function getCacheSetOptions( IDatabase
$db1 ) {
3076 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3077 foreach ( func_get_args() as $db ) {
3078 /** @var IDatabase $db */
3079 $status = $db->getSessionLagStatus();
3080 if ( $status['lag'] === false ) {
3081 $res['lag'] = false;
3082 } elseif ( $res['lag'] !== false ) {
3083 $res['lag'] = max( $res['lag'], $status['lag'] );
3085 $res['since'] = min( $res['since'], $status['since'] );
3086 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3092 public function getLag() {
3096 function maxListLen() {
3100 public function encodeBlob( $b ) {
3104 public function decodeBlob( $b ) {
3105 if ( $b instanceof Blob
) {
3111 public function setSessionOptions( array $options ) {
3115 * Read and execute SQL commands from a file.
3117 * Returns true on success, error string or exception on failure (depending
3118 * on object's error ignore settings).
3120 * @param string $filename File name to open
3121 * @param bool|callable $lineCallback Optional function called before reading each line
3122 * @param bool|callable $resultCallback Optional function called for each MySQL result
3123 * @param bool|string $fname Calling function name or false if name should be
3124 * generated dynamically using $filename
3125 * @param bool|callable $inputCallback Optional function called for each
3126 * complete line sent
3127 * @return bool|string
3130 public function sourceFile(
3131 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3133 MediaWiki\
suppressWarnings();
3134 $fp = fopen( $filename, 'r' );
3135 MediaWiki\restoreWarnings
();
3137 if ( false === $fp ) {
3138 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3142 $fname = __METHOD__
. "( $filename )";
3146 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3147 } catch ( Exception
$e ) {
3157 public function setSchemaVars( $vars ) {
3158 $this->mSchemaVars
= $vars;
3162 * Read and execute commands from an open file handle.
3164 * Returns true on success, error string or exception on failure (depending
3165 * on object's error ignore settings).
3167 * @param resource $fp File handle
3168 * @param bool|callable $lineCallback Optional function called before reading each query
3169 * @param bool|callable $resultCallback Optional function called for each MySQL result
3170 * @param string $fname Calling function name
3171 * @param bool|callable $inputCallback Optional function called for each complete query sent
3172 * @return bool|string
3174 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3175 $fname = __METHOD__
, $inputCallback = false
3179 while ( !feof( $fp ) ) {
3180 if ( $lineCallback ) {
3181 call_user_func( $lineCallback );
3184 $line = trim( fgets( $fp ) );
3186 if ( $line == '' ) {
3190 if ( '-' == $line[0] && '-' == $line[1] ) {
3198 $done = $this->streamStatementEnd( $cmd, $line );
3202 if ( $done ||
feof( $fp ) ) {
3203 $cmd = $this->replaceVars( $cmd );
3205 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3206 $res = $this->query( $cmd, $fname );
3208 if ( $resultCallback ) {
3209 call_user_func( $resultCallback, $res, $this );
3212 if ( false === $res ) {
3213 $err = $this->lastError();
3215 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3226 * Called by sourceStream() to check if we've reached a statement end
3228 * @param string $sql SQL assembled so far
3229 * @param string $newLine New line about to be added to $sql
3230 * @return bool Whether $newLine contains end of the statement
3232 public function streamStatementEnd( &$sql, &$newLine ) {
3233 if ( $this->delimiter
) {
3235 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3236 if ( $newLine != $prev ) {
3245 * Database independent variable replacement. Replaces a set of variables
3246 * in an SQL statement with their contents as given by $this->getSchemaVars().
3248 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3250 * - '{$var}' should be used for text and is passed through the database's
3252 * - `{$var}` should be used for identifiers (e.g. table and database names).
3253 * It is passed through the database's addIdentifierQuotes method which
3254 * can be overridden if the database uses something other than backticks.
3255 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3256 * database's tableName method.
3257 * - / *i* / passes the name that follows through the database's indexName method.
3258 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3259 * its use should be avoided. In 1.24 and older, string encoding was applied.
3261 * @param string $ins SQL statement to replace variables in
3262 * @return string The new SQL statement with variables replaced
3264 protected function replaceVars( $ins ) {
3265 $vars = $this->getSchemaVars();
3266 return preg_replace_callback(
3268 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3269 \'\{\$ (\w+) }\' | # 3. addQuotes
3270 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3271 /\*\$ (\w+) \*/ # 5. leave unencoded
3273 function ( $m ) use ( $vars ) {
3274 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3275 // check for both nonexistent keys *and* the empty string.
3276 if ( isset( $m[1] ) && $m[1] !== '' ) {
3277 if ( $m[1] === 'i' ) {
3278 return $this->indexName( $m[2] );
3280 return $this->tableName( $m[2] );
3282 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3283 return $this->addQuotes( $vars[$m[3]] );
3284 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3285 return $this->addIdentifierQuotes( $vars[$m[4]] );
3286 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3287 return $vars[$m[5]];
3297 * Get schema variables. If none have been set via setSchemaVars(), then
3298 * use some defaults from the current object.
3302 protected function getSchemaVars() {
3303 if ( $this->mSchemaVars
) {
3304 return $this->mSchemaVars
;
3306 return $this->getDefaultSchemaVars();
3311 * Get schema variables to use if none have been set via setSchemaVars().
3313 * Override this in derived classes to provide variables for tables.sql
3314 * and SQL patch files.
3318 protected function getDefaultSchemaVars() {
3322 public function lockIsFree( $lockName, $method ) {
3326 public function lock( $lockName, $method, $timeout = 5 ) {
3327 $this->mNamedLocksHeld
[$lockName] = 1;
3332 public function unlock( $lockName, $method ) {
3333 unset( $this->mNamedLocksHeld
[$lockName] );
3338 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3339 if ( $this->writesOrCallbacksPending() ) {
3340 // This only flushes transactions to clear snapshots, not to write data
3341 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3342 throw new DBUnexpectedError(
3344 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
3348 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3352 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3353 if ( $this->trxLevel() ) {
3354 // There is a good chance an exception was thrown, causing any early return
3355 // from the caller. Let any error handler get a chance to issue rollback().
3356 // If there isn't one, let the error bubble up and trigger server-side rollback.
3357 $this->onTransactionResolution(
3358 function () use ( $lockKey, $fname ) {
3359 $this->unlock( $lockKey, $fname );
3364 $this->unlock( $lockKey, $fname );
3368 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3373 public function namedLocksEnqueue() {
3378 * Lock specific tables
3380 * @param array $read Array of tables to lock for read access
3381 * @param array $write Array of tables to lock for write access
3382 * @param string $method Name of caller
3383 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3386 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3391 * Unlock specific tables
3393 * @param string $method The caller
3396 public function unlockTables( $method ) {
3402 * @param string $tableName
3403 * @param string $fName
3404 * @return bool|ResultWrapper
3407 public function dropTable( $tableName, $fName = __METHOD__
) {
3408 if ( !$this->tableExists( $tableName, $fName ) ) {
3411 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3413 return $this->query( $sql, $fName );
3416 public function getInfinity() {
3420 public function encodeExpiry( $expiry ) {
3421 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3422 ?
$this->getInfinity()
3423 : $this->timestamp( $expiry );
3426 public function decodeExpiry( $expiry, $format = TS_MW
) {
3427 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3432 $t = new ConvertableTimestamp( $expiry );
3434 return $t->getTimestamp( $format );
3435 } catch ( TimestampException
$e ) {
3440 public function setBigSelects( $value = true ) {
3444 public function isReadOnly() {
3445 return ( $this->getReadOnlyReason() !== false );
3449 * @return string|bool Reason this DB is read-only or false if it is not
3451 protected function getReadOnlyReason() {
3452 $reason = $this->getLBInfo( 'readOnlyReason' );
3454 return is_string( $reason ) ?
$reason : false;
3457 public function setTableAliases( array $aliases ) {
3458 $this->tableAliases
= $aliases;
3465 public function __toString() {
3466 return (string)$this->mConn
;
3470 * Called by serialize. Throw an exception when DB connection is serialized.
3471 * This causes problems on some database engines because the connection is
3472 * not restored on unserialize.
3474 public function __sleep() {
3475 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3476 'the connection is not restored on wakeup.' );
3480 * Run a few simple sanity checks
3482 public function __destruct() {
3483 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3484 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3487 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3488 if ( $danglingWriters ) {
3489 $fnames = implode( ', ', $danglingWriters );
3490 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );