3 * @defgroup Database Database
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
26 use Psr\Log\LoggerAwareInterface
;
27 use Psr\Log\LoggerInterface
;
30 * Database abstraction object
33 abstract class Database
implements IDatabase
, LoggerAwareInterface
{
34 /** Number of times to re-try an operation in case of deadlock */
35 const DEADLOCK_TRIES
= 4;
36 /** Minimum time to wait before retry, in microseconds */
37 const DEADLOCK_DELAY_MIN
= 500000;
38 /** Maximum time to wait before retry */
39 const DEADLOCK_DELAY_MAX
= 1500000;
41 /** How long before it is worth doing a dummy query to test the connection */
43 const PING_QUERY
= 'SELECT 1 AS ping';
45 const TINY_WRITE_SEC
= .010;
46 const SLOW_WRITE_SEC
= .500;
47 const SMALL_WRITE_ROWS
= 100;
49 /** @var string SQL query */
50 protected $mLastQuery = '';
52 protected $mDoneWrites = false;
53 /** @var string|bool */
54 protected $mPHPError = false;
63 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
64 protected $tableAliases = [];
65 /** @var bool Whether this PHP instance is for a CLI script */
67 /** @var string Agent name for query profiling */
70 /** @var BagOStuff APC cache */
72 /** @var LoggerInterface */
73 protected $connLogger;
74 /** @var LoggerInterface */
75 protected $queryLogger;
76 /** @var callback Error logging callback */
77 protected $errorLogger;
79 /** @var resource Database connection */
80 protected $mConn = null;
82 protected $mOpened = false;
84 /** @var array[] List of (callable, method name) */
85 protected $mTrxIdleCallbacks = [];
86 /** @var array[] List of (callable, method name) */
87 protected $mTrxPreCommitCallbacks = [];
88 /** @var array[] List of (callable, method name) */
89 protected $mTrxEndCallbacks = [];
90 /** @var callable[] Map of (name => callable) */
91 protected $mTrxRecurringCallbacks = [];
92 /** @var bool Whether to suppress triggering of transaction end callbacks */
93 protected $mTrxEndCallbacksSuppressed = false;
96 protected $mTablePrefix = '';
98 protected $mSchema = '';
102 protected $mLBInfo = [];
103 /** @var bool|null */
104 protected $mDefaultBigSelects = null;
105 /** @var array|bool */
106 protected $mSchemaVars = false;
108 protected $mSessionVars = [];
109 /** @var array|null */
110 protected $preparedArgs;
111 /** @var string|bool|null Stashed value of html_errors INI setting */
112 protected $htmlErrors;
114 protected $delimiter = ';';
115 /** @var DatabaseDomain */
116 protected $currentDomain;
119 * Either 1 if a transaction is active or 0 otherwise.
120 * The other Trx fields may not be meaningfull if this is 0.
124 protected $mTrxLevel = 0;
126 * Either a short hexidecimal string if a transaction is active or ""
129 * @see DatabaseBase::mTrxLevel
131 protected $mTrxShortId = '';
133 * The UNIX time that the transaction started. Callers can assume that if
134 * snapshot isolation is used, then the data is *at least* up to date to that
135 * point (possibly more up-to-date since the first SELECT defines the snapshot).
138 * @see DatabaseBase::mTrxLevel
140 private $mTrxTimestamp = null;
141 /** @var float Lag estimate at the time of BEGIN */
142 private $mTrxReplicaLag = null;
144 * Remembers the function name given for starting the most recent transaction via begin().
145 * Used to provide additional context for error reporting.
148 * @see DatabaseBase::mTrxLevel
150 private $mTrxFname = null;
152 * Record if possible write queries were done in the last transaction started
155 * @see DatabaseBase::mTrxLevel
157 private $mTrxDoneWrites = false;
159 * Record if the current transaction was started implicitly due to DBO_TRX being set.
162 * @see DatabaseBase::mTrxLevel
164 private $mTrxAutomatic = false;
166 * Array of levels of atomicity within transactions
170 private $mTrxAtomicLevels = [];
172 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
176 private $mTrxAutomaticAtomic = false;
178 * Track the write query callers of the current transaction
182 private $mTrxWriteCallers = [];
184 * @var float Seconds spent in write queries for the current transaction
186 private $mTrxWriteDuration = 0.0;
188 * @var integer Number of write queries for the current transaction
190 private $mTrxWriteQueryCount = 0;
192 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
194 private $mTrxWriteAdjDuration = 0.0;
196 * @var integer Number of write queries counted in mTrxWriteAdjDuration
198 private $mTrxWriteAdjQueryCount = 0;
200 * @var float RTT time estimate
202 private $mRTTEstimate = 0.0;
204 /** @var array Map of (name => 1) for locks obtained via lock() */
205 private $mNamedLocksHeld = [];
207 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
208 private $lazyMasterHandle;
212 * @var resource File handle for upgrade
214 protected $fileHandle = null;
218 * @var string[] Process cache of VIEWs names in the database
220 protected $allViews = null;
222 /** @var float UNIX timestamp */
223 protected $lastPing = 0.0;
225 /** @var int[] Prior mFlags values */
226 private $priorFlags = [];
228 /** @var object|string Class name or object With profileIn/profileOut methods */
230 /** @var TransactionProfiler */
231 protected $trxProfiler;
234 * Constructor and database handle and attempt to connect to the DB server
236 * IDatabase classes should not be constructed directly in external
237 * code. Database::factory() should be used instead.
239 * @param array $params Parameters passed from Database::factory()
241 function __construct( array $params ) {
242 $server = $params['host'];
243 $user = $params['user'];
244 $password = $params['password'];
245 $dbName = $params['dbname'];
247 $this->mSchema
= $params['schema'];
248 $this->mTablePrefix
= $params['tablePrefix'];
250 $this->cliMode
= $params['cliMode'];
251 // Agent name is added to SQL queries in a comment, so make sure it can't break out
252 $this->agent
= str_replace( '/', '-', $params['agent'] );
254 $this->mFlags
= $params['flags'];
255 if ( $this->mFlags
& DBO_DEFAULT
) {
256 if ( $this->cliMode
) {
257 $this->mFlags
&= ~DBO_TRX
;
259 $this->mFlags |
= DBO_TRX
;
263 $this->mSessionVars
= $params['variables'];
265 $this->srvCache
= isset( $params['srvCache'] )
266 ?
$params['srvCache']
267 : new HashBagOStuff();
269 $this->profiler
= $params['profiler'];
270 $this->trxProfiler
= $params['trxProfiler'];
271 $this->connLogger
= $params['connLogger'];
272 $this->queryLogger
= $params['queryLogger'];
274 // Set initial dummy domain until open() sets the final DB/prefix
275 $this->currentDomain
= DatabaseDomain
::newUnspecified();
278 $this->open( $server, $user, $password, $dbName );
279 } elseif ( $this->requiresDatabaseUser() ) {
280 throw new InvalidArgumentException( "No database user provided." );
283 // Set the domain object after open() sets the relevant fields
284 if ( $this->mDBname
!= '' ) {
285 // Domains with server scope but a table prefix are not used by IDatabase classes
286 $this->currentDomain
= new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
);
291 * Construct a Database subclass instance given a database type and parameters
293 * This also connects to the database immediately upon object construction
295 * @param string $dbType A possible DB type (sqlite, mysql, postgres)
296 * @param array $p Parameter map with keys:
297 * - host : The hostname of the DB server
298 * - user : The name of the database user the client operates under
299 * - password : The password for the database user
300 * - dbname : The name of the database to use where queries do not specify one.
301 * The database must exist or an error might be thrown. Setting this to the empty string
302 * will avoid any such errors and make the handle have no implicit database scope. This is
303 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
304 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
305 * in which user names and such are defined, e.g. users are database-specific in Postgres.
306 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
307 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
308 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
309 * recognized in queries. This can be used in place of schemas for handle site farms.
310 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
311 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
312 * flag in place UNLESS this this database simply acts as a key/value store.
313 * - driver: Optional name of a specific DB client driver. For MySQL, there is the old
314 * 'mysql' driver and the newer 'mysqli' driver.
315 * - variables: Optional map of session variables to set after connecting. This can be
316 * used to adjust lock timeouts or encoding modes and the like.
317 * - connLogger: Optional PSR-3 logger interface instance.
318 * - queryLogger: Optional PSR-3 logger interface instance.
319 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
320 * These will be called in query(), using a simplified version of the SQL that also
321 * includes the agent as a SQL comment.
322 * - trxProfiler: Optional TransactionProfiler instance.
323 * - errorLogger: Optional callback that takes an Exception and logs it.
324 * - cliMode: Whether to consider the execution context that of a CLI script.
325 * - agent: Optional name used to identify the end-user in query profiling/logging.
326 * - srvCache: Optional BagOStuff instance to an APC-style cache.
327 * @return Database|null If the database driver or extension cannot be found
328 * @throws InvalidArgumentException If the database driver or extension cannot be found
331 final public static function factory( $dbType, $p = [] ) {
332 static $canonicalDBTypes = [
333 'mysql' => [ 'mysqli', 'mysql' ],
341 $dbType = strtolower( $dbType );
342 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
343 $possibleDrivers = $canonicalDBTypes[$dbType];
344 if ( !empty( $p['driver'] ) ) {
345 if ( in_array( $p['driver'], $possibleDrivers ) ) {
346 $driver = $p['driver'];
348 throw new InvalidArgumentException( __METHOD__
.
349 " type '$dbType' does not support driver '{$p['driver']}'" );
352 foreach ( $possibleDrivers as $posDriver ) {
353 if ( extension_loaded( $posDriver ) ) {
354 $driver = $posDriver;
362 if ( $driver === false ) {
363 throw new InvalidArgumentException( __METHOD__
.
364 " no viable database extension found for type '$dbType'" );
367 $class = 'Database' . ucfirst( $driver );
368 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
369 // Resolve some defaults for b/c
370 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
371 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
372 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
373 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
374 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
375 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
376 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
377 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
378 $p['cliMode'] = isset( $p['cliMode'] ) ?
$p['cliMode'] : ( PHP_SAPI
=== 'cli' );
379 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
380 if ( !isset( $p['connLogger'] ) ) {
381 $p['connLogger'] = new \Psr\Log\
NullLogger();
383 if ( !isset( $p['queryLogger'] ) ) {
384 $p['queryLogger'] = new \Psr\Log\
NullLogger();
386 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
387 if ( !isset( $p['trxProfiler'] ) ) {
388 $p['trxProfiler'] = new TransactionProfiler();
390 if ( !isset( $p['errorLogger'] ) ) {
391 $p['errorLogger'] = function ( Exception
$e ) {
392 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_WARNING
);
396 $conn = new $class( $p );
404 public function setLogger( LoggerInterface
$logger ) {
405 $this->queryLogger
= $logger;
408 public function getServerInfo() {
409 return $this->getServerVersion();
412 public function bufferResults( $buffer = null ) {
413 $res = !$this->getFlag( DBO_NOBUFFER
);
414 if ( $buffer !== null ) {
415 $buffer ?
$this->clearFlag( DBO_NOBUFFER
) : $this->setFlag( DBO_NOBUFFER
);
422 * Turns on (false) or off (true) the automatic generation and sending
423 * of a "we're sorry, but there has been a database error" page on
424 * database errors. Default is on (false). When turned off, the
425 * code should use lastErrno() and lastError() to handle the
426 * situation as appropriate.
428 * Do not use this function outside of the Database classes.
430 * @param null|bool $ignoreErrors
431 * @return bool The previous value of the flag.
433 protected function ignoreErrors( $ignoreErrors = null ) {
434 $res = $this->getFlag( DBO_IGNORE
);
435 if ( $ignoreErrors !== null ) {
436 $ignoreErrors ?
$this->setFlag( DBO_IGNORE
) : $this->clearFlag( DBO_IGNORE
);
442 public function trxLevel() {
443 return $this->mTrxLevel
;
446 public function trxTimestamp() {
447 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
450 public function tablePrefix( $prefix = null ) {
451 $old = $this->mTablePrefix
;
452 if ( $prefix !== null ) {
453 $this->mTablePrefix
= $prefix;
454 $this->currentDomain
= ( $this->mDBname
!= '' )
455 ?
new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
)
456 : DatabaseDomain
::newUnspecified();
462 public function dbSchema( $schema = null ) {
463 $old = $this->mSchema
;
464 if ( $schema !== null ) {
465 $this->mSchema
= $schema;
472 * Set the filehandle to copy write statements to.
474 * @param resource $fh File handle
476 public function setFileHandle( $fh ) {
477 $this->fileHandle
= $fh;
480 public function getLBInfo( $name = null ) {
481 if ( is_null( $name ) ) {
482 return $this->mLBInfo
;
484 if ( array_key_exists( $name, $this->mLBInfo
) ) {
485 return $this->mLBInfo
[$name];
492 public function setLBInfo( $name, $value = null ) {
493 if ( is_null( $value ) ) {
494 $this->mLBInfo
= $name;
496 $this->mLBInfo
[$name] = $value;
500 public function setLazyMasterHandle( IDatabase
$conn ) {
501 $this->lazyMasterHandle
= $conn;
505 * @return IDatabase|null
506 * @see setLazyMasterHandle()
509 public function getLazyMasterHandle() {
510 return $this->lazyMasterHandle
;
513 public function implicitGroupby() {
517 public function implicitOrderby() {
521 public function lastQuery() {
522 return $this->mLastQuery
;
525 public function doneWrites() {
526 return (bool)$this->mDoneWrites
;
529 public function lastDoneWrites() {
530 return $this->mDoneWrites ?
: false;
533 public function writesPending() {
534 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
537 public function writesOrCallbacksPending() {
538 return $this->mTrxLevel
&& (
539 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
543 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
544 if ( !$this->mTrxLevel
) {
546 } elseif ( !$this->mTrxDoneWrites
) {
551 case self
::ESTIMATE_DB_APPLY
:
553 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
554 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
555 // For omitted queries, make them count as something at least
556 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
557 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
560 default: // everything
561 return $this->mTrxWriteDuration
;
565 public function pendingWriteCallers() {
566 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
569 protected function pendingWriteAndCallbackCallers() {
570 if ( !$this->mTrxLevel
) {
574 $fnames = $this->mTrxWriteCallers
;
576 $this->mTrxIdleCallbacks
,
577 $this->mTrxPreCommitCallbacks
,
578 $this->mTrxEndCallbacks
580 foreach ( $callbacks as $callback ) {
581 $fnames[] = $callback[1];
588 public function isOpen() {
589 return $this->mOpened
;
592 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
593 if ( $remember === self
::REMEMBER_PRIOR
) {
594 array_push( $this->priorFlags
, $this->mFlags
);
596 $this->mFlags |
= $flag;
599 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
600 if ( $remember === self
::REMEMBER_PRIOR
) {
601 array_push( $this->priorFlags
, $this->mFlags
);
603 $this->mFlags
&= ~
$flag;
606 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
607 if ( !$this->priorFlags
) {
611 if ( $state === self
::RESTORE_INITIAL
) {
612 $this->mFlags
= reset( $this->priorFlags
);
613 $this->priorFlags
= [];
615 $this->mFlags
= array_pop( $this->priorFlags
);
619 public function getFlag( $flag ) {
620 return !!( $this->mFlags
& $flag );
623 public function getProperty( $name ) {
627 public function getDomainID() {
628 return $this->currentDomain
->getId();
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-3 logger 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 if ( $this->profiler
) {
896 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
898 $ret = $this->doQuery( $commentedSql );
899 if ( $this->profiler
) {
900 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
902 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
904 unset( $queryProfSection ); // profile out (if set)
906 if ( $ret !== false ) {
907 $this->lastPing
= $startTime;
908 if ( $isWrite && $this->mTrxLevel
) {
909 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
910 $this->mTrxWriteCallers
[] = $fname;
914 if ( $sql === self
::PING_QUERY
) {
915 $this->mRTTEstimate
= $queryRuntime;
918 $this->trxProfiler
->recordQueryCompletion(
919 $queryProf, $startTime, $isWrite, $this->affectedRows()
921 $this->queryLogger
->debug( $sql, [
923 'master' => $isMaster,
924 'runtime' => $queryRuntime,
931 * Update the estimated run-time of a query, not counting large row lock times
933 * LoadBalancer can be set to rollback transactions that will create huge replication
934 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
935 * queries, like inserting a row can take a long time due to row locking. This method
936 * uses some simple heuristics to discount those cases.
938 * @param string $sql A SQL write query
939 * @param float $runtime Total runtime, including RTT
941 private function updateTrxWriteQueryTime( $sql, $runtime ) {
942 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
943 $indicativeOfReplicaRuntime = true;
944 if ( $runtime > self
::SLOW_WRITE_SEC
) {
945 $verb = $this->getQueryVerb( $sql );
946 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
947 if ( $verb === 'INSERT' ) {
948 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
949 } elseif ( $verb === 'REPLACE' ) {
950 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
954 $this->mTrxWriteDuration +
= $runtime;
955 $this->mTrxWriteQueryCount +
= 1;
956 if ( $indicativeOfReplicaRuntime ) {
957 $this->mTrxWriteAdjDuration +
= $runtime;
958 $this->mTrxWriteAdjQueryCount +
= 1;
962 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
963 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
964 # Dropped connections also mean that named locks are automatically released.
965 # Only allow error suppression in autocommit mode or when the lost transaction
966 # didn't matter anyway (aside from DBO_TRX snapshot loss).
967 if ( $this->mNamedLocksHeld
) {
968 return false; // possible critical section violation
969 } elseif ( $sql === 'COMMIT' ) {
970 return !$priorWritesPending; // nothing written anyway? (T127428)
971 } elseif ( $sql === 'ROLLBACK' ) {
972 return true; // transaction lost...which is also what was requested :)
973 } elseif ( $this->explicitTrxActive() ) {
974 return false; // don't drop atomocity
975 } elseif ( $priorWritesPending ) {
976 return false; // prior writes lost from implicit transaction
982 private function handleTransactionLoss() {
983 $this->mTrxLevel
= 0;
984 $this->mTrxIdleCallbacks
= []; // bug 65263
985 $this->mTrxPreCommitCallbacks
= []; // bug 65263
987 // Handle callbacks in mTrxEndCallbacks
988 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
989 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
991 } catch ( Exception
$e ) {
992 // Already logged; move on...
997 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
998 if ( $this->ignoreErrors() ||
$tempIgnore ) {
999 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1001 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1002 $this->queryLogger
->error(
1003 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1004 $this->getLogContext( [
1005 'method' => __METHOD__
,
1008 'sql1line' => $sql1line,
1012 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1013 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1017 public function freeResult( $res ) {
1020 public function selectField(
1021 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1023 if ( $var === '*' ) { // sanity
1024 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1027 if ( !is_array( $options ) ) {
1028 $options = [ $options ];
1031 $options['LIMIT'] = 1;
1033 $res = $this->select( $table, $var, $cond, $fname, $options );
1034 if ( $res === false ||
!$this->numRows( $res ) ) {
1038 $row = $this->fetchRow( $res );
1040 if ( $row !== false ) {
1041 return reset( $row );
1047 public function selectFieldValues(
1048 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1050 if ( $var === '*' ) { // sanity
1051 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1052 } elseif ( !is_string( $var ) ) { // sanity
1053 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1056 if ( !is_array( $options ) ) {
1057 $options = [ $options ];
1060 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1061 if ( $res === false ) {
1066 foreach ( $res as $row ) {
1067 $values[] = $row->$var;
1074 * Returns an optional USE INDEX clause to go after the table, and a
1075 * string to go at the end of the query.
1077 * @param array $options Associative array of options to be turned into
1078 * an SQL query, valid keys are listed in the function.
1080 * @see DatabaseBase::select()
1082 public function makeSelectOptions( $options ) {
1083 $preLimitTail = $postLimitTail = '';
1088 foreach ( $options as $key => $option ) {
1089 if ( is_numeric( $key ) ) {
1090 $noKeyOptions[$option] = true;
1094 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1096 $preLimitTail .= $this->makeOrderBy( $options );
1098 // if (isset($options['LIMIT'])) {
1099 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1100 // isset($options['OFFSET']) ? $options['OFFSET']
1104 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1105 $postLimitTail .= ' FOR UPDATE';
1108 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1109 $postLimitTail .= ' LOCK IN SHARE MODE';
1112 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1113 $startOpts .= 'DISTINCT';
1116 # Various MySQL extensions
1117 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1118 $startOpts .= ' /*! STRAIGHT_JOIN */';
1121 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1122 $startOpts .= ' HIGH_PRIORITY';
1125 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1126 $startOpts .= ' SQL_BIG_RESULT';
1129 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1130 $startOpts .= ' SQL_BUFFER_RESULT';
1133 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1134 $startOpts .= ' SQL_SMALL_RESULT';
1137 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1138 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1141 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1142 $startOpts .= ' SQL_CACHE';
1145 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1146 $startOpts .= ' SQL_NO_CACHE';
1149 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1150 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1154 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1155 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1160 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1164 * Returns an optional GROUP BY with an optional HAVING
1166 * @param array $options Associative array of options
1168 * @see DatabaseBase::select()
1171 public function makeGroupByWithHaving( $options ) {
1173 if ( isset( $options['GROUP BY'] ) ) {
1174 $gb = is_array( $options['GROUP BY'] )
1175 ?
implode( ',', $options['GROUP BY'] )
1176 : $options['GROUP BY'];
1177 $sql .= ' GROUP BY ' . $gb;
1179 if ( isset( $options['HAVING'] ) ) {
1180 $having = is_array( $options['HAVING'] )
1181 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1182 : $options['HAVING'];
1183 $sql .= ' HAVING ' . $having;
1190 * Returns an optional ORDER BY
1192 * @param array $options Associative array of options
1194 * @see DatabaseBase::select()
1197 public function makeOrderBy( $options ) {
1198 if ( isset( $options['ORDER BY'] ) ) {
1199 $ob = is_array( $options['ORDER BY'] )
1200 ?
implode( ',', $options['ORDER BY'] )
1201 : $options['ORDER BY'];
1203 return ' ORDER BY ' . $ob;
1209 // See IDatabase::select for the docs for this function
1210 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1211 $options = [], $join_conds = [] ) {
1212 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1214 return $this->query( $sql, $fname );
1217 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1218 $options = [], $join_conds = []
1220 if ( is_array( $vars ) ) {
1221 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1224 $options = (array)$options;
1225 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1226 ?
$options['USE INDEX']
1228 $ignoreIndexes = ( isset( $options['IGNORE INDEX'] ) && is_array( $options['IGNORE INDEX'] ) )
1229 ?
$options['IGNORE INDEX']
1232 if ( is_array( $table ) ) {
1234 $this->tableNamesWithIndexClauseOrJOIN( $table, $useIndexes, $ignoreIndexes, $join_conds );
1235 } elseif ( $table != '' ) {
1236 if ( $table[0] == ' ' ) {
1237 $from = ' FROM ' . $table;
1240 $this->tableNamesWithIndexClauseOrJOIN( [ $table ], $useIndexes, $ignoreIndexes, [] );
1246 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1247 $this->makeSelectOptions( $options );
1249 if ( !empty( $conds ) ) {
1250 if ( is_array( $conds ) ) {
1251 $conds = $this->makeList( $conds, self
::LIST_AND
);
1253 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex WHERE $conds $preLimitTail";
1255 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1258 if ( isset( $options['LIMIT'] ) ) {
1259 $sql = $this->limitResult( $sql, $options['LIMIT'],
1260 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1262 $sql = "$sql $postLimitTail";
1264 if ( isset( $options['EXPLAIN'] ) ) {
1265 $sql = 'EXPLAIN ' . $sql;
1271 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1272 $options = [], $join_conds = []
1274 $options = (array)$options;
1275 $options['LIMIT'] = 1;
1276 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1278 if ( $res === false ) {
1282 if ( !$this->numRows( $res ) ) {
1286 $obj = $this->fetchObject( $res );
1291 public function estimateRowCount(
1292 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1295 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1298 $row = $this->fetchRow( $res );
1299 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1305 public function selectRowCount(
1306 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1309 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1310 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1313 $row = $this->fetchRow( $res );
1314 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1321 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1322 * It's only slightly flawed. Don't use for anything important.
1324 * @param string $sql A SQL Query
1328 protected static function generalizeSQL( $sql ) {
1329 # This does the same as the regexp below would do, but in such a way
1330 # as to avoid crashing php on some large strings.
1331 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1333 $sql = str_replace( "\\\\", '', $sql );
1334 $sql = str_replace( "\\'", '', $sql );
1335 $sql = str_replace( "\\\"", '', $sql );
1336 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1337 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1339 # All newlines, tabs, etc replaced by single space
1340 $sql = preg_replace( '/\s+/', ' ', $sql );
1343 # except the ones surrounded by characters, e.g. l10n
1344 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1345 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1350 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1351 $info = $this->fieldInfo( $table, $field );
1356 public function indexExists( $table, $index, $fname = __METHOD__
) {
1357 if ( !$this->tableExists( $table ) ) {
1361 $info = $this->indexInfo( $table, $index, $fname );
1362 if ( is_null( $info ) ) {
1365 return $info !== false;
1369 public function tableExists( $table, $fname = __METHOD__
) {
1370 $table = $this->tableName( $table );
1371 $old = $this->ignoreErrors( true );
1372 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1373 $this->ignoreErrors( $old );
1378 public function indexUnique( $table, $index ) {
1379 $indexInfo = $this->indexInfo( $table, $index );
1381 if ( !$indexInfo ) {
1385 return !$indexInfo[0]->Non_unique
;
1389 * Helper for DatabaseBase::insert().
1391 * @param array $options
1394 protected function makeInsertOptions( $options ) {
1395 return implode( ' ', $options );
1398 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1399 # No rows to insert, easy just return now
1400 if ( !count( $a ) ) {
1404 $table = $this->tableName( $table );
1406 if ( !is_array( $options ) ) {
1407 $options = [ $options ];
1411 if ( isset( $options['fileHandle'] ) ) {
1412 $fh = $options['fileHandle'];
1414 $options = $this->makeInsertOptions( $options );
1416 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1418 $keys = array_keys( $a[0] );
1421 $keys = array_keys( $a );
1424 $sql = 'INSERT ' . $options .
1425 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1429 foreach ( $a as $row ) {
1435 $sql .= '(' . $this->makeList( $row ) . ')';
1438 $sql .= '(' . $this->makeList( $a ) . ')';
1441 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1443 } elseif ( $fh !== null ) {
1447 return (bool)$this->query( $sql, $fname );
1451 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1453 * @param array $options
1456 protected function makeUpdateOptionsArray( $options ) {
1457 if ( !is_array( $options ) ) {
1458 $options = [ $options ];
1463 if ( in_array( 'IGNORE', $options ) ) {
1471 * Make UPDATE options for the DatabaseBase::update function
1473 * @param array $options The options passed to DatabaseBase::update
1476 protected function makeUpdateOptions( $options ) {
1477 $opts = $this->makeUpdateOptionsArray( $options );
1479 return implode( ' ', $opts );
1482 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1483 $table = $this->tableName( $table );
1484 $opts = $this->makeUpdateOptions( $options );
1485 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1487 if ( $conds !== [] && $conds !== '*' ) {
1488 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1491 return $this->query( $sql, $fname );
1494 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1495 if ( !is_array( $a ) ) {
1496 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1502 foreach ( $a as $field => $value ) {
1504 if ( $mode == self
::LIST_AND
) {
1506 } elseif ( $mode == self
::LIST_OR
) {
1515 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1516 $list .= "($value)";
1517 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1520 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1522 // Remove null from array to be handled separately if found
1523 $includeNull = false;
1524 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1525 $includeNull = true;
1526 unset( $value[$nullKey] );
1528 if ( count( $value ) == 0 && !$includeNull ) {
1529 throw new InvalidArgumentException(
1530 __METHOD__
. ": empty input for field $field" );
1531 } elseif ( count( $value ) == 0 ) {
1532 // only check if $field is null
1533 $list .= "$field IS NULL";
1535 // IN clause contains at least one valid element
1536 if ( $includeNull ) {
1537 // Group subconditions to ensure correct precedence
1540 if ( count( $value ) == 1 ) {
1541 // Special-case single values, as IN isn't terribly efficient
1542 // Don't necessarily assume the single key is 0; we don't
1543 // enforce linear numeric ordering on other arrays here.
1544 $value = array_values( $value )[0];
1545 $list .= $field . " = " . $this->addQuotes( $value );
1547 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1549 // if null present in array, append IS NULL
1550 if ( $includeNull ) {
1551 $list .= " OR $field IS NULL)";
1554 } elseif ( $value === null ) {
1555 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1556 $list .= "$field IS ";
1557 } elseif ( $mode == self
::LIST_SET
) {
1558 $list .= "$field = ";
1563 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1565 $list .= "$field = ";
1567 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1574 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1577 foreach ( $data as $base => $sub ) {
1578 if ( count( $sub ) ) {
1579 $conds[] = $this->makeList(
1580 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1586 return $this->makeList( $conds, self
::LIST_OR
);
1588 // Nothing to search for...
1594 * Return aggregated value alias
1596 * @param array $valuedata
1597 * @param string $valuename
1601 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1605 public function bitNot( $field ) {
1609 public function bitAnd( $fieldLeft, $fieldRight ) {
1610 return "($fieldLeft & $fieldRight)";
1613 public function bitOr( $fieldLeft, $fieldRight ) {
1614 return "($fieldLeft | $fieldRight)";
1617 public function buildConcat( $stringList ) {
1618 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1621 public function buildGroupConcatField(
1622 $delim, $table, $field, $conds = '', $join_conds = []
1624 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1626 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1630 * @param string $field Field or column to cast
1634 public function buildStringCast( $field ) {
1638 public function selectDB( $db ) {
1639 # Stub. Shouldn't cause serious problems if it's not overridden, but
1640 # if your database engine supports a concept similar to MySQL's
1641 # databases you may as well.
1642 $this->mDBname
= $db;
1647 public function getDBname() {
1648 return $this->mDBname
;
1651 public function getServer() {
1652 return $this->mServer
;
1656 * Format a table name ready for use in constructing an SQL query
1658 * This does two important things: it quotes the table names to clean them up,
1659 * and it adds a table prefix if only given a table name with no quotes.
1661 * All functions of this object which require a table name call this function
1662 * themselves. Pass the canonical name to such functions. This is only needed
1663 * when calling query() directly.
1665 * @note This function does not sanitize user input. It is not safe to use
1666 * this function to escape user input.
1667 * @param string $name Database table name
1668 * @param string $format One of:
1669 * quoted - Automatically pass the table name through addIdentifierQuotes()
1670 * so that it can be used in a query.
1671 * raw - Do not add identifier quotes to the table name
1672 * @return string Full database name
1674 public function tableName( $name, $format = 'quoted' ) {
1675 # Skip the entire process when we have a string quoted on both ends.
1676 # Note that we check the end so that we will still quote any use of
1677 # use of `database`.table. But won't break things if someone wants
1678 # to query a database table with a dot in the name.
1679 if ( $this->isQuotedIdentifier( $name ) ) {
1683 # Lets test for any bits of text that should never show up in a table
1684 # name. Basically anything like JOIN or ON which are actually part of
1685 # SQL queries, but may end up inside of the table value to combine
1686 # sql. Such as how the API is doing.
1687 # Note that we use a whitespace test rather than a \b test to avoid
1688 # any remote case where a word like on may be inside of a table name
1689 # surrounded by symbols which may be considered word breaks.
1690 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1694 # Split database and table into proper variables.
1695 # We reverse the explode so that database.table and table both output
1696 # the correct table.
1697 $dbDetails = explode( '.', $name, 3 );
1698 if ( count( $dbDetails ) == 3 ) {
1699 list( $database, $schema, $table ) = $dbDetails;
1700 # We don't want any prefix added in this case
1702 } elseif ( count( $dbDetails ) == 2 ) {
1703 list( $database, $table ) = $dbDetails;
1704 # We don't want any prefix added in this case
1705 # In dbs that support it, $database may actually be the schema
1706 # but that doesn't affect any of the functionality here
1710 list( $table ) = $dbDetails;
1711 if ( isset( $this->tableAliases
[$table] ) ) {
1712 $database = $this->tableAliases
[$table]['dbname'];
1713 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1714 ?
$this->tableAliases
[$table]['schema']
1716 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1717 ?
$this->tableAliases
[$table]['prefix']
1718 : $this->mTablePrefix
;
1721 $schema = $this->mSchema
; # Default schema
1722 $prefix = $this->mTablePrefix
; # Default prefix
1726 # Quote $table and apply the prefix if not quoted.
1727 # $tableName might be empty if this is called from Database::replaceVars()
1728 $tableName = "{$prefix}{$table}";
1729 if ( $format == 'quoted'
1730 && !$this->isQuotedIdentifier( $tableName ) && $tableName !== ''
1732 $tableName = $this->addIdentifierQuotes( $tableName );
1735 # Quote $schema and merge it with the table name if needed
1736 if ( strlen( $schema ) ) {
1737 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1738 $schema = $this->addIdentifierQuotes( $schema );
1740 $tableName = $schema . '.' . $tableName;
1743 # Quote $database and merge it with the table name if needed
1744 if ( $database !== '' ) {
1745 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1746 $database = $this->addIdentifierQuotes( $database );
1748 $tableName = $database . '.' . $tableName;
1755 * Fetch a number of table names into an array
1756 * This is handy when you need to construct SQL for joins
1759 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1760 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1761 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1765 public function tableNames() {
1766 $inArray = func_get_args();
1769 foreach ( $inArray as $name ) {
1770 $retVal[$name] = $this->tableName( $name );
1777 * Fetch a number of table names into an zero-indexed numerical array
1778 * This is handy when you need to construct SQL for joins
1781 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1782 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1783 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1787 public function tableNamesN() {
1788 $inArray = func_get_args();
1791 foreach ( $inArray as $name ) {
1792 $retVal[] = $this->tableName( $name );
1799 * Get an aliased table name
1800 * e.g. tableName AS newTableName
1802 * @param string $name Table name, see tableName()
1803 * @param string|bool $alias Alias (optional)
1804 * @return string SQL name for aliased table. Will not alias a table to its own name
1806 public function tableNameWithAlias( $name, $alias = false ) {
1807 if ( !$alias ||
$alias == $name ) {
1808 return $this->tableName( $name );
1810 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1815 * Gets an array of aliased table names
1817 * @param array $tables [ [alias] => table ]
1818 * @return string[] See tableNameWithAlias()
1820 public function tableNamesWithAlias( $tables ) {
1822 foreach ( $tables as $alias => $table ) {
1823 if ( is_numeric( $alias ) ) {
1826 $retval[] = $this->tableNameWithAlias( $table, $alias );
1833 * Get an aliased field name
1834 * e.g. fieldName AS newFieldName
1836 * @param string $name Field name
1837 * @param string|bool $alias Alias (optional)
1838 * @return string SQL name for aliased field. Will not alias a field to its own name
1840 public function fieldNameWithAlias( $name, $alias = false ) {
1841 if ( !$alias ||
(string)$alias === (string)$name ) {
1844 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1849 * Gets an array of aliased field names
1851 * @param array $fields [ [alias] => field ]
1852 * @return string[] See fieldNameWithAlias()
1854 public function fieldNamesWithAlias( $fields ) {
1856 foreach ( $fields as $alias => $field ) {
1857 if ( is_numeric( $alias ) ) {
1860 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1867 * Get the aliased table name clause for a FROM clause
1868 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
1870 * @param array $tables ( [alias] => table )
1871 * @param array $use_index Same as for select()
1872 * @param array $ignore_index Same as for select()
1873 * @param array $join_conds Same as for select()
1876 protected function tableNamesWithIndexClauseOrJOIN(
1877 $tables, $use_index = [], $ignore_index = [], $join_conds = []
1881 $use_index = (array)$use_index;
1882 $ignore_index = (array)$ignore_index;
1883 $join_conds = (array)$join_conds;
1885 foreach ( $tables as $alias => $table ) {
1886 if ( !is_string( $alias ) ) {
1887 // No alias? Set it equal to the table name
1890 // Is there a JOIN clause for this table?
1891 if ( isset( $join_conds[$alias] ) ) {
1892 list( $joinType, $conds ) = $join_conds[$alias];
1893 $tableClause = $joinType;
1894 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1895 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1896 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1898 $tableClause .= ' ' . $use;
1901 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
1902 $ignore = $this->ignoreIndexClause( implode( ',', (array)$ignore_index[$alias] ) );
1903 if ( $ignore != '' ) {
1904 $tableClause .= ' ' . $ignore;
1907 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
1909 $tableClause .= ' ON (' . $on . ')';
1912 $retJOIN[] = $tableClause;
1913 } elseif ( isset( $use_index[$alias] ) ) {
1914 // Is there an INDEX clause for this table?
1915 $tableClause = $this->tableNameWithAlias( $table, $alias );
1916 $tableClause .= ' ' . $this->useIndexClause(
1917 implode( ',', (array)$use_index[$alias] )
1920 $ret[] = $tableClause;
1921 } elseif ( isset( $ignore_index[$alias] ) ) {
1922 // Is there an INDEX clause for this table?
1923 $tableClause = $this->tableNameWithAlias( $table, $alias );
1924 $tableClause .= ' ' . $this->ignoreIndexClause(
1925 implode( ',', (array)$ignore_index[$alias] )
1928 $ret[] = $tableClause;
1930 $tableClause = $this->tableNameWithAlias( $table, $alias );
1932 $ret[] = $tableClause;
1936 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1937 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1938 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1940 // Compile our final table clause
1941 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
1945 * Get the name of an index in a given table.
1947 * @param string $index
1950 protected function indexName( $index ) {
1951 // Backwards-compatibility hack
1953 'ar_usertext_timestamp' => 'usertext_timestamp',
1954 'un_user_id' => 'user_id',
1955 'un_user_ip' => 'user_ip',
1958 if ( isset( $renamed[$index] ) ) {
1959 return $renamed[$index];
1965 public function addQuotes( $s ) {
1966 if ( $s instanceof Blob
) {
1969 if ( $s === null ) {
1972 # This will also quote numeric values. This should be harmless,
1973 # and protects against weird problems that occur when they really
1974 # _are_ strings such as article titles and string->number->string
1975 # conversion is not 1:1.
1976 return "'" . $this->strencode( $s ) . "'";
1981 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1982 * MySQL uses `backticks` while basically everything else uses double quotes.
1983 * Since MySQL is the odd one out here the double quotes are our generic
1984 * and we implement backticks in DatabaseMysql.
1989 public function addIdentifierQuotes( $s ) {
1990 return '"' . str_replace( '"', '""', $s ) . '"';
1994 * Returns if the given identifier looks quoted or not according to
1995 * the database convention for quoting identifiers .
1997 * @note Do not use this to determine if untrusted input is safe.
1998 * A malicious user can trick this function.
1999 * @param string $name
2002 public function isQuotedIdentifier( $name ) {
2003 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2010 protected function escapeLikeInternal( $s ) {
2011 return addcslashes( $s, '\%_' );
2014 public function buildLike() {
2015 $params = func_get_args();
2017 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2018 $params = $params[0];
2023 foreach ( $params as $value ) {
2024 if ( $value instanceof LikeMatch
) {
2025 $s .= $value->toString();
2027 $s .= $this->escapeLikeInternal( $value );
2031 return " LIKE {$this->addQuotes( $s )} ";
2034 public function anyChar() {
2035 return new LikeMatch( '_' );
2038 public function anyString() {
2039 return new LikeMatch( '%' );
2042 public function nextSequenceValue( $seqName ) {
2047 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2048 * is only needed because a) MySQL must be as efficient as possible due to
2049 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2050 * which index to pick. Anyway, other databases might have different
2051 * indexes on a given table. So don't bother overriding this unless you're
2053 * @param string $index
2056 public function useIndexClause( $index ) {
2061 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2062 * is only needed because a) MySQL must be as efficient as possible due to
2063 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2064 * which index to pick. Anyway, other databases might have different
2065 * indexes on a given table. So don't bother overriding this unless you're
2067 * @param string $index
2070 public function ignoreIndexClause( $index ) {
2074 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2075 $quotedTable = $this->tableName( $table );
2077 if ( count( $rows ) == 0 ) {
2082 if ( !is_array( reset( $rows ) ) ) {
2086 // @FXIME: this is not atomic, but a trx would break affectedRows()
2087 foreach ( $rows as $row ) {
2088 # Delete rows which collide
2089 if ( $uniqueIndexes ) {
2090 $sql = "DELETE FROM $quotedTable WHERE ";
2092 foreach ( $uniqueIndexes as $index ) {
2099 if ( is_array( $index ) ) {
2101 foreach ( $index as $col ) {
2107 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2110 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2114 $this->query( $sql, $fname );
2117 # Now insert the row
2118 $this->insert( $table, $row, $fname );
2123 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2126 * @param string $table Table name
2127 * @param array|string $rows Row(s) to insert
2128 * @param string $fname Caller function name
2130 * @return ResultWrapper
2132 protected function nativeReplace( $table, $rows, $fname ) {
2133 $table = $this->tableName( $table );
2136 if ( !is_array( reset( $rows ) ) ) {
2140 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2143 foreach ( $rows as $row ) {
2150 $sql .= '(' . $this->makeList( $row ) . ')';
2153 return $this->query( $sql, $fname );
2156 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2159 if ( !count( $rows ) ) {
2160 return true; // nothing to do
2163 if ( !is_array( reset( $rows ) ) ) {
2167 if ( count( $uniqueIndexes ) ) {
2168 $clauses = []; // list WHERE clauses that each identify a single row
2169 foreach ( $rows as $row ) {
2170 foreach ( $uniqueIndexes as $index ) {
2171 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2172 $rowKey = []; // unique key to this row
2173 foreach ( $index as $column ) {
2174 $rowKey[$column] = $row[$column];
2176 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2179 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2184 $useTrx = !$this->mTrxLevel
;
2186 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2189 # Update any existing conflicting row(s)
2190 if ( $where !== false ) {
2191 $ok = $this->update( $table, $set, $where, $fname );
2195 # Now insert any non-conflicting row(s)
2196 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2197 } catch ( Exception
$e ) {
2199 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2204 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2210 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2214 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2217 $delTable = $this->tableName( $delTable );
2218 $joinTable = $this->tableName( $joinTable );
2219 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2220 if ( $conds != '*' ) {
2221 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2225 $this->query( $sql, $fname );
2229 * Returns the size of a text field, or -1 for "unlimited"
2231 * @param string $table
2232 * @param string $field
2235 public function textFieldSize( $table, $field ) {
2236 $table = $this->tableName( $table );
2237 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2238 $res = $this->query( $sql, __METHOD__
);
2239 $row = $this->fetchObject( $res );
2243 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2252 public function delete( $table, $conds, $fname = __METHOD__
) {
2254 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2257 $table = $this->tableName( $table );
2258 $sql = "DELETE FROM $table";
2260 if ( $conds != '*' ) {
2261 if ( is_array( $conds ) ) {
2262 $conds = $this->makeList( $conds, self
::LIST_AND
);
2264 $sql .= ' WHERE ' . $conds;
2267 return $this->query( $sql, $fname );
2270 public function insertSelect(
2271 $destTable, $srcTable, $varMap, $conds,
2272 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2274 if ( $this->cliMode
) {
2275 // For massive migrations with downtime, we don't want to select everything
2276 // into memory and OOM, so do all this native on the server side if possible.
2277 return $this->nativeInsertSelect(
2288 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2289 // on only the master (without needing row-based-replication). It also makes it easy to
2290 // know how big the INSERT is going to be.
2292 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2293 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2295 $selectOptions[] = 'FOR UPDATE';
2296 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2302 foreach ( $res as $row ) {
2303 $rows[] = (array)$row;
2306 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2309 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2310 $fname = __METHOD__
,
2311 $insertOptions = [], $selectOptions = []
2313 $destTable = $this->tableName( $destTable );
2315 if ( !is_array( $insertOptions ) ) {
2316 $insertOptions = [ $insertOptions ];
2319 $insertOptions = $this->makeInsertOptions( $insertOptions );
2321 if ( !is_array( $selectOptions ) ) {
2322 $selectOptions = [ $selectOptions ];
2325 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2328 if ( is_array( $srcTable ) ) {
2329 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2331 $srcTable = $this->tableName( $srcTable );
2334 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2335 " SELECT $startOpts " . implode( ',', $varMap ) .
2336 " FROM $srcTable $useIndex $ignoreIndex ";
2338 if ( $conds != '*' ) {
2339 if ( is_array( $conds ) ) {
2340 $conds = $this->makeList( $conds, self
::LIST_AND
);
2342 $sql .= " WHERE $conds";
2345 $sql .= " $tailOpts";
2347 return $this->query( $sql, $fname );
2351 * Construct a LIMIT query with optional offset. This is used for query
2352 * pages. The SQL should be adjusted so that only the first $limit rows
2353 * are returned. If $offset is provided as well, then the first $offset
2354 * rows should be discarded, and the next $limit rows should be returned.
2355 * If the result of the query is not ordered, then the rows to be returned
2356 * are theoretically arbitrary.
2358 * $sql is expected to be a SELECT, if that makes a difference.
2360 * The version provided by default works in MySQL and SQLite. It will very
2361 * likely need to be overridden for most other DBMSes.
2363 * @param string $sql SQL query we will append the limit too
2364 * @param int $limit The SQL limit
2365 * @param int|bool $offset The SQL offset (default false)
2366 * @throws DBUnexpectedError
2369 public function limitResult( $sql, $limit, $offset = false ) {
2370 if ( !is_numeric( $limit ) ) {
2371 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2374 return "$sql LIMIT "
2375 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2379 public function unionSupportsOrderAndLimit() {
2380 return true; // True for almost every DB supported
2383 public function unionQueries( $sqls, $all ) {
2384 $glue = $all ?
') UNION ALL (' : ') UNION (';
2386 return '(' . implode( $glue, $sqls ) . ')';
2389 public function conditional( $cond, $trueVal, $falseVal ) {
2390 if ( is_array( $cond ) ) {
2391 $cond = $this->makeList( $cond, self
::LIST_AND
);
2394 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2397 public function strreplace( $orig, $old, $new ) {
2398 return "REPLACE({$orig}, {$old}, {$new})";
2401 public function getServerUptime() {
2405 public function wasDeadlock() {
2409 public function wasLockTimeout() {
2413 public function wasErrorReissuable() {
2417 public function wasReadOnlyError() {
2422 * Determines if the given query error was a connection drop
2425 * @param integer|string $errno
2428 public function wasConnectionError( $errno ) {
2433 * Perform a deadlock-prone transaction.
2435 * This function invokes a callback function to perform a set of write
2436 * queries. If a deadlock occurs during the processing, the transaction
2437 * will be rolled back and the callback function will be called again.
2439 * Avoid using this method outside of Job or Maintenance classes.
2442 * $dbw->deadlockLoop( callback, ... );
2444 * Extra arguments are passed through to the specified callback function.
2445 * This method requires that no transactions are already active to avoid
2446 * causing premature commits or exceptions.
2448 * Returns whatever the callback function returned on its successful,
2449 * iteration, or false on error, for example if the retry limit was
2453 * @throws DBUnexpectedError
2456 public function deadlockLoop() {
2457 $args = func_get_args();
2458 $function = array_shift( $args );
2459 $tries = self
::DEADLOCK_TRIES
;
2461 $this->begin( __METHOD__
);
2464 /** @var Exception $e */
2468 $retVal = call_user_func_array( $function, $args );
2470 } catch ( DBQueryError
$e ) {
2471 if ( $this->wasDeadlock() ) {
2472 // Retry after a randomized delay
2473 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2475 // Throw the error back up
2479 } while ( --$tries > 0 );
2481 if ( $tries <= 0 ) {
2482 // Too many deadlocks; give up
2483 $this->rollback( __METHOD__
);
2486 $this->commit( __METHOD__
);
2492 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2493 # Real waits are implemented in the subclass.
2497 public function getSlavePos() {
2502 public function getMasterPos() {
2507 public function serverIsReadOnly() {
2511 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2512 if ( !$this->mTrxLevel
) {
2513 throw new DBUnexpectedError( $this, "No transaction is active." );
2515 $this->mTrxEndCallbacks
[] = [ $callback, $fname ];
2518 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2519 $this->mTrxIdleCallbacks
[] = [ $callback, $fname ];
2520 if ( !$this->mTrxLevel
) {
2521 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2525 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2526 if ( $this->mTrxLevel
) {
2527 $this->mTrxPreCommitCallbacks
[] = [ $callback, $fname ];
2529 // If no transaction is active, then make one for this callback
2530 $this->startAtomic( __METHOD__
);
2532 call_user_func( $callback );
2533 $this->endAtomic( __METHOD__
);
2534 } catch ( Exception
$e ) {
2535 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2541 final public function setTransactionListener( $name, callable
$callback = null ) {
2543 $this->mTrxRecurringCallbacks
[$name] = $callback;
2545 unset( $this->mTrxRecurringCallbacks
[$name] );
2550 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2552 * This method should not be used outside of Database/LoadBalancer
2554 * @param bool $suppress
2557 final public function setTrxEndCallbackSuppression( $suppress ) {
2558 $this->mTrxEndCallbacksSuppressed
= $suppress;
2562 * Actually run and consume any "on transaction idle/resolution" callbacks.
2564 * This method should not be used outside of Database/LoadBalancer
2566 * @param integer $trigger IDatabase::TRIGGER_* constant
2570 public function runOnTransactionIdleCallbacks( $trigger ) {
2571 if ( $this->mTrxEndCallbacksSuppressed
) {
2575 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2576 /** @var Exception $e */
2577 $e = null; // first exception
2578 do { // callbacks may add callbacks :)
2579 $callbacks = array_merge(
2580 $this->mTrxIdleCallbacks
,
2581 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2583 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2584 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2585 foreach ( $callbacks as $callback ) {
2587 list( $phpCallback ) = $callback;
2588 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2589 call_user_func_array( $phpCallback, [ $trigger ] );
2591 $this->setFlag( DBO_TRX
); // restore automatic begin()
2593 $this->clearFlag( DBO_TRX
); // restore auto-commit
2595 } catch ( Exception
$ex ) {
2596 call_user_func( $this->errorLogger
, $ex );
2598 // Some callbacks may use startAtomic/endAtomic, so make sure
2599 // their transactions are ended so other callbacks don't fail
2600 if ( $this->trxLevel() ) {
2601 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2605 } while ( count( $this->mTrxIdleCallbacks
) );
2607 if ( $e instanceof Exception
) {
2608 throw $e; // re-throw any first exception
2613 * Actually run and consume any "on transaction pre-commit" callbacks.
2615 * This method should not be used outside of Database/LoadBalancer
2620 public function runOnTransactionPreCommitCallbacks() {
2621 $e = null; // first exception
2622 do { // callbacks may add callbacks :)
2623 $callbacks = $this->mTrxPreCommitCallbacks
;
2624 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2625 foreach ( $callbacks as $callback ) {
2627 list( $phpCallback ) = $callback;
2628 call_user_func( $phpCallback );
2629 } catch ( Exception
$ex ) {
2630 call_user_func( $this->errorLogger
, $ex );
2634 } while ( count( $this->mTrxPreCommitCallbacks
) );
2636 if ( $e instanceof Exception
) {
2637 throw $e; // re-throw any first exception
2642 * Actually run any "transaction listener" callbacks.
2644 * This method should not be used outside of Database/LoadBalancer
2646 * @param integer $trigger IDatabase::TRIGGER_* constant
2650 public function runTransactionListenerCallbacks( $trigger ) {
2651 if ( $this->mTrxEndCallbacksSuppressed
) {
2655 /** @var Exception $e */
2656 $e = null; // first exception
2658 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2660 $phpCallback( $trigger, $this );
2661 } catch ( Exception
$ex ) {
2662 call_user_func( $this->errorLogger
, $ex );
2667 if ( $e instanceof Exception
) {
2668 throw $e; // re-throw any first exception
2672 final public function startAtomic( $fname = __METHOD__
) {
2673 if ( !$this->mTrxLevel
) {
2674 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2675 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2676 // in all changes being in one transaction to keep requests transactional.
2677 if ( !$this->getFlag( DBO_TRX
) ) {
2678 $this->mTrxAutomaticAtomic
= true;
2682 $this->mTrxAtomicLevels
[] = $fname;
2685 final public function endAtomic( $fname = __METHOD__
) {
2686 if ( !$this->mTrxLevel
) {
2687 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2689 if ( !$this->mTrxAtomicLevels ||
2690 array_pop( $this->mTrxAtomicLevels
) !== $fname
2692 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2695 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2696 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2700 final public function doAtomicSection( $fname, callable
$callback ) {
2701 $this->startAtomic( $fname );
2703 $res = call_user_func_array( $callback, [ $this, $fname ] );
2704 } catch ( Exception
$e ) {
2705 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2708 $this->endAtomic( $fname );
2713 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2714 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2715 if ( $this->mTrxLevel
) {
2716 if ( $this->mTrxAtomicLevels
) {
2717 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2718 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2719 throw new DBUnexpectedError( $this, $msg );
2720 } elseif ( !$this->mTrxAutomatic
) {
2721 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2722 throw new DBUnexpectedError( $this, $msg );
2724 // @TODO: make this an exception at some point
2725 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2726 $this->queryLogger
->error( $msg );
2727 return; // join the main transaction set
2729 } elseif ( $this->getFlag( DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2730 // @TODO: make this an exception at some point
2731 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2732 $this->queryLogger
->error( $msg );
2733 return; // let any writes be in the main transaction
2736 // Avoid fatals if close() was called
2737 $this->assertOpen();
2739 $this->doBegin( $fname );
2740 $this->mTrxTimestamp
= microtime( true );
2741 $this->mTrxFname
= $fname;
2742 $this->mTrxDoneWrites
= false;
2743 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2744 $this->mTrxAutomaticAtomic
= false;
2745 $this->mTrxAtomicLevels
= [];
2746 $this->mTrxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2747 $this->mTrxWriteDuration
= 0.0;
2748 $this->mTrxWriteQueryCount
= 0;
2749 $this->mTrxWriteAdjDuration
= 0.0;
2750 $this->mTrxWriteAdjQueryCount
= 0;
2751 $this->mTrxWriteCallers
= [];
2752 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2753 // Get an estimate of the replica DB lag before then, treating estimate staleness
2754 // as lag itself just to be safe
2755 $status = $this->getApproximateLagStatus();
2756 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2760 * Issues the BEGIN command to the database server.
2762 * @see DatabaseBase::begin()
2763 * @param string $fname
2765 protected function doBegin( $fname ) {
2766 $this->query( 'BEGIN', $fname );
2767 $this->mTrxLevel
= 1;
2770 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2771 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2772 // There are still atomic sections open. This cannot be ignored
2773 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2774 throw new DBUnexpectedError(
2776 "$fname: Got COMMIT while atomic sections $levels are still open."
2780 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2781 if ( !$this->mTrxLevel
) {
2782 return; // nothing to do
2783 } elseif ( !$this->mTrxAutomatic
) {
2784 throw new DBUnexpectedError(
2786 "$fname: Flushing an explicit transaction, getting out of sync."
2790 if ( !$this->mTrxLevel
) {
2791 $this->queryLogger
->error( "$fname: No transaction to commit, something got out of sync." );
2792 return; // nothing to do
2793 } elseif ( $this->mTrxAutomatic
) {
2794 // @TODO: make this an exception at some point
2795 $msg = "$fname: Explicit commit of implicit transaction.";
2796 $this->queryLogger
->error( $msg );
2797 return; // wait for the main transaction set commit round
2801 // Avoid fatals if close() was called
2802 $this->assertOpen();
2804 $this->runOnTransactionPreCommitCallbacks();
2805 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2806 $this->doCommit( $fname );
2807 if ( $this->mTrxDoneWrites
) {
2808 $this->mDoneWrites
= microtime( true );
2809 $this->trxProfiler
->transactionWritingOut(
2810 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2813 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2814 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
2818 * Issues the COMMIT command to the database server.
2820 * @see DatabaseBase::commit()
2821 * @param string $fname
2823 protected function doCommit( $fname ) {
2824 if ( $this->mTrxLevel
) {
2825 $this->query( 'COMMIT', $fname );
2826 $this->mTrxLevel
= 0;
2830 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2831 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2832 if ( !$this->mTrxLevel
) {
2833 return; // nothing to do
2836 if ( !$this->mTrxLevel
) {
2837 $this->queryLogger
->error(
2838 "$fname: No transaction to rollback, something got out of sync." );
2839 return; // nothing to do
2840 } elseif ( $this->getFlag( DBO_TRX
) ) {
2841 throw new DBUnexpectedError(
2843 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2848 // Avoid fatals if close() was called
2849 $this->assertOpen();
2851 $this->doRollback( $fname );
2852 $this->mTrxAtomicLevels
= [];
2853 if ( $this->mTrxDoneWrites
) {
2854 $this->trxProfiler
->transactionWritingOut(
2855 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
2858 $this->mTrxIdleCallbacks
= []; // clear
2859 $this->mTrxPreCommitCallbacks
= []; // clear
2860 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
2861 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
2865 * Issues the ROLLBACK command to the database server.
2867 * @see DatabaseBase::rollback()
2868 * @param string $fname
2870 protected function doRollback( $fname ) {
2871 if ( $this->mTrxLevel
) {
2872 # Disconnects cause rollback anyway, so ignore those errors
2873 $ignoreErrors = true;
2874 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
2875 $this->mTrxLevel
= 0;
2879 public function flushSnapshot( $fname = __METHOD__
) {
2880 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
2881 // This only flushes transactions to clear snapshots, not to write data
2882 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
2883 throw new DBUnexpectedError(
2885 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
2889 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2892 public function explicitTrxActive() {
2893 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
2897 * Creates a new table with structure copied from existing table
2898 * Note that unlike most database abstraction functions, this function does not
2899 * automatically append database prefix, because it works at a lower
2900 * abstraction level.
2901 * The table names passed to this function shall not be quoted (this
2902 * function calls addIdentifierQuotes when needed).
2904 * @param string $oldName Name of table whose structure should be copied
2905 * @param string $newName Name of table to be created
2906 * @param bool $temporary Whether the new table should be temporary
2907 * @param string $fname Calling function name
2908 * @throws RuntimeException
2909 * @return bool True if operation was successful
2911 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
2914 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2917 function listTables( $prefix = null, $fname = __METHOD__
) {
2918 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2922 * Reset the views process cache set by listViews()
2925 final public function clearViewsCache() {
2926 $this->allViews
= null;
2930 * Lists all the VIEWs in the database
2932 * For caching purposes the list of all views should be stored in
2933 * $this->allViews. The process cache can be cleared with clearViewsCache()
2935 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
2936 * @param string $fname Name of calling function
2937 * @throws RuntimeException
2941 public function listViews( $prefix = null, $fname = __METHOD__
) {
2942 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2946 * Differentiates between a TABLE and a VIEW
2948 * @param string $name Name of the database-structure to test.
2949 * @throws RuntimeException
2953 public function isView( $name ) {
2954 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2957 public function timestamp( $ts = 0 ) {
2958 $t = new ConvertableTimestamp( $ts );
2959 // Let errors bubble up to avoid putting garbage in the DB
2960 return $t->getTimestamp( TS_MW
);
2963 public function timestampOrNull( $ts = null ) {
2964 if ( is_null( $ts ) ) {
2967 return $this->timestamp( $ts );
2972 * Take the result from a query, and wrap it in a ResultWrapper if
2973 * necessary. Boolean values are passed through as is, to indicate success
2974 * of write queries or failure.
2976 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2977 * resource, and it was necessary to call this function to convert it to
2978 * a wrapper. Nowadays, raw database objects are never exposed to external
2979 * callers, so this is unnecessary in external code.
2981 * @param bool|ResultWrapper|resource|object $result
2982 * @return bool|ResultWrapper
2984 protected function resultObject( $result ) {
2987 } elseif ( $result instanceof ResultWrapper
) {
2989 } elseif ( $result === true ) {
2990 // Successful write query
2993 return new ResultWrapper( $this, $result );
2997 public function ping( &$rtt = null ) {
2998 // Avoid hitting the server if it was hit recently
2999 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3000 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
3001 $rtt = $this->mRTTEstimate
;
3002 return true; // don't care about $rtt
3006 // This will reconnect if possible or return false if not
3007 $this->clearFlag( DBO_TRX
, self
::REMEMBER_PRIOR
);
3008 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3009 $this->restoreFlags( self
::RESTORE_PRIOR
);
3012 $rtt = $this->mRTTEstimate
;
3021 protected function reconnect() {
3022 $this->closeConnection();
3023 $this->mOpened
= false;
3024 $this->mConn
= false;
3026 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3027 $this->lastPing
= microtime( true );
3029 } catch ( DBConnectionError
$e ) {
3036 public function getSessionLagStatus() {
3037 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3041 * Get the replica DB lag when the current transaction started
3043 * This is useful when transactions might use snapshot isolation
3044 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3045 * is this lag plus transaction duration. If they don't, it is still
3046 * safe to be pessimistic. This returns null if there is no transaction.
3048 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3051 public function getTransactionLagStatus() {
3052 return $this->mTrxLevel
3053 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3058 * Get a replica DB lag estimate for this server
3060 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3063 public function getApproximateLagStatus() {
3065 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3066 'since' => microtime( true )
3071 * Merge the result of getSessionLagStatus() for several DBs
3072 * using the most pessimistic values to estimate the lag of
3073 * any data derived from them in combination
3075 * This is information is useful for caching modules
3077 * @see WANObjectCache::set()
3078 * @see WANObjectCache::getWithSetCallback()
3080 * @param IDatabase $db1
3081 * @param IDatabase ...
3082 * @return array Map of values:
3083 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3084 * - since: oldest UNIX timestamp of any of the DB lag estimates
3085 * - pending: whether any of the DBs have uncommitted changes
3088 public static function getCacheSetOptions( IDatabase
$db1 ) {
3089 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3090 foreach ( func_get_args() as $db ) {
3091 /** @var IDatabase $db */
3092 $status = $db->getSessionLagStatus();
3093 if ( $status['lag'] === false ) {
3094 $res['lag'] = false;
3095 } elseif ( $res['lag'] !== false ) {
3096 $res['lag'] = max( $res['lag'], $status['lag'] );
3098 $res['since'] = min( $res['since'], $status['since'] );
3099 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3105 public function getLag() {
3109 function maxListLen() {
3113 public function encodeBlob( $b ) {
3117 public function decodeBlob( $b ) {
3118 if ( $b instanceof Blob
) {
3124 public function setSessionOptions( array $options ) {
3128 * Read and execute SQL commands from a file.
3130 * Returns true on success, error string or exception on failure (depending
3131 * on object's error ignore settings).
3133 * @param string $filename File name to open
3134 * @param bool|callable $lineCallback Optional function called before reading each line
3135 * @param bool|callable $resultCallback Optional function called for each MySQL result
3136 * @param bool|string $fname Calling function name or false if name should be
3137 * generated dynamically using $filename
3138 * @param bool|callable $inputCallback Optional function called for each
3139 * complete line sent
3140 * @return bool|string
3143 public function sourceFile(
3144 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3146 MediaWiki\
suppressWarnings();
3147 $fp = fopen( $filename, 'r' );
3148 MediaWiki\restoreWarnings
();
3150 if ( false === $fp ) {
3151 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3155 $fname = __METHOD__
. "( $filename )";
3159 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3160 } catch ( Exception
$e ) {
3170 public function setSchemaVars( $vars ) {
3171 $this->mSchemaVars
= $vars;
3175 * Read and execute commands from an open file handle.
3177 * Returns true on success, error string or exception on failure (depending
3178 * on object's error ignore settings).
3180 * @param resource $fp File handle
3181 * @param bool|callable $lineCallback Optional function called before reading each query
3182 * @param bool|callable $resultCallback Optional function called for each MySQL result
3183 * @param string $fname Calling function name
3184 * @param bool|callable $inputCallback Optional function called for each complete query sent
3185 * @return bool|string
3187 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3188 $fname = __METHOD__
, $inputCallback = false
3192 while ( !feof( $fp ) ) {
3193 if ( $lineCallback ) {
3194 call_user_func( $lineCallback );
3197 $line = trim( fgets( $fp ) );
3199 if ( $line == '' ) {
3203 if ( '-' == $line[0] && '-' == $line[1] ) {
3211 $done = $this->streamStatementEnd( $cmd, $line );
3215 if ( $done ||
feof( $fp ) ) {
3216 $cmd = $this->replaceVars( $cmd );
3218 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3219 $res = $this->query( $cmd, $fname );
3221 if ( $resultCallback ) {
3222 call_user_func( $resultCallback, $res, $this );
3225 if ( false === $res ) {
3226 $err = $this->lastError();
3228 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3239 * Called by sourceStream() to check if we've reached a statement end
3241 * @param string $sql SQL assembled so far
3242 * @param string $newLine New line about to be added to $sql
3243 * @return bool Whether $newLine contains end of the statement
3245 public function streamStatementEnd( &$sql, &$newLine ) {
3246 if ( $this->delimiter
) {
3248 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3249 if ( $newLine != $prev ) {
3258 * Database independent variable replacement. Replaces a set of variables
3259 * in an SQL statement with their contents as given by $this->getSchemaVars().
3261 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3263 * - '{$var}' should be used for text and is passed through the database's
3265 * - `{$var}` should be used for identifiers (e.g. table and database names).
3266 * It is passed through the database's addIdentifierQuotes method which
3267 * can be overridden if the database uses something other than backticks.
3268 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3269 * database's tableName method.
3270 * - / *i* / passes the name that follows through the database's indexName method.
3271 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3272 * its use should be avoided. In 1.24 and older, string encoding was applied.
3274 * @param string $ins SQL statement to replace variables in
3275 * @return string The new SQL statement with variables replaced
3277 protected function replaceVars( $ins ) {
3278 $vars = $this->getSchemaVars();
3279 return preg_replace_callback(
3281 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3282 \'\{\$ (\w+) }\' | # 3. addQuotes
3283 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3284 /\*\$ (\w+) \*/ # 5. leave unencoded
3286 function ( $m ) use ( $vars ) {
3287 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3288 // check for both nonexistent keys *and* the empty string.
3289 if ( isset( $m[1] ) && $m[1] !== '' ) {
3290 if ( $m[1] === 'i' ) {
3291 return $this->indexName( $m[2] );
3293 return $this->tableName( $m[2] );
3295 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3296 return $this->addQuotes( $vars[$m[3]] );
3297 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3298 return $this->addIdentifierQuotes( $vars[$m[4]] );
3299 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3300 return $vars[$m[5]];
3310 * Get schema variables. If none have been set via setSchemaVars(), then
3311 * use some defaults from the current object.
3315 protected function getSchemaVars() {
3316 if ( $this->mSchemaVars
) {
3317 return $this->mSchemaVars
;
3319 return $this->getDefaultSchemaVars();
3324 * Get schema variables to use if none have been set via setSchemaVars().
3326 * Override this in derived classes to provide variables for tables.sql
3327 * and SQL patch files.
3331 protected function getDefaultSchemaVars() {
3335 public function lockIsFree( $lockName, $method ) {
3339 public function lock( $lockName, $method, $timeout = 5 ) {
3340 $this->mNamedLocksHeld
[$lockName] = 1;
3345 public function unlock( $lockName, $method ) {
3346 unset( $this->mNamedLocksHeld
[$lockName] );
3351 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3352 if ( $this->writesOrCallbacksPending() ) {
3353 // This only flushes transactions to clear snapshots, not to write data
3354 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3355 throw new DBUnexpectedError(
3357 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
3361 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3365 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3366 if ( $this->trxLevel() ) {
3367 // There is a good chance an exception was thrown, causing any early return
3368 // from the caller. Let any error handler get a chance to issue rollback().
3369 // If there isn't one, let the error bubble up and trigger server-side rollback.
3370 $this->onTransactionResolution(
3371 function () use ( $lockKey, $fname ) {
3372 $this->unlock( $lockKey, $fname );
3377 $this->unlock( $lockKey, $fname );
3381 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3386 public function namedLocksEnqueue() {
3391 * Lock specific tables
3393 * @param array $read Array of tables to lock for read access
3394 * @param array $write Array of tables to lock for write access
3395 * @param string $method Name of caller
3396 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3399 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3404 * Unlock specific tables
3406 * @param string $method The caller
3409 public function unlockTables( $method ) {
3415 * @param string $tableName
3416 * @param string $fName
3417 * @return bool|ResultWrapper
3420 public function dropTable( $tableName, $fName = __METHOD__
) {
3421 if ( !$this->tableExists( $tableName, $fName ) ) {
3424 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3426 return $this->query( $sql, $fName );
3429 public function getInfinity() {
3433 public function encodeExpiry( $expiry ) {
3434 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3435 ?
$this->getInfinity()
3436 : $this->timestamp( $expiry );
3439 public function decodeExpiry( $expiry, $format = TS_MW
) {
3440 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3445 $t = new ConvertableTimestamp( $expiry );
3447 return $t->getTimestamp( $format );
3448 } catch ( TimestampException
$e ) {
3453 public function setBigSelects( $value = true ) {
3457 public function isReadOnly() {
3458 return ( $this->getReadOnlyReason() !== false );
3462 * @return string|bool Reason this DB is read-only or false if it is not
3464 protected function getReadOnlyReason() {
3465 $reason = $this->getLBInfo( 'readOnlyReason' );
3467 return is_string( $reason ) ?
$reason : false;
3470 public function setTableAliases( array $aliases ) {
3471 $this->tableAliases
= $aliases;
3475 * @return bool Whether a DB user is required to access the DB
3478 protected function requiresDatabaseUser() {
3486 public function __toString() {
3487 return (string)$this->mConn
;
3491 * Called by serialize. Throw an exception when DB connection is serialized.
3492 * This causes problems on some database engines because the connection is
3493 * not restored on unserialize.
3495 public function __sleep() {
3496 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3497 'the connection is not restored on wakeup.' );
3501 * Run a few simple sanity checks
3503 public function __destruct() {
3504 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3505 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3508 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3509 if ( $danglingWriters ) {
3510 $fnames = implode( ', ', $danglingWriters );
3511 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );