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 = [];
206 /** @var array Map of (table name => 1) for TEMPORARY tables */
207 protected $mSessionTempTables = [];
209 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
210 private $lazyMasterHandle;
214 * @var string[] Process cache of VIEWs names in the database
216 protected $allViews = null;
218 /** @var float UNIX timestamp */
219 protected $lastPing = 0.0;
221 /** @var int[] Prior mFlags values */
222 private $priorFlags = [];
224 /** @var object|string Class name or object With profileIn/profileOut methods */
226 /** @var TransactionProfiler */
227 protected $trxProfiler;
230 * Constructor and database handle and attempt to connect to the DB server
232 * IDatabase classes should not be constructed directly in external
233 * code. Database::factory() should be used instead.
235 * @param array $params Parameters passed from Database::factory()
237 function __construct( array $params ) {
238 $server = $params['host'];
239 $user = $params['user'];
240 $password = $params['password'];
241 $dbName = $params['dbname'];
243 $this->mSchema
= $params['schema'];
244 $this->mTablePrefix
= $params['tablePrefix'];
246 $this->cliMode
= $params['cliMode'];
247 // Agent name is added to SQL queries in a comment, so make sure it can't break out
248 $this->agent
= str_replace( '/', '-', $params['agent'] );
250 $this->mFlags
= $params['flags'];
251 if ( $this->mFlags
& self
::DBO_DEFAULT
) {
252 if ( $this->cliMode
) {
253 $this->mFlags
&= ~self
::DBO_TRX
;
255 $this->mFlags |
= self
::DBO_TRX
;
259 $this->mSessionVars
= $params['variables'];
261 $this->srvCache
= isset( $params['srvCache'] )
262 ?
$params['srvCache']
263 : new HashBagOStuff();
265 $this->profiler
= $params['profiler'];
266 $this->trxProfiler
= $params['trxProfiler'];
267 $this->connLogger
= $params['connLogger'];
268 $this->queryLogger
= $params['queryLogger'];
269 $this->errorLogger
= $params['errorLogger'];
271 // Set initial dummy domain until open() sets the final DB/prefix
272 $this->currentDomain
= DatabaseDomain
::newUnspecified();
275 $this->open( $server, $user, $password, $dbName );
276 } elseif ( $this->requiresDatabaseUser() ) {
277 throw new InvalidArgumentException( "No database user provided." );
280 // Set the domain object after open() sets the relevant fields
281 if ( $this->mDBname
!= '' ) {
282 // Domains with server scope but a table prefix are not used by IDatabase classes
283 $this->currentDomain
= new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
);
288 * Construct a Database subclass instance given a database type and parameters
290 * This also connects to the database immediately upon object construction
292 * @param string $dbType A possible DB type (sqlite, mysql, postgres)
293 * @param array $p Parameter map with keys:
294 * - host : The hostname of the DB server
295 * - user : The name of the database user the client operates under
296 * - password : The password for the database user
297 * - dbname : The name of the database to use where queries do not specify one.
298 * The database must exist or an error might be thrown. Setting this to the empty string
299 * will avoid any such errors and make the handle have no implicit database scope. This is
300 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
301 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
302 * in which user names and such are defined, e.g. users are database-specific in Postgres.
303 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
304 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
305 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
306 * recognized in queries. This can be used in place of schemas for handle site farms.
307 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
308 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
309 * flag in place UNLESS this this database simply acts as a key/value store.
310 * - driver: Optional name of a specific DB client driver. For MySQL, there is the old
311 * 'mysql' driver and the newer 'mysqli' driver.
312 * - variables: Optional map of session variables to set after connecting. This can be
313 * used to adjust lock timeouts or encoding modes and the like.
314 * - connLogger: Optional PSR-3 logger interface instance.
315 * - queryLogger: Optional PSR-3 logger interface instance.
316 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
317 * These will be called in query(), using a simplified version of the SQL that also
318 * includes the agent as a SQL comment.
319 * - trxProfiler: Optional TransactionProfiler instance.
320 * - errorLogger: Optional callback that takes an Exception and logs it.
321 * - cliMode: Whether to consider the execution context that of a CLI script.
322 * - agent: Optional name used to identify the end-user in query profiling/logging.
323 * - srvCache: Optional BagOStuff instance to an APC-style cache.
324 * @return Database|null If the database driver or extension cannot be found
325 * @throws InvalidArgumentException If the database driver or extension cannot be found
328 final public static function factory( $dbType, $p = [] ) {
329 static $canonicalDBTypes = [
330 'mysql' => [ 'mysqli', 'mysql' ],
338 $dbType = strtolower( $dbType );
339 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
340 $possibleDrivers = $canonicalDBTypes[$dbType];
341 if ( !empty( $p['driver'] ) ) {
342 if ( in_array( $p['driver'], $possibleDrivers ) ) {
343 $driver = $p['driver'];
345 throw new InvalidArgumentException( __METHOD__
.
346 " type '$dbType' does not support driver '{$p['driver']}'" );
349 foreach ( $possibleDrivers as $posDriver ) {
350 if ( extension_loaded( $posDriver ) ) {
351 $driver = $posDriver;
359 if ( $driver === false ) {
360 throw new InvalidArgumentException( __METHOD__
.
361 " no viable database extension found for type '$dbType'" );
364 $class = 'Database' . ucfirst( $driver );
365 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
366 // Resolve some defaults for b/c
367 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
368 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
369 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
370 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
371 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
372 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
373 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
374 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
375 $p['cliMode'] = isset( $p['cliMode'] ) ?
$p['cliMode'] : ( PHP_SAPI
=== 'cli' );
376 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
377 if ( !isset( $p['connLogger'] ) ) {
378 $p['connLogger'] = new \Psr\Log\
NullLogger();
380 if ( !isset( $p['queryLogger'] ) ) {
381 $p['queryLogger'] = new \Psr\Log\
NullLogger();
383 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
384 if ( !isset( $p['trxProfiler'] ) ) {
385 $p['trxProfiler'] = new TransactionProfiler();
387 if ( !isset( $p['errorLogger'] ) ) {
388 $p['errorLogger'] = function ( Exception
$e ) {
389 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_WARNING
);
393 $conn = new $class( $p );
401 public function setLogger( LoggerInterface
$logger ) {
402 $this->queryLogger
= $logger;
405 public function getServerInfo() {
406 return $this->getServerVersion();
409 public function bufferResults( $buffer = null ) {
410 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
411 if ( $buffer !== null ) {
413 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
414 : $this->setFlag( self
::DBO_NOBUFFER
);
421 * Turns on (false) or off (true) the automatic generation and sending
422 * of a "we're sorry, but there has been a database error" page on
423 * database errors. Default is on (false). When turned off, the
424 * code should use lastErrno() and lastError() to handle the
425 * situation as appropriate.
427 * Do not use this function outside of the Database classes.
429 * @param null|bool $ignoreErrors
430 * @return bool The previous value of the flag.
432 protected function ignoreErrors( $ignoreErrors = null ) {
433 $res = $this->getFlag( self
::DBO_IGNORE
);
434 if ( $ignoreErrors !== null ) {
436 ?
$this->setFlag( self
::DBO_IGNORE
)
437 : $this->clearFlag( self
::DBO_IGNORE
);
443 public function trxLevel() {
444 return $this->mTrxLevel
;
447 public function trxTimestamp() {
448 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
451 public function tablePrefix( $prefix = null ) {
452 $old = $this->mTablePrefix
;
453 if ( $prefix !== null ) {
454 $this->mTablePrefix
= $prefix;
455 $this->currentDomain
= ( $this->mDBname
!= '' )
456 ?
new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
)
457 : DatabaseDomain
::newUnspecified();
463 public function dbSchema( $schema = null ) {
464 $old = $this->mSchema
;
465 if ( $schema !== null ) {
466 $this->mSchema
= $schema;
472 public function getLBInfo( $name = null ) {
473 if ( is_null( $name ) ) {
474 return $this->mLBInfo
;
476 if ( array_key_exists( $name, $this->mLBInfo
) ) {
477 return $this->mLBInfo
[$name];
484 public function setLBInfo( $name, $value = null ) {
485 if ( is_null( $value ) ) {
486 $this->mLBInfo
= $name;
488 $this->mLBInfo
[$name] = $value;
492 public function setLazyMasterHandle( IDatabase
$conn ) {
493 $this->lazyMasterHandle
= $conn;
497 * @return IDatabase|null
498 * @see setLazyMasterHandle()
501 public function getLazyMasterHandle() {
502 return $this->lazyMasterHandle
;
505 public function implicitGroupby() {
509 public function implicitOrderby() {
513 public function lastQuery() {
514 return $this->mLastQuery
;
517 public function doneWrites() {
518 return (bool)$this->mDoneWrites
;
521 public function lastDoneWrites() {
522 return $this->mDoneWrites ?
: false;
525 public function writesPending() {
526 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
529 public function writesOrCallbacksPending() {
530 return $this->mTrxLevel
&& (
531 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
535 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
536 if ( !$this->mTrxLevel
) {
538 } elseif ( !$this->mTrxDoneWrites
) {
543 case self
::ESTIMATE_DB_APPLY
:
545 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
546 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
547 // For omitted queries, make them count as something at least
548 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
549 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
552 default: // everything
553 return $this->mTrxWriteDuration
;
557 public function pendingWriteCallers() {
558 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
561 protected function pendingWriteAndCallbackCallers() {
562 if ( !$this->mTrxLevel
) {
566 $fnames = $this->mTrxWriteCallers
;
568 $this->mTrxIdleCallbacks
,
569 $this->mTrxPreCommitCallbacks
,
570 $this->mTrxEndCallbacks
572 foreach ( $callbacks as $callback ) {
573 $fnames[] = $callback[1];
580 public function isOpen() {
581 return $this->mOpened
;
584 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
585 if ( $remember === self
::REMEMBER_PRIOR
) {
586 array_push( $this->priorFlags
, $this->mFlags
);
588 $this->mFlags |
= $flag;
591 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
592 if ( $remember === self
::REMEMBER_PRIOR
) {
593 array_push( $this->priorFlags
, $this->mFlags
);
595 $this->mFlags
&= ~
$flag;
598 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
599 if ( !$this->priorFlags
) {
603 if ( $state === self
::RESTORE_INITIAL
) {
604 $this->mFlags
= reset( $this->priorFlags
);
605 $this->priorFlags
= [];
607 $this->mFlags
= array_pop( $this->priorFlags
);
611 public function getFlag( $flag ) {
612 return !!( $this->mFlags
& $flag );
615 public function getProperty( $name ) {
619 public function getDomainID() {
620 return $this->currentDomain
->getId();
623 final public function getWikiID() {
624 return $this->getDomainID();
628 * Get information about an index into an object
629 * @param string $table Table name
630 * @param string $index Index name
631 * @param string $fname Calling function name
632 * @return mixed Database-specific index description class or false if the index does not exist
634 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
637 * Wrapper for addslashes()
639 * @param string $s String to be slashed.
640 * @return string Slashed string.
642 abstract function strencode( $s );
644 protected function installErrorHandler() {
645 $this->mPHPError
= false;
646 $this->htmlErrors
= ini_set( 'html_errors', '0' );
647 set_error_handler( [ $this, 'connectionErrorLogger' ] );
651 * @return bool|string
653 protected function restoreErrorHandler() {
654 restore_error_handler();
655 if ( $this->htmlErrors
!== false ) {
656 ini_set( 'html_errors', $this->htmlErrors
);
658 if ( $this->mPHPError
) {
659 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
660 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
669 * This method should not be used outside of Database classes
672 * @param string $errstr
674 public function connectionErrorLogger( $errno, $errstr ) {
675 $this->mPHPError
= $errstr;
679 * Create a log context to pass to PSR-3 logger functions.
681 * @param array $extras Additional data to add to context
684 protected function getLogContext( array $extras = [] ) {
687 'db_server' => $this->mServer
,
688 'db_name' => $this->mDBname
,
689 'db_user' => $this->mUser
,
695 public function close() {
696 if ( $this->mConn
) {
697 if ( $this->trxLevel() ) {
698 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
701 $closed = $this->closeConnection();
702 $this->mConn
= false;
703 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
704 throw new RuntimeException( "Transaction callbacks still pending." );
708 $this->mOpened
= false;
714 * Make sure isOpen() returns true as a sanity check
716 * @throws DBUnexpectedError
718 protected function assertOpen() {
719 if ( !$this->isOpen() ) {
720 throw new DBUnexpectedError( $this, "DB connection was already closed." );
725 * Closes underlying database connection
727 * @return bool Whether connection was closed successfully
729 abstract protected function closeConnection();
731 public function reportConnectionError( $error = 'Unknown error' ) {
732 $myError = $this->lastError();
738 throw new DBConnectionError( $this, $error );
742 * The DBMS-dependent part of query()
744 * @param string $sql SQL query.
745 * @return ResultWrapper|bool Result object to feed to fetchObject,
746 * fetchRow, ...; or false on failure
748 abstract protected function doQuery( $sql );
751 * Determine whether a query writes to the DB.
752 * Should return true if unsure.
757 protected function isWriteQuery( $sql ) {
759 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
764 * @return string|null
766 protected function getQueryVerb( $sql ) {
767 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
771 * Determine whether a SQL statement is sensitive to isolation level.
772 * A SQL statement is considered transactable if its result could vary
773 * depending on the transaction isolation level. Operational commands
774 * such as 'SET' and 'SHOW' are not considered to be transactable.
779 protected function isTransactableQuery( $sql ) {
780 $verb = $this->getQueryVerb( $sql );
781 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
785 * @param string $sql A SQL query
786 * @return bool Whether $sql is SQL for creating/dropping a new TEMPORARY table
788 protected function registerTempTableOperation( $sql ) {
790 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
794 $this->mSessionTempTables
[$matches[1]] = 1;
797 } elseif ( preg_match(
798 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
802 unset( $this->mSessionTempTables
[$matches[1]] );
805 } elseif ( preg_match(
806 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
810 return isset( $this->mSessionTempTables
[$matches[1]] );
816 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
817 $priorWritesPending = $this->writesOrCallbacksPending();
818 $this->mLastQuery
= $sql;
820 $isWrite = $this->isWriteQuery( $sql ) && !$this->registerTempTableOperation( $sql );
822 $reason = $this->getReadOnlyReason();
823 if ( $reason !== false ) {
824 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
826 # Set a flag indicating that writes have been done
827 $this->mDoneWrites
= microtime( true );
830 // Add trace comment to the begin of the sql string, right after the operator.
831 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
832 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
834 # Start implicit transactions that wrap the request if DBO_TRX is enabled
835 if ( !$this->mTrxLevel
&& $this->getFlag( self
::DBO_TRX
)
836 && $this->isTransactableQuery( $sql )
838 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
839 $this->mTrxAutomatic
= true;
842 # Keep track of whether the transaction has write queries pending
843 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
844 $this->mTrxDoneWrites
= true;
845 $this->trxProfiler
->transactionWritingIn(
846 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
849 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
850 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
853 # Avoid fatals if close() was called
856 # Send the query to the server
857 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
859 # Try reconnecting if the connection was lost
860 if ( false === $ret && $this->wasErrorReissuable() ) {
861 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
862 # Stash the last error values before anything might clear them
863 $lastError = $this->lastError();
864 $lastErrno = $this->lastErrno();
865 # Update state tracking to reflect transaction loss due to disconnection
866 $this->handleSessionLoss();
867 if ( $this->reconnect() ) {
868 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
869 $this->connLogger
->warning( $msg );
870 $this->queryLogger
->warning(
871 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
873 if ( !$recoverable ) {
874 # Callers may catch the exception and continue to use the DB
875 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
877 # Should be safe to silently retry the query
878 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
881 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
882 $this->connLogger
->error( $msg );
886 if ( false === $ret ) {
887 # Deadlocks cause the entire transaction to abort, not just the statement.
888 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
889 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
890 if ( $this->wasDeadlock() ) {
891 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
892 $tempIgnore = false; // not recoverable
894 # Update state tracking to reflect transaction loss
895 $this->handleSessionLoss();
898 $this->reportQueryError(
899 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
902 $res = $this->resultObject( $ret );
907 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
908 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
909 # generalizeSQL() will probably cut down the query to reasonable
910 # logging size most of the time. The substr is really just a sanity check.
912 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
914 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
917 # Include query transaction state
918 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
920 $startTime = microtime( true );
921 if ( $this->profiler
) {
922 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
924 $ret = $this->doQuery( $commentedSql );
925 if ( $this->profiler
) {
926 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
928 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
930 unset( $queryProfSection ); // profile out (if set)
932 if ( $ret !== false ) {
933 $this->lastPing
= $startTime;
934 if ( $isWrite && $this->mTrxLevel
) {
935 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
936 $this->mTrxWriteCallers
[] = $fname;
940 if ( $sql === self
::PING_QUERY
) {
941 $this->mRTTEstimate
= $queryRuntime;
944 $this->trxProfiler
->recordQueryCompletion(
945 $queryProf, $startTime, $isWrite, $this->affectedRows()
947 $this->queryLogger
->debug( $sql, [
949 'master' => $isMaster,
950 'runtime' => $queryRuntime,
957 * Update the estimated run-time of a query, not counting large row lock times
959 * LoadBalancer can be set to rollback transactions that will create huge replication
960 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
961 * queries, like inserting a row can take a long time due to row locking. This method
962 * uses some simple heuristics to discount those cases.
964 * @param string $sql A SQL write query
965 * @param float $runtime Total runtime, including RTT
967 private function updateTrxWriteQueryTime( $sql, $runtime ) {
968 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
969 $indicativeOfReplicaRuntime = true;
970 if ( $runtime > self
::SLOW_WRITE_SEC
) {
971 $verb = $this->getQueryVerb( $sql );
972 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
973 if ( $verb === 'INSERT' ) {
974 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
975 } elseif ( $verb === 'REPLACE' ) {
976 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
980 $this->mTrxWriteDuration +
= $runtime;
981 $this->mTrxWriteQueryCount +
= 1;
982 if ( $indicativeOfReplicaRuntime ) {
983 $this->mTrxWriteAdjDuration +
= $runtime;
984 $this->mTrxWriteAdjQueryCount +
= 1;
988 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
989 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
990 # Dropped connections also mean that named locks are automatically released.
991 # Only allow error suppression in autocommit mode or when the lost transaction
992 # didn't matter anyway (aside from DBO_TRX snapshot loss).
993 if ( $this->mNamedLocksHeld
) {
994 return false; // possible critical section violation
995 } elseif ( $sql === 'COMMIT' ) {
996 return !$priorWritesPending; // nothing written anyway? (T127428)
997 } elseif ( $sql === 'ROLLBACK' ) {
998 return true; // transaction lost...which is also what was requested :)
999 } elseif ( $this->explicitTrxActive() ) {
1000 return false; // don't drop atomocity
1001 } elseif ( $priorWritesPending ) {
1002 return false; // prior writes lost from implicit transaction
1008 private function handleSessionLoss() {
1009 $this->mTrxLevel
= 0;
1010 $this->mTrxIdleCallbacks
= []; // bug 65263
1011 $this->mTrxPreCommitCallbacks
= []; // bug 65263
1012 $this->mSessionTempTables
= [];
1013 $this->mNamedLocksHeld
= [];
1015 // Handle callbacks in mTrxEndCallbacks
1016 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1017 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1019 } catch ( Exception
$e ) {
1020 // Already logged; move on...
1025 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1026 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1027 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1029 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1030 $this->queryLogger
->error(
1031 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1032 $this->getLogContext( [
1033 'method' => __METHOD__
,
1036 'sql1line' => $sql1line,
1040 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1041 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1045 public function freeResult( $res ) {
1048 public function selectField(
1049 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1051 if ( $var === '*' ) { // sanity
1052 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1055 if ( !is_array( $options ) ) {
1056 $options = [ $options ];
1059 $options['LIMIT'] = 1;
1061 $res = $this->select( $table, $var, $cond, $fname, $options );
1062 if ( $res === false ||
!$this->numRows( $res ) ) {
1066 $row = $this->fetchRow( $res );
1068 if ( $row !== false ) {
1069 return reset( $row );
1075 public function selectFieldValues(
1076 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1078 if ( $var === '*' ) { // sanity
1079 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1080 } elseif ( !is_string( $var ) ) { // sanity
1081 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1084 if ( !is_array( $options ) ) {
1085 $options = [ $options ];
1088 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1089 if ( $res === false ) {
1094 foreach ( $res as $row ) {
1095 $values[] = $row->$var;
1102 * Returns an optional USE INDEX clause to go after the table, and a
1103 * string to go at the end of the query.
1105 * @param array $options Associative array of options to be turned into
1106 * an SQL query, valid keys are listed in the function.
1108 * @see DatabaseBase::select()
1110 protected function makeSelectOptions( $options ) {
1111 $preLimitTail = $postLimitTail = '';
1116 foreach ( $options as $key => $option ) {
1117 if ( is_numeric( $key ) ) {
1118 $noKeyOptions[$option] = true;
1122 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1124 $preLimitTail .= $this->makeOrderBy( $options );
1126 // if (isset($options['LIMIT'])) {
1127 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1128 // isset($options['OFFSET']) ? $options['OFFSET']
1132 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1133 $postLimitTail .= ' FOR UPDATE';
1136 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1137 $postLimitTail .= ' LOCK IN SHARE MODE';
1140 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1141 $startOpts .= 'DISTINCT';
1144 # Various MySQL extensions
1145 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1146 $startOpts .= ' /*! STRAIGHT_JOIN */';
1149 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1150 $startOpts .= ' HIGH_PRIORITY';
1153 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1154 $startOpts .= ' SQL_BIG_RESULT';
1157 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1158 $startOpts .= ' SQL_BUFFER_RESULT';
1161 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1162 $startOpts .= ' SQL_SMALL_RESULT';
1165 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1166 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1169 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1170 $startOpts .= ' SQL_CACHE';
1173 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1174 $startOpts .= ' SQL_NO_CACHE';
1177 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1178 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1182 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1183 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1188 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1192 * Returns an optional GROUP BY with an optional HAVING
1194 * @param array $options Associative array of options
1196 * @see DatabaseBase::select()
1199 protected function makeGroupByWithHaving( $options ) {
1201 if ( isset( $options['GROUP BY'] ) ) {
1202 $gb = is_array( $options['GROUP BY'] )
1203 ?
implode( ',', $options['GROUP BY'] )
1204 : $options['GROUP BY'];
1205 $sql .= ' GROUP BY ' . $gb;
1207 if ( isset( $options['HAVING'] ) ) {
1208 $having = is_array( $options['HAVING'] )
1209 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1210 : $options['HAVING'];
1211 $sql .= ' HAVING ' . $having;
1218 * Returns an optional ORDER BY
1220 * @param array $options Associative array of options
1222 * @see DatabaseBase::select()
1225 protected function makeOrderBy( $options ) {
1226 if ( isset( $options['ORDER BY'] ) ) {
1227 $ob = is_array( $options['ORDER BY'] )
1228 ?
implode( ',', $options['ORDER BY'] )
1229 : $options['ORDER BY'];
1231 return ' ORDER BY ' . $ob;
1237 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1238 $options = [], $join_conds = [] ) {
1239 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1241 return $this->query( $sql, $fname );
1244 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1245 $options = [], $join_conds = []
1247 if ( is_array( $vars ) ) {
1248 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1251 $options = (array)$options;
1252 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1253 ?
$options['USE INDEX']
1256 isset( $options['IGNORE INDEX'] ) &&
1257 is_array( $options['IGNORE INDEX'] )
1259 ?
$options['IGNORE INDEX']
1262 if ( is_array( $table ) ) {
1264 $this->tableNamesWithIndexClauseOrJOIN(
1265 $table, $useIndexes, $ignoreIndexes, $join_conds );
1266 } elseif ( $table != '' ) {
1267 if ( $table[0] == ' ' ) {
1268 $from = ' FROM ' . $table;
1271 $this->tableNamesWithIndexClauseOrJOIN(
1272 [ $table ], $useIndexes, $ignoreIndexes, [] );
1278 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1279 $this->makeSelectOptions( $options );
1281 if ( !empty( $conds ) ) {
1282 if ( is_array( $conds ) ) {
1283 $conds = $this->makeList( $conds, self
::LIST_AND
);
1285 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1286 "WHERE $conds $preLimitTail";
1288 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1291 if ( isset( $options['LIMIT'] ) ) {
1292 $sql = $this->limitResult( $sql, $options['LIMIT'],
1293 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1295 $sql = "$sql $postLimitTail";
1297 if ( isset( $options['EXPLAIN'] ) ) {
1298 $sql = 'EXPLAIN ' . $sql;
1304 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1305 $options = [], $join_conds = []
1307 $options = (array)$options;
1308 $options['LIMIT'] = 1;
1309 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1311 if ( $res === false ) {
1315 if ( !$this->numRows( $res ) ) {
1319 $obj = $this->fetchObject( $res );
1324 public function estimateRowCount(
1325 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1328 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1331 $row = $this->fetchRow( $res );
1332 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1338 public function selectRowCount(
1339 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1342 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1343 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1346 $row = $this->fetchRow( $res );
1347 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1354 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1355 * It's only slightly flawed. Don't use for anything important.
1357 * @param string $sql A SQL Query
1361 protected static function generalizeSQL( $sql ) {
1362 # This does the same as the regexp below would do, but in such a way
1363 # as to avoid crashing php on some large strings.
1364 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1366 $sql = str_replace( "\\\\", '', $sql );
1367 $sql = str_replace( "\\'", '', $sql );
1368 $sql = str_replace( "\\\"", '', $sql );
1369 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1370 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1372 # All newlines, tabs, etc replaced by single space
1373 $sql = preg_replace( '/\s+/', ' ', $sql );
1376 # except the ones surrounded by characters, e.g. l10n
1377 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1378 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1383 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1384 $info = $this->fieldInfo( $table, $field );
1389 public function indexExists( $table, $index, $fname = __METHOD__
) {
1390 if ( !$this->tableExists( $table ) ) {
1394 $info = $this->indexInfo( $table, $index, $fname );
1395 if ( is_null( $info ) ) {
1398 return $info !== false;
1402 public function tableExists( $table, $fname = __METHOD__
) {
1403 $tableRaw = $this->tableName( $table, 'raw' );
1404 if ( isset( $this->mSessionTempTables
[$tableRaw] ) ) {
1405 return true; // already known to exist
1408 $table = $this->tableName( $table );
1409 $old = $this->ignoreErrors( true );
1410 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1411 $this->ignoreErrors( $old );
1416 public function indexUnique( $table, $index ) {
1417 $indexInfo = $this->indexInfo( $table, $index );
1419 if ( !$indexInfo ) {
1423 return !$indexInfo[0]->Non_unique
;
1427 * Helper for DatabaseBase::insert().
1429 * @param array $options
1432 protected function makeInsertOptions( $options ) {
1433 return implode( ' ', $options );
1436 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1437 # No rows to insert, easy just return now
1438 if ( !count( $a ) ) {
1442 $table = $this->tableName( $table );
1444 if ( !is_array( $options ) ) {
1445 $options = [ $options ];
1449 if ( isset( $options['fileHandle'] ) ) {
1450 $fh = $options['fileHandle'];
1452 $options = $this->makeInsertOptions( $options );
1454 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1456 $keys = array_keys( $a[0] );
1459 $keys = array_keys( $a );
1462 $sql = 'INSERT ' . $options .
1463 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1467 foreach ( $a as $row ) {
1473 $sql .= '(' . $this->makeList( $row ) . ')';
1476 $sql .= '(' . $this->makeList( $a ) . ')';
1479 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1481 } elseif ( $fh !== null ) {
1485 return (bool)$this->query( $sql, $fname );
1489 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1491 * @param array $options
1494 protected function makeUpdateOptionsArray( $options ) {
1495 if ( !is_array( $options ) ) {
1496 $options = [ $options ];
1501 if ( in_array( 'IGNORE', $options ) ) {
1509 * Make UPDATE options for the DatabaseBase::update function
1511 * @param array $options The options passed to DatabaseBase::update
1514 protected function makeUpdateOptions( $options ) {
1515 $opts = $this->makeUpdateOptionsArray( $options );
1517 return implode( ' ', $opts );
1520 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1521 $table = $this->tableName( $table );
1522 $opts = $this->makeUpdateOptions( $options );
1523 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1525 if ( $conds !== [] && $conds !== '*' ) {
1526 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1529 return $this->query( $sql, $fname );
1532 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1533 if ( !is_array( $a ) ) {
1534 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1540 foreach ( $a as $field => $value ) {
1542 if ( $mode == self
::LIST_AND
) {
1544 } elseif ( $mode == self
::LIST_OR
) {
1553 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1554 $list .= "($value)";
1555 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1558 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1560 // Remove null from array to be handled separately if found
1561 $includeNull = false;
1562 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1563 $includeNull = true;
1564 unset( $value[$nullKey] );
1566 if ( count( $value ) == 0 && !$includeNull ) {
1567 throw new InvalidArgumentException(
1568 __METHOD__
. ": empty input for field $field" );
1569 } elseif ( count( $value ) == 0 ) {
1570 // only check if $field is null
1571 $list .= "$field IS NULL";
1573 // IN clause contains at least one valid element
1574 if ( $includeNull ) {
1575 // Group subconditions to ensure correct precedence
1578 if ( count( $value ) == 1 ) {
1579 // Special-case single values, as IN isn't terribly efficient
1580 // Don't necessarily assume the single key is 0; we don't
1581 // enforce linear numeric ordering on other arrays here.
1582 $value = array_values( $value )[0];
1583 $list .= $field . " = " . $this->addQuotes( $value );
1585 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1587 // if null present in array, append IS NULL
1588 if ( $includeNull ) {
1589 $list .= " OR $field IS NULL)";
1592 } elseif ( $value === null ) {
1593 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1594 $list .= "$field IS ";
1595 } elseif ( $mode == self
::LIST_SET
) {
1596 $list .= "$field = ";
1601 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1603 $list .= "$field = ";
1605 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1612 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1615 foreach ( $data as $base => $sub ) {
1616 if ( count( $sub ) ) {
1617 $conds[] = $this->makeList(
1618 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1624 return $this->makeList( $conds, self
::LIST_OR
);
1626 // Nothing to search for...
1631 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1635 public function bitNot( $field ) {
1639 public function bitAnd( $fieldLeft, $fieldRight ) {
1640 return "($fieldLeft & $fieldRight)";
1643 public function bitOr( $fieldLeft, $fieldRight ) {
1644 return "($fieldLeft | $fieldRight)";
1647 public function buildConcat( $stringList ) {
1648 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1651 public function buildGroupConcatField(
1652 $delim, $table, $field, $conds = '', $join_conds = []
1654 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1656 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1659 public function buildStringCast( $field ) {
1663 public function selectDB( $db ) {
1664 # Stub. Shouldn't cause serious problems if it's not overridden, but
1665 # if your database engine supports a concept similar to MySQL's
1666 # databases you may as well.
1667 $this->mDBname
= $db;
1672 public function getDBname() {
1673 return $this->mDBname
;
1676 public function getServer() {
1677 return $this->mServer
;
1681 * Format a table name ready for use in constructing an SQL query
1683 * This does two important things: it quotes the table names to clean them up,
1684 * and it adds a table prefix if only given a table name with no quotes.
1686 * All functions of this object which require a table name call this function
1687 * themselves. Pass the canonical name to such functions. This is only needed
1688 * when calling query() directly.
1690 * @note This function does not sanitize user input. It is not safe to use
1691 * this function to escape user input.
1692 * @param string $name Database table name
1693 * @param string $format One of:
1694 * quoted - Automatically pass the table name through addIdentifierQuotes()
1695 * so that it can be used in a query.
1696 * raw - Do not add identifier quotes to the table name
1697 * @return string Full database name
1699 public function tableName( $name, $format = 'quoted' ) {
1700 # Skip the entire process when we have a string quoted on both ends.
1701 # Note that we check the end so that we will still quote any use of
1702 # use of `database`.table. But won't break things if someone wants
1703 # to query a database table with a dot in the name.
1704 if ( $this->isQuotedIdentifier( $name ) ) {
1708 # Lets test for any bits of text that should never show up in a table
1709 # name. Basically anything like JOIN or ON which are actually part of
1710 # SQL queries, but may end up inside of the table value to combine
1711 # sql. Such as how the API is doing.
1712 # Note that we use a whitespace test rather than a \b test to avoid
1713 # any remote case where a word like on may be inside of a table name
1714 # surrounded by symbols which may be considered word breaks.
1715 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1719 # Split database and table into proper variables.
1720 # We reverse the explode so that database.table and table both output
1721 # the correct table.
1722 $dbDetails = explode( '.', $name, 3 );
1723 if ( count( $dbDetails ) == 3 ) {
1724 list( $database, $schema, $table ) = $dbDetails;
1725 # We don't want any prefix added in this case
1727 } elseif ( count( $dbDetails ) == 2 ) {
1728 list( $database, $table ) = $dbDetails;
1729 # We don't want any prefix added in this case
1730 # In dbs that support it, $database may actually be the schema
1731 # but that doesn't affect any of the functionality here
1735 list( $table ) = $dbDetails;
1736 if ( isset( $this->tableAliases
[$table] ) ) {
1737 $database = $this->tableAliases
[$table]['dbname'];
1738 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1739 ?
$this->tableAliases
[$table]['schema']
1741 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1742 ?
$this->tableAliases
[$table]['prefix']
1743 : $this->mTablePrefix
;
1746 $schema = $this->mSchema
; # Default schema
1747 $prefix = $this->mTablePrefix
; # Default prefix
1751 # Quote $table and apply the prefix if not quoted.
1752 # $tableName might be empty if this is called from Database::replaceVars()
1753 $tableName = "{$prefix}{$table}";
1754 if ( $format == 'quoted'
1755 && !$this->isQuotedIdentifier( $tableName ) && $tableName !== ''
1757 $tableName = $this->addIdentifierQuotes( $tableName );
1760 # Quote $schema and merge it with the table name if needed
1761 if ( strlen( $schema ) ) {
1762 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1763 $schema = $this->addIdentifierQuotes( $schema );
1765 $tableName = $schema . '.' . $tableName;
1768 # Quote $database and merge it with the table name if needed
1769 if ( $database !== '' ) {
1770 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1771 $database = $this->addIdentifierQuotes( $database );
1773 $tableName = $database . '.' . $tableName;
1780 * Fetch a number of table names into an array
1781 * This is handy when you need to construct SQL for joins
1784 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1785 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1786 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1790 public function tableNames() {
1791 $inArray = func_get_args();
1794 foreach ( $inArray as $name ) {
1795 $retVal[$name] = $this->tableName( $name );
1802 * Fetch a number of table names into an zero-indexed numerical array
1803 * This is handy when you need to construct SQL for joins
1806 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1807 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1808 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1812 public function tableNamesN() {
1813 $inArray = func_get_args();
1816 foreach ( $inArray as $name ) {
1817 $retVal[] = $this->tableName( $name );
1824 * Get an aliased table name
1825 * e.g. tableName AS newTableName
1827 * @param string $name Table name, see tableName()
1828 * @param string|bool $alias Alias (optional)
1829 * @return string SQL name for aliased table. Will not alias a table to its own name
1831 protected function tableNameWithAlias( $name, $alias = false ) {
1832 if ( !$alias ||
$alias == $name ) {
1833 return $this->tableName( $name );
1835 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1840 * Gets an array of aliased table names
1842 * @param array $tables [ [alias] => table ]
1843 * @return string[] See tableNameWithAlias()
1845 protected function tableNamesWithAlias( $tables ) {
1847 foreach ( $tables as $alias => $table ) {
1848 if ( is_numeric( $alias ) ) {
1851 $retval[] = $this->tableNameWithAlias( $table, $alias );
1858 * Get an aliased field name
1859 * e.g. fieldName AS newFieldName
1861 * @param string $name Field name
1862 * @param string|bool $alias Alias (optional)
1863 * @return string SQL name for aliased field. Will not alias a field to its own name
1865 protected function fieldNameWithAlias( $name, $alias = false ) {
1866 if ( !$alias ||
(string)$alias === (string)$name ) {
1869 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1874 * Gets an array of aliased field names
1876 * @param array $fields [ [alias] => field ]
1877 * @return string[] See fieldNameWithAlias()
1879 protected function fieldNamesWithAlias( $fields ) {
1881 foreach ( $fields as $alias => $field ) {
1882 if ( is_numeric( $alias ) ) {
1885 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1892 * Get the aliased table name clause for a FROM clause
1893 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
1895 * @param array $tables ( [alias] => table )
1896 * @param array $use_index Same as for select()
1897 * @param array $ignore_index Same as for select()
1898 * @param array $join_conds Same as for select()
1901 protected function tableNamesWithIndexClauseOrJOIN(
1902 $tables, $use_index = [], $ignore_index = [], $join_conds = []
1906 $use_index = (array)$use_index;
1907 $ignore_index = (array)$ignore_index;
1908 $join_conds = (array)$join_conds;
1910 foreach ( $tables as $alias => $table ) {
1911 if ( !is_string( $alias ) ) {
1912 // No alias? Set it equal to the table name
1915 // Is there a JOIN clause for this table?
1916 if ( isset( $join_conds[$alias] ) ) {
1917 list( $joinType, $conds ) = $join_conds[$alias];
1918 $tableClause = $joinType;
1919 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1920 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1921 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1923 $tableClause .= ' ' . $use;
1926 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
1927 $ignore = $this->ignoreIndexClause(
1928 implode( ',', (array)$ignore_index[$alias] ) );
1929 if ( $ignore != '' ) {
1930 $tableClause .= ' ' . $ignore;
1933 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
1935 $tableClause .= ' ON (' . $on . ')';
1938 $retJOIN[] = $tableClause;
1939 } elseif ( isset( $use_index[$alias] ) ) {
1940 // Is there an INDEX clause for this table?
1941 $tableClause = $this->tableNameWithAlias( $table, $alias );
1942 $tableClause .= ' ' . $this->useIndexClause(
1943 implode( ',', (array)$use_index[$alias] )
1946 $ret[] = $tableClause;
1947 } elseif ( isset( $ignore_index[$alias] ) ) {
1948 // Is there an INDEX clause for this table?
1949 $tableClause = $this->tableNameWithAlias( $table, $alias );
1950 $tableClause .= ' ' . $this->ignoreIndexClause(
1951 implode( ',', (array)$ignore_index[$alias] )
1954 $ret[] = $tableClause;
1956 $tableClause = $this->tableNameWithAlias( $table, $alias );
1958 $ret[] = $tableClause;
1962 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1963 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1964 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1966 // Compile our final table clause
1967 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
1971 * Get the name of an index in a given table.
1973 * @param string $index
1976 protected function indexName( $index ) {
1980 public function addQuotes( $s ) {
1981 if ( $s instanceof Blob
) {
1984 if ( $s === null ) {
1986 } elseif ( is_bool( $s ) ) {
1989 # This will also quote numeric values. This should be harmless,
1990 # and protects against weird problems that occur when they really
1991 # _are_ strings such as article titles and string->number->string
1992 # conversion is not 1:1.
1993 return "'" . $this->strencode( $s ) . "'";
1998 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1999 * MySQL uses `backticks` while basically everything else uses double quotes.
2000 * Since MySQL is the odd one out here the double quotes are our generic
2001 * and we implement backticks in DatabaseMysql.
2006 public function addIdentifierQuotes( $s ) {
2007 return '"' . str_replace( '"', '""', $s ) . '"';
2011 * Returns if the given identifier looks quoted or not according to
2012 * the database convention for quoting identifiers .
2014 * @note Do not use this to determine if untrusted input is safe.
2015 * A malicious user can trick this function.
2016 * @param string $name
2019 public function isQuotedIdentifier( $name ) {
2020 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2027 protected function escapeLikeInternal( $s ) {
2028 return addcslashes( $s, '\%_' );
2031 public function buildLike() {
2032 $params = func_get_args();
2034 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2035 $params = $params[0];
2040 foreach ( $params as $value ) {
2041 if ( $value instanceof LikeMatch
) {
2042 $s .= $value->toString();
2044 $s .= $this->escapeLikeInternal( $value );
2048 return " LIKE {$this->addQuotes( $s )} ";
2051 public function anyChar() {
2052 return new LikeMatch( '_' );
2055 public function anyString() {
2056 return new LikeMatch( '%' );
2059 public function nextSequenceValue( $seqName ) {
2064 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2065 * is only needed because a) MySQL must be as efficient as possible due to
2066 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2067 * which index to pick. Anyway, other databases might have different
2068 * indexes on a given table. So don't bother overriding this unless you're
2070 * @param string $index
2073 public function useIndexClause( $index ) {
2078 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2079 * is only needed because a) MySQL must be as efficient as possible due to
2080 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2081 * which index to pick. Anyway, other databases might have different
2082 * indexes on a given table. So don't bother overriding this unless you're
2084 * @param string $index
2087 public function ignoreIndexClause( $index ) {
2091 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2092 $quotedTable = $this->tableName( $table );
2094 if ( count( $rows ) == 0 ) {
2099 if ( !is_array( reset( $rows ) ) ) {
2103 // @FXIME: this is not atomic, but a trx would break affectedRows()
2104 foreach ( $rows as $row ) {
2105 # Delete rows which collide
2106 if ( $uniqueIndexes ) {
2107 $sql = "DELETE FROM $quotedTable WHERE ";
2109 foreach ( $uniqueIndexes as $index ) {
2116 if ( is_array( $index ) ) {
2118 foreach ( $index as $col ) {
2124 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2127 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2131 $this->query( $sql, $fname );
2134 # Now insert the row
2135 $this->insert( $table, $row, $fname );
2140 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2143 * @param string $table Table name
2144 * @param array|string $rows Row(s) to insert
2145 * @param string $fname Caller function name
2147 * @return ResultWrapper
2149 protected function nativeReplace( $table, $rows, $fname ) {
2150 $table = $this->tableName( $table );
2153 if ( !is_array( reset( $rows ) ) ) {
2157 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2160 foreach ( $rows as $row ) {
2167 $sql .= '(' . $this->makeList( $row ) . ')';
2170 return $this->query( $sql, $fname );
2173 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2176 if ( !count( $rows ) ) {
2177 return true; // nothing to do
2180 if ( !is_array( reset( $rows ) ) ) {
2184 if ( count( $uniqueIndexes ) ) {
2185 $clauses = []; // list WHERE clauses that each identify a single row
2186 foreach ( $rows as $row ) {
2187 foreach ( $uniqueIndexes as $index ) {
2188 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2189 $rowKey = []; // unique key to this row
2190 foreach ( $index as $column ) {
2191 $rowKey[$column] = $row[$column];
2193 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2196 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2201 $useTrx = !$this->mTrxLevel
;
2203 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2206 # Update any existing conflicting row(s)
2207 if ( $where !== false ) {
2208 $ok = $this->update( $table, $set, $where, $fname );
2212 # Now insert any non-conflicting row(s)
2213 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2214 } catch ( Exception
$e ) {
2216 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2221 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2227 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2231 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2234 $delTable = $this->tableName( $delTable );
2235 $joinTable = $this->tableName( $joinTable );
2236 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2237 if ( $conds != '*' ) {
2238 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2242 $this->query( $sql, $fname );
2246 * Returns the size of a text field, or -1 for "unlimited"
2248 * @param string $table
2249 * @param string $field
2252 public function textFieldSize( $table, $field ) {
2253 $table = $this->tableName( $table );
2254 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2255 $res = $this->query( $sql, __METHOD__
);
2256 $row = $this->fetchObject( $res );
2260 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2269 public function delete( $table, $conds, $fname = __METHOD__
) {
2271 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2274 $table = $this->tableName( $table );
2275 $sql = "DELETE FROM $table";
2277 if ( $conds != '*' ) {
2278 if ( is_array( $conds ) ) {
2279 $conds = $this->makeList( $conds, self
::LIST_AND
);
2281 $sql .= ' WHERE ' . $conds;
2284 return $this->query( $sql, $fname );
2287 public function insertSelect(
2288 $destTable, $srcTable, $varMap, $conds,
2289 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2291 if ( $this->cliMode
) {
2292 // For massive migrations with downtime, we don't want to select everything
2293 // into memory and OOM, so do all this native on the server side if possible.
2294 return $this->nativeInsertSelect(
2305 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2306 // on only the master (without needing row-based-replication). It also makes it easy to
2307 // know how big the INSERT is going to be.
2309 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2310 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2312 $selectOptions[] = 'FOR UPDATE';
2313 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2319 foreach ( $res as $row ) {
2320 $rows[] = (array)$row;
2323 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2326 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2327 $fname = __METHOD__
,
2328 $insertOptions = [], $selectOptions = []
2330 $destTable = $this->tableName( $destTable );
2332 if ( !is_array( $insertOptions ) ) {
2333 $insertOptions = [ $insertOptions ];
2336 $insertOptions = $this->makeInsertOptions( $insertOptions );
2338 if ( !is_array( $selectOptions ) ) {
2339 $selectOptions = [ $selectOptions ];
2342 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2345 if ( is_array( $srcTable ) ) {
2346 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2348 $srcTable = $this->tableName( $srcTable );
2351 $sql = "INSERT $insertOptions" .
2352 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2353 " SELECT $startOpts " . implode( ',', $varMap ) .
2354 " FROM $srcTable $useIndex $ignoreIndex ";
2356 if ( $conds != '*' ) {
2357 if ( is_array( $conds ) ) {
2358 $conds = $this->makeList( $conds, self
::LIST_AND
);
2360 $sql .= " WHERE $conds";
2363 $sql .= " $tailOpts";
2365 return $this->query( $sql, $fname );
2369 * Construct a LIMIT query with optional offset. This is used for query
2370 * pages. The SQL should be adjusted so that only the first $limit rows
2371 * are returned. If $offset is provided as well, then the first $offset
2372 * rows should be discarded, and the next $limit rows should be returned.
2373 * If the result of the query is not ordered, then the rows to be returned
2374 * are theoretically arbitrary.
2376 * $sql is expected to be a SELECT, if that makes a difference.
2378 * The version provided by default works in MySQL and SQLite. It will very
2379 * likely need to be overridden for most other DBMSes.
2381 * @param string $sql SQL query we will append the limit too
2382 * @param int $limit The SQL limit
2383 * @param int|bool $offset The SQL offset (default false)
2384 * @throws DBUnexpectedError
2387 public function limitResult( $sql, $limit, $offset = false ) {
2388 if ( !is_numeric( $limit ) ) {
2389 throw new DBUnexpectedError( $this,
2390 "Invalid non-numeric limit passed to limitResult()\n" );
2393 return "$sql LIMIT "
2394 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2398 public function unionSupportsOrderAndLimit() {
2399 return true; // True for almost every DB supported
2402 public function unionQueries( $sqls, $all ) {
2403 $glue = $all ?
') UNION ALL (' : ') UNION (';
2405 return '(' . implode( $glue, $sqls ) . ')';
2408 public function conditional( $cond, $trueVal, $falseVal ) {
2409 if ( is_array( $cond ) ) {
2410 $cond = $this->makeList( $cond, self
::LIST_AND
);
2413 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2416 public function strreplace( $orig, $old, $new ) {
2417 return "REPLACE({$orig}, {$old}, {$new})";
2420 public function getServerUptime() {
2424 public function wasDeadlock() {
2428 public function wasLockTimeout() {
2432 public function wasErrorReissuable() {
2436 public function wasReadOnlyError() {
2441 * Do not use this method outside of Database/DBError classes
2443 * @param integer|string $errno
2444 * @return bool Whether the given query error was a connection drop
2446 public function wasConnectionError( $errno ) {
2451 * Perform a deadlock-prone transaction.
2453 * This function invokes a callback function to perform a set of write
2454 * queries. If a deadlock occurs during the processing, the transaction
2455 * will be rolled back and the callback function will be called again.
2457 * Avoid using this method outside of Job or Maintenance classes.
2460 * $dbw->deadlockLoop( callback, ... );
2462 * Extra arguments are passed through to the specified callback function.
2463 * This method requires that no transactions are already active to avoid
2464 * causing premature commits or exceptions.
2466 * Returns whatever the callback function returned on its successful,
2467 * iteration, or false on error, for example if the retry limit was
2471 * @throws DBUnexpectedError
2474 public function deadlockLoop() {
2475 $args = func_get_args();
2476 $function = array_shift( $args );
2477 $tries = self
::DEADLOCK_TRIES
;
2479 $this->begin( __METHOD__
);
2482 /** @var Exception $e */
2486 $retVal = call_user_func_array( $function, $args );
2488 } catch ( DBQueryError
$e ) {
2489 if ( $this->wasDeadlock() ) {
2490 // Retry after a randomized delay
2491 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2493 // Throw the error back up
2497 } while ( --$tries > 0 );
2499 if ( $tries <= 0 ) {
2500 // Too many deadlocks; give up
2501 $this->rollback( __METHOD__
);
2504 $this->commit( __METHOD__
);
2510 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2511 # Real waits are implemented in the subclass.
2515 public function getSlavePos() {
2520 public function getMasterPos() {
2525 public function serverIsReadOnly() {
2529 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2530 if ( !$this->mTrxLevel
) {
2531 throw new DBUnexpectedError( $this, "No transaction is active." );
2533 $this->mTrxEndCallbacks
[] = [ $callback, $fname ];
2536 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2537 $this->mTrxIdleCallbacks
[] = [ $callback, $fname ];
2538 if ( !$this->mTrxLevel
) {
2539 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2543 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2544 if ( $this->mTrxLevel
) {
2545 $this->mTrxPreCommitCallbacks
[] = [ $callback, $fname ];
2547 // If no transaction is active, then make one for this callback
2548 $this->startAtomic( __METHOD__
);
2550 call_user_func( $callback );
2551 $this->endAtomic( __METHOD__
);
2552 } catch ( Exception
$e ) {
2553 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2559 final public function setTransactionListener( $name, callable
$callback = null ) {
2561 $this->mTrxRecurringCallbacks
[$name] = $callback;
2563 unset( $this->mTrxRecurringCallbacks
[$name] );
2568 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2570 * This method should not be used outside of Database/LoadBalancer
2572 * @param bool $suppress
2575 final public function setTrxEndCallbackSuppression( $suppress ) {
2576 $this->mTrxEndCallbacksSuppressed
= $suppress;
2580 * Actually run and consume any "on transaction idle/resolution" callbacks.
2582 * This method should not be used outside of Database/LoadBalancer
2584 * @param integer $trigger IDatabase::TRIGGER_* constant
2588 public function runOnTransactionIdleCallbacks( $trigger ) {
2589 if ( $this->mTrxEndCallbacksSuppressed
) {
2593 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
2594 /** @var Exception $e */
2595 $e = null; // first exception
2596 do { // callbacks may add callbacks :)
2597 $callbacks = array_merge(
2598 $this->mTrxIdleCallbacks
,
2599 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2601 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2602 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2603 foreach ( $callbacks as $callback ) {
2605 list( $phpCallback ) = $callback;
2606 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
2607 call_user_func_array( $phpCallback, [ $trigger ] );
2609 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
2611 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
2613 } catch ( Exception
$ex ) {
2614 call_user_func( $this->errorLogger
, $ex );
2616 // Some callbacks may use startAtomic/endAtomic, so make sure
2617 // their transactions are ended so other callbacks don't fail
2618 if ( $this->trxLevel() ) {
2619 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2623 } while ( count( $this->mTrxIdleCallbacks
) );
2625 if ( $e instanceof Exception
) {
2626 throw $e; // re-throw any first exception
2631 * Actually run and consume any "on transaction pre-commit" callbacks.
2633 * This method should not be used outside of Database/LoadBalancer
2638 public function runOnTransactionPreCommitCallbacks() {
2639 $e = null; // first exception
2640 do { // callbacks may add callbacks :)
2641 $callbacks = $this->mTrxPreCommitCallbacks
;
2642 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2643 foreach ( $callbacks as $callback ) {
2645 list( $phpCallback ) = $callback;
2646 call_user_func( $phpCallback );
2647 } catch ( Exception
$ex ) {
2648 call_user_func( $this->errorLogger
, $ex );
2652 } while ( count( $this->mTrxPreCommitCallbacks
) );
2654 if ( $e instanceof Exception
) {
2655 throw $e; // re-throw any first exception
2660 * Actually run any "transaction listener" callbacks.
2662 * This method should not be used outside of Database/LoadBalancer
2664 * @param integer $trigger IDatabase::TRIGGER_* constant
2668 public function runTransactionListenerCallbacks( $trigger ) {
2669 if ( $this->mTrxEndCallbacksSuppressed
) {
2673 /** @var Exception $e */
2674 $e = null; // first exception
2676 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2678 $phpCallback( $trigger, $this );
2679 } catch ( Exception
$ex ) {
2680 call_user_func( $this->errorLogger
, $ex );
2685 if ( $e instanceof Exception
) {
2686 throw $e; // re-throw any first exception
2690 final public function startAtomic( $fname = __METHOD__
) {
2691 if ( !$this->mTrxLevel
) {
2692 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2693 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2694 // in all changes being in one transaction to keep requests transactional.
2695 if ( !$this->getFlag( self
::DBO_TRX
) ) {
2696 $this->mTrxAutomaticAtomic
= true;
2700 $this->mTrxAtomicLevels
[] = $fname;
2703 final public function endAtomic( $fname = __METHOD__
) {
2704 if ( !$this->mTrxLevel
) {
2705 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2707 if ( !$this->mTrxAtomicLevels ||
2708 array_pop( $this->mTrxAtomicLevels
) !== $fname
2710 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2713 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2714 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2718 final public function doAtomicSection( $fname, callable
$callback ) {
2719 $this->startAtomic( $fname );
2721 $res = call_user_func_array( $callback, [ $this, $fname ] );
2722 } catch ( Exception
$e ) {
2723 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2726 $this->endAtomic( $fname );
2731 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2732 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2733 if ( $this->mTrxLevel
) {
2734 if ( $this->mTrxAtomicLevels
) {
2735 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2736 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2737 throw new DBUnexpectedError( $this, $msg );
2738 } elseif ( !$this->mTrxAutomatic
) {
2739 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2740 throw new DBUnexpectedError( $this, $msg );
2742 // @TODO: make this an exception at some point
2743 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2744 $this->queryLogger
->error( $msg );
2745 return; // join the main transaction set
2747 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2748 // @TODO: make this an exception at some point
2749 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2750 $this->queryLogger
->error( $msg );
2751 return; // let any writes be in the main transaction
2754 // Avoid fatals if close() was called
2755 $this->assertOpen();
2757 $this->doBegin( $fname );
2758 $this->mTrxTimestamp
= microtime( true );
2759 $this->mTrxFname
= $fname;
2760 $this->mTrxDoneWrites
= false;
2761 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2762 $this->mTrxAutomaticAtomic
= false;
2763 $this->mTrxAtomicLevels
= [];
2764 $this->mTrxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2765 $this->mTrxWriteDuration
= 0.0;
2766 $this->mTrxWriteQueryCount
= 0;
2767 $this->mTrxWriteAdjDuration
= 0.0;
2768 $this->mTrxWriteAdjQueryCount
= 0;
2769 $this->mTrxWriteCallers
= [];
2770 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2771 // Get an estimate of the replica DB lag before then, treating estimate staleness
2772 // as lag itself just to be safe
2773 $status = $this->getApproximateLagStatus();
2774 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2778 * Issues the BEGIN command to the database server.
2780 * @see DatabaseBase::begin()
2781 * @param string $fname
2783 protected function doBegin( $fname ) {
2784 $this->query( 'BEGIN', $fname );
2785 $this->mTrxLevel
= 1;
2788 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2789 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2790 // There are still atomic sections open. This cannot be ignored
2791 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2792 throw new DBUnexpectedError(
2794 "$fname: Got COMMIT while atomic sections $levels are still open."
2798 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2799 if ( !$this->mTrxLevel
) {
2800 return; // nothing to do
2801 } elseif ( !$this->mTrxAutomatic
) {
2802 throw new DBUnexpectedError(
2804 "$fname: Flushing an explicit transaction, getting out of sync."
2808 if ( !$this->mTrxLevel
) {
2809 $this->queryLogger
->error(
2810 "$fname: No transaction to commit, something got out of sync." );
2811 return; // nothing to do
2812 } elseif ( $this->mTrxAutomatic
) {
2813 // @TODO: make this an exception at some point
2814 $msg = "$fname: Explicit commit of implicit transaction.";
2815 $this->queryLogger
->error( $msg );
2816 return; // wait for the main transaction set commit round
2820 // Avoid fatals if close() was called
2821 $this->assertOpen();
2823 $this->runOnTransactionPreCommitCallbacks();
2824 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2825 $this->doCommit( $fname );
2826 if ( $this->mTrxDoneWrites
) {
2827 $this->mDoneWrites
= microtime( true );
2828 $this->trxProfiler
->transactionWritingOut(
2829 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2832 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2833 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
2837 * Issues the COMMIT command to the database server.
2839 * @see DatabaseBase::commit()
2840 * @param string $fname
2842 protected function doCommit( $fname ) {
2843 if ( $this->mTrxLevel
) {
2844 $this->query( 'COMMIT', $fname );
2845 $this->mTrxLevel
= 0;
2849 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2850 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2851 if ( !$this->mTrxLevel
) {
2852 return; // nothing to do
2855 if ( !$this->mTrxLevel
) {
2856 $this->queryLogger
->error(
2857 "$fname: No transaction to rollback, something got out of sync." );
2858 return; // nothing to do
2859 } elseif ( $this->getFlag( self
::DBO_TRX
) ) {
2860 throw new DBUnexpectedError(
2862 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2867 // Avoid fatals if close() was called
2868 $this->assertOpen();
2870 $this->doRollback( $fname );
2871 $this->mTrxAtomicLevels
= [];
2872 if ( $this->mTrxDoneWrites
) {
2873 $this->trxProfiler
->transactionWritingOut(
2874 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
2877 $this->mTrxIdleCallbacks
= []; // clear
2878 $this->mTrxPreCommitCallbacks
= []; // clear
2879 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
2880 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
2884 * Issues the ROLLBACK command to the database server.
2886 * @see DatabaseBase::rollback()
2887 * @param string $fname
2889 protected function doRollback( $fname ) {
2890 if ( $this->mTrxLevel
) {
2891 # Disconnects cause rollback anyway, so ignore those errors
2892 $ignoreErrors = true;
2893 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
2894 $this->mTrxLevel
= 0;
2898 public function flushSnapshot( $fname = __METHOD__
) {
2899 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
2900 // This only flushes transactions to clear snapshots, not to write data
2901 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
2902 throw new DBUnexpectedError(
2904 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
2908 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2911 public function explicitTrxActive() {
2912 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
2916 * Creates a new table with structure copied from existing table
2917 * Note that unlike most database abstraction functions, this function does not
2918 * automatically append database prefix, because it works at a lower
2919 * abstraction level.
2920 * The table names passed to this function shall not be quoted (this
2921 * function calls addIdentifierQuotes when needed).
2923 * @param string $oldName Name of table whose structure should be copied
2924 * @param string $newName Name of table to be created
2925 * @param bool $temporary Whether the new table should be temporary
2926 * @param string $fname Calling function name
2927 * @throws RuntimeException
2928 * @return bool True if operation was successful
2930 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
2933 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2936 public function listTables( $prefix = null, $fname = __METHOD__
) {
2937 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2941 * Reset the views process cache set by listViews()
2944 final public function clearViewsCache() {
2945 $this->allViews
= null;
2949 * Lists all the VIEWs in the database
2951 * For caching purposes the list of all views should be stored in
2952 * $this->allViews. The process cache can be cleared with clearViewsCache()
2954 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
2955 * @param string $fname Name of calling function
2956 * @throws RuntimeException
2960 public function listViews( $prefix = null, $fname = __METHOD__
) {
2961 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2965 * Differentiates between a TABLE and a VIEW
2967 * @param string $name Name of the database-structure to test.
2968 * @throws RuntimeException
2972 public function isView( $name ) {
2973 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2976 public function timestamp( $ts = 0 ) {
2977 $t = new ConvertibleTimestamp( $ts );
2978 // Let errors bubble up to avoid putting garbage in the DB
2979 return $t->getTimestamp( TS_MW
);
2982 public function timestampOrNull( $ts = null ) {
2983 if ( is_null( $ts ) ) {
2986 return $this->timestamp( $ts );
2991 * Take the result from a query, and wrap it in a ResultWrapper if
2992 * necessary. Boolean values are passed through as is, to indicate success
2993 * of write queries or failure.
2995 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2996 * resource, and it was necessary to call this function to convert it to
2997 * a wrapper. Nowadays, raw database objects are never exposed to external
2998 * callers, so this is unnecessary in external code.
3000 * @param bool|ResultWrapper|resource|object $result
3001 * @return bool|ResultWrapper
3003 protected function resultObject( $result ) {
3006 } elseif ( $result instanceof ResultWrapper
) {
3008 } elseif ( $result === true ) {
3009 // Successful write query
3012 return new ResultWrapper( $this, $result );
3016 public function ping( &$rtt = null ) {
3017 // Avoid hitting the server if it was hit recently
3018 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3019 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
3020 $rtt = $this->mRTTEstimate
;
3021 return true; // don't care about $rtt
3025 // This will reconnect if possible or return false if not
3026 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
3027 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3028 $this->restoreFlags( self
::RESTORE_PRIOR
);
3031 $rtt = $this->mRTTEstimate
;
3040 protected function reconnect() {
3041 $this->closeConnection();
3042 $this->mOpened
= false;
3043 $this->mConn
= false;
3045 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3046 $this->lastPing
= microtime( true );
3048 } catch ( DBConnectionError
$e ) {
3055 public function getSessionLagStatus() {
3056 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3060 * Get the replica DB lag when the current transaction started
3062 * This is useful when transactions might use snapshot isolation
3063 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3064 * is this lag plus transaction duration. If they don't, it is still
3065 * safe to be pessimistic. This returns null if there is no transaction.
3067 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3070 protected function getTransactionLagStatus() {
3071 return $this->mTrxLevel
3072 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3077 * Get a replica DB lag estimate for this server
3079 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3082 protected function getApproximateLagStatus() {
3084 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3085 'since' => microtime( true )
3090 * Merge the result of getSessionLagStatus() for several DBs
3091 * using the most pessimistic values to estimate the lag of
3092 * any data derived from them in combination
3094 * This is information is useful for caching modules
3096 * @see WANObjectCache::set()
3097 * @see WANObjectCache::getWithSetCallback()
3099 * @param IDatabase $db1
3100 * @param IDatabase ...
3101 * @return array Map of values:
3102 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3103 * - since: oldest UNIX timestamp of any of the DB lag estimates
3104 * - pending: whether any of the DBs have uncommitted changes
3107 public static function getCacheSetOptions( IDatabase
$db1 ) {
3108 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3109 foreach ( func_get_args() as $db ) {
3110 /** @var IDatabase $db */
3111 $status = $db->getSessionLagStatus();
3112 if ( $status['lag'] === false ) {
3113 $res['lag'] = false;
3114 } elseif ( $res['lag'] !== false ) {
3115 $res['lag'] = max( $res['lag'], $status['lag'] );
3117 $res['since'] = min( $res['since'], $status['since'] );
3118 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3124 public function getLag() {
3128 public function maxListLen() {
3132 public function encodeBlob( $b ) {
3136 public function decodeBlob( $b ) {
3137 if ( $b instanceof Blob
) {
3143 public function setSessionOptions( array $options ) {
3147 * Read and execute SQL commands from a file.
3149 * Returns true on success, error string or exception on failure (depending
3150 * on object's error ignore settings).
3152 * @param string $filename File name to open
3153 * @param bool|callable $lineCallback Optional function called before reading each line
3154 * @param bool|callable $resultCallback Optional function called for each MySQL result
3155 * @param bool|string $fname Calling function name or false if name should be
3156 * generated dynamically using $filename
3157 * @param bool|callable $inputCallback Optional function called for each
3158 * complete line sent
3159 * @return bool|string
3162 public function sourceFile(
3164 $lineCallback = false,
3165 $resultCallback = false,
3167 $inputCallback = false
3169 MediaWiki\
suppressWarnings();
3170 $fp = fopen( $filename, 'r' );
3171 MediaWiki\restoreWarnings
();
3173 if ( false === $fp ) {
3174 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3178 $fname = __METHOD__
. "( $filename )";
3182 $error = $this->sourceStream(
3183 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3184 } catch ( Exception
$e ) {
3194 public function setSchemaVars( $vars ) {
3195 $this->mSchemaVars
= $vars;
3199 * Read and execute commands from an open file handle.
3201 * Returns true on success, error string or exception on failure (depending
3202 * on object's error ignore settings).
3204 * @param resource $fp File handle
3205 * @param bool|callable $lineCallback Optional function called before reading each query
3206 * @param bool|callable $resultCallback Optional function called for each MySQL result
3207 * @param string $fname Calling function name
3208 * @param bool|callable $inputCallback Optional function called for each complete query sent
3209 * @return bool|string
3211 public function sourceStream(
3213 $lineCallback = false,
3214 $resultCallback = false,
3215 $fname = __METHOD__
,
3216 $inputCallback = false
3220 while ( !feof( $fp ) ) {
3221 if ( $lineCallback ) {
3222 call_user_func( $lineCallback );
3225 $line = trim( fgets( $fp ) );
3227 if ( $line == '' ) {
3231 if ( '-' == $line[0] && '-' == $line[1] ) {
3239 $done = $this->streamStatementEnd( $cmd, $line );
3243 if ( $done ||
feof( $fp ) ) {
3244 $cmd = $this->replaceVars( $cmd );
3246 if ( !$inputCallback ||
call_user_func( $inputCallback, $cmd ) ) {
3247 $res = $this->query( $cmd, $fname );
3249 if ( $resultCallback ) {
3250 call_user_func( $resultCallback, $res, $this );
3253 if ( false === $res ) {
3254 $err = $this->lastError();
3256 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3267 * Called by sourceStream() to check if we've reached a statement end
3269 * @param string &$sql SQL assembled so far
3270 * @param string &$newLine New line about to be added to $sql
3271 * @return bool Whether $newLine contains end of the statement
3273 public function streamStatementEnd( &$sql, &$newLine ) {
3274 if ( $this->delimiter
) {
3276 $newLine = preg_replace(
3277 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3278 if ( $newLine != $prev ) {
3287 * Database independent variable replacement. Replaces a set of variables
3288 * in an SQL statement with their contents as given by $this->getSchemaVars().
3290 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3292 * - '{$var}' should be used for text and is passed through the database's
3294 * - `{$var}` should be used for identifiers (e.g. table and database names).
3295 * It is passed through the database's addIdentifierQuotes method which
3296 * can be overridden if the database uses something other than backticks.
3297 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3298 * database's tableName method.
3299 * - / *i* / passes the name that follows through the database's indexName method.
3300 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3301 * its use should be avoided. In 1.24 and older, string encoding was applied.
3303 * @param string $ins SQL statement to replace variables in
3304 * @return string The new SQL statement with variables replaced
3306 protected function replaceVars( $ins ) {
3307 $vars = $this->getSchemaVars();
3308 return preg_replace_callback(
3310 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3311 \'\{\$ (\w+) }\' | # 3. addQuotes
3312 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3313 /\*\$ (\w+) \*/ # 5. leave unencoded
3315 function ( $m ) use ( $vars ) {
3316 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3317 // check for both nonexistent keys *and* the empty string.
3318 if ( isset( $m[1] ) && $m[1] !== '' ) {
3319 if ( $m[1] === 'i' ) {
3320 return $this->indexName( $m[2] );
3322 return $this->tableName( $m[2] );
3324 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3325 return $this->addQuotes( $vars[$m[3]] );
3326 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3327 return $this->addIdentifierQuotes( $vars[$m[4]] );
3328 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3329 return $vars[$m[5]];
3339 * Get schema variables. If none have been set via setSchemaVars(), then
3340 * use some defaults from the current object.
3344 protected function getSchemaVars() {
3345 if ( $this->mSchemaVars
) {
3346 return $this->mSchemaVars
;
3348 return $this->getDefaultSchemaVars();
3353 * Get schema variables to use if none have been set via setSchemaVars().
3355 * Override this in derived classes to provide variables for tables.sql
3356 * and SQL patch files.
3360 protected function getDefaultSchemaVars() {
3364 public function lockIsFree( $lockName, $method ) {
3368 public function lock( $lockName, $method, $timeout = 5 ) {
3369 $this->mNamedLocksHeld
[$lockName] = 1;
3374 public function unlock( $lockName, $method ) {
3375 unset( $this->mNamedLocksHeld
[$lockName] );
3380 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3381 if ( $this->writesOrCallbacksPending() ) {
3382 // This only flushes transactions to clear snapshots, not to write data
3383 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3384 throw new DBUnexpectedError(
3386 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
3390 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3394 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3395 if ( $this->trxLevel() ) {
3396 // There is a good chance an exception was thrown, causing any early return
3397 // from the caller. Let any error handler get a chance to issue rollback().
3398 // If there isn't one, let the error bubble up and trigger server-side rollback.
3399 $this->onTransactionResolution(
3400 function () use ( $lockKey, $fname ) {
3401 $this->unlock( $lockKey, $fname );
3406 $this->unlock( $lockKey, $fname );
3410 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3415 public function namedLocksEnqueue() {
3420 * Lock specific tables
3422 * @param array $read Array of tables to lock for read access
3423 * @param array $write Array of tables to lock for write access
3424 * @param string $method Name of caller
3425 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3428 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3433 * Unlock specific tables
3435 * @param string $method The caller
3438 public function unlockTables( $method ) {
3444 * @param string $tableName
3445 * @param string $fName
3446 * @return bool|ResultWrapper
3449 public function dropTable( $tableName, $fName = __METHOD__
) {
3450 if ( !$this->tableExists( $tableName, $fName ) ) {
3453 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3455 return $this->query( $sql, $fName );
3458 public function getInfinity() {
3462 public function encodeExpiry( $expiry ) {
3463 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3464 ?
$this->getInfinity()
3465 : $this->timestamp( $expiry );
3468 public function decodeExpiry( $expiry, $format = TS_MW
) {
3469 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3473 return ConvertibleTimestamp
::convert( $format, $expiry );
3476 public function setBigSelects( $value = true ) {
3480 public function isReadOnly() {
3481 return ( $this->getReadOnlyReason() !== false );
3485 * @return string|bool Reason this DB is read-only or false if it is not
3487 protected function getReadOnlyReason() {
3488 $reason = $this->getLBInfo( 'readOnlyReason' );
3490 return is_string( $reason ) ?
$reason : false;
3493 public function setTableAliases( array $aliases ) {
3494 $this->tableAliases
= $aliases;
3498 * @return bool Whether a DB user is required to access the DB
3501 protected function requiresDatabaseUser() {
3509 public function __toString() {
3510 return (string)$this->mConn
;
3514 * Make sure that copies do not share the same client binding handle
3515 * @throws DBConnectionError
3517 public function __clone() {
3518 $this->connLogger
->warning(
3519 "Cloning " . get_class( $this ) . " is not recomended; forking connection:\n" .
3520 ( new RuntimeException() )->getTraceAsString()
3523 if ( $this->isOpen() ) {
3524 // Open a new connection resource without messing with the old one
3525 $this->mOpened
= false;
3526 $this->mConn
= false;
3527 $this->mTrxEndCallbacks
= []; // don't copy
3528 $this->handleSessionLoss(); // no trx or locks anymore
3529 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3530 $this->lastPing
= microtime( true );
3535 * Called by serialize. Throw an exception when DB connection is serialized.
3536 * This causes problems on some database engines because the connection is
3537 * not restored on unserialize.
3539 public function __sleep() {
3540 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3541 'the connection is not restored on wakeup.' );
3545 * Run a few simple sanity checks and close dangling connections
3547 public function __destruct() {
3548 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3549 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3552 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3553 if ( $danglingWriters ) {
3554 $fnames = implode( ', ', $danglingWriters );
3555 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3558 if ( $this->mConn
) {
3559 // Avoid connection leaks for sanity
3560 $this->closeConnection();
3561 $this->mConn
= false;
3562 $this->mOpened
= false;