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 namespace Wikimedia\Rdbms
;
28 use Psr\Log\LoggerAwareInterface
;
29 use Psr\Log\LoggerInterface
;
30 use Wikimedia\ScopedCallback
;
31 use Wikimedia\Timestamp\ConvertibleTimestamp
;
35 use InvalidArgumentException
;
37 use DBUnexpectedError
;
38 use DBConnectionError
;
44 * Relational database abstraction object
49 abstract class Database
implements IDatabase
, IMaintainableDatabase
, LoggerAwareInterface
{
50 /** Number of times to re-try an operation in case of deadlock */
51 const DEADLOCK_TRIES
= 4;
52 /** Minimum time to wait before retry, in microseconds */
53 const DEADLOCK_DELAY_MIN
= 500000;
54 /** Maximum time to wait before retry */
55 const DEADLOCK_DELAY_MAX
= 1500000;
57 /** How long before it is worth doing a dummy query to test the connection */
59 const PING_QUERY
= 'SELECT 1 AS ping';
61 const TINY_WRITE_SEC
= .010;
62 const SLOW_WRITE_SEC
= .500;
63 const SMALL_WRITE_ROWS
= 100;
65 /** @var string SQL query */
66 protected $mLastQuery = '';
67 /** @var float|bool UNIX timestamp of last write query */
68 protected $mLastWriteTime = false;
69 /** @var string|bool */
70 protected $mPHPError = false;
79 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
80 protected $tableAliases = [];
81 /** @var bool Whether this PHP instance is for a CLI script */
83 /** @var string Agent name for query profiling */
86 /** @var BagOStuff APC cache */
88 /** @var LoggerInterface */
89 protected $connLogger;
90 /** @var LoggerInterface */
91 protected $queryLogger;
92 /** @var callback Error logging callback */
93 protected $errorLogger;
95 /** @var resource|null Database connection */
96 protected $mConn = null;
98 protected $mOpened = false;
100 /** @var array[] List of (callable, method name) */
101 protected $mTrxIdleCallbacks = [];
102 /** @var array[] List of (callable, method name) */
103 protected $mTrxPreCommitCallbacks = [];
104 /** @var array[] List of (callable, method name) */
105 protected $mTrxEndCallbacks = [];
106 /** @var callable[] Map of (name => callable) */
107 protected $mTrxRecurringCallbacks = [];
108 /** @var bool Whether to suppress triggering of transaction end callbacks */
109 protected $mTrxEndCallbacksSuppressed = false;
112 protected $mTablePrefix = '';
114 protected $mSchema = '';
118 protected $mLBInfo = [];
119 /** @var bool|null */
120 protected $mDefaultBigSelects = null;
121 /** @var array|bool */
122 protected $mSchemaVars = false;
124 protected $mSessionVars = [];
125 /** @var array|null */
126 protected $preparedArgs;
127 /** @var string|bool|null Stashed value of html_errors INI setting */
128 protected $htmlErrors;
130 protected $delimiter = ';';
131 /** @var DatabaseDomain */
132 protected $currentDomain;
135 * Either 1 if a transaction is active or 0 otherwise.
136 * The other Trx fields may not be meaningfull if this is 0.
140 protected $mTrxLevel = 0;
142 * Either a short hexidecimal string if a transaction is active or ""
145 * @see Database::mTrxLevel
147 protected $mTrxShortId = '';
149 * The UNIX time that the transaction started. Callers can assume that if
150 * snapshot isolation is used, then the data is *at least* up to date to that
151 * point (possibly more up-to-date since the first SELECT defines the snapshot).
154 * @see Database::mTrxLevel
156 private $mTrxTimestamp = null;
157 /** @var float Lag estimate at the time of BEGIN */
158 private $mTrxReplicaLag = null;
160 * Remembers the function name given for starting the most recent transaction via begin().
161 * Used to provide additional context for error reporting.
164 * @see Database::mTrxLevel
166 private $mTrxFname = null;
168 * Record if possible write queries were done in the last transaction started
171 * @see Database::mTrxLevel
173 private $mTrxDoneWrites = false;
175 * Record if the current transaction was started implicitly due to DBO_TRX being set.
178 * @see Database::mTrxLevel
180 private $mTrxAutomatic = false;
182 * Array of levels of atomicity within transactions
186 private $mTrxAtomicLevels = [];
188 * Record if the current transaction was started implicitly by Database::startAtomic
192 private $mTrxAutomaticAtomic = false;
194 * Track the write query callers of the current transaction
198 private $mTrxWriteCallers = [];
200 * @var float Seconds spent in write queries for the current transaction
202 private $mTrxWriteDuration = 0.0;
204 * @var integer Number of write queries for the current transaction
206 private $mTrxWriteQueryCount = 0;
208 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
210 private $mTrxWriteAdjDuration = 0.0;
212 * @var integer Number of write queries counted in mTrxWriteAdjDuration
214 private $mTrxWriteAdjQueryCount = 0;
216 * @var float RTT time estimate
218 private $mRTTEstimate = 0.0;
220 /** @var array Map of (name => 1) for locks obtained via lock() */
221 private $mNamedLocksHeld = [];
222 /** @var array Map of (table name => 1) for TEMPORARY tables */
223 protected $mSessionTempTables = [];
225 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
226 private $lazyMasterHandle;
228 /** @var float UNIX timestamp */
229 protected $lastPing = 0.0;
231 /** @var int[] Prior mFlags values */
232 private $priorFlags = [];
234 /** @var object|string Class name or object With profileIn/profileOut methods */
236 /** @var TransactionProfiler */
237 protected $trxProfiler;
240 * Constructor and database handle and attempt to connect to the DB server
242 * IDatabase classes should not be constructed directly in external
243 * code. Database::factory() should be used instead.
245 * @param array $params Parameters passed from Database::factory()
247 function __construct( array $params ) {
248 $server = $params['host'];
249 $user = $params['user'];
250 $password = $params['password'];
251 $dbName = $params['dbname'];
253 $this->mSchema
= $params['schema'];
254 $this->mTablePrefix
= $params['tablePrefix'];
256 $this->cliMode
= $params['cliMode'];
257 // Agent name is added to SQL queries in a comment, so make sure it can't break out
258 $this->agent
= str_replace( '/', '-', $params['agent'] );
260 $this->mFlags
= $params['flags'];
261 if ( $this->mFlags
& self
::DBO_DEFAULT
) {
262 if ( $this->cliMode
) {
263 $this->mFlags
&= ~self
::DBO_TRX
;
265 $this->mFlags |
= self
::DBO_TRX
;
269 $this->mSessionVars
= $params['variables'];
271 $this->srvCache
= isset( $params['srvCache'] )
272 ?
$params['srvCache']
273 : new HashBagOStuff();
275 $this->profiler
= $params['profiler'];
276 $this->trxProfiler
= $params['trxProfiler'];
277 $this->connLogger
= $params['connLogger'];
278 $this->queryLogger
= $params['queryLogger'];
279 $this->errorLogger
= $params['errorLogger'];
281 // Set initial dummy domain until open() sets the final DB/prefix
282 $this->currentDomain
= DatabaseDomain
::newUnspecified();
285 $this->open( $server, $user, $password, $dbName );
286 } elseif ( $this->requiresDatabaseUser() ) {
287 throw new InvalidArgumentException( "No database user provided." );
290 // Set the domain object after open() sets the relevant fields
291 if ( $this->mDBname
!= '' ) {
292 // Domains with server scope but a table prefix are not used by IDatabase classes
293 $this->currentDomain
= new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
);
298 * Construct a Database subclass instance given a database type and parameters
300 * This also connects to the database immediately upon object construction
302 * @param string $dbType A possible DB type (sqlite, mysql, postgres)
303 * @param array $p Parameter map with keys:
304 * - host : The hostname of the DB server
305 * - user : The name of the database user the client operates under
306 * - password : The password for the database user
307 * - dbname : The name of the database to use where queries do not specify one.
308 * The database must exist or an error might be thrown. Setting this to the empty string
309 * will avoid any such errors and make the handle have no implicit database scope. This is
310 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
311 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
312 * in which user names and such are defined, e.g. users are database-specific in Postgres.
313 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
314 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
315 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
316 * recognized in queries. This can be used in place of schemas for handle site farms.
317 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
318 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
319 * flag in place UNLESS this this database simply acts as a key/value store.
320 * - driver: Optional name of a specific DB client driver. For MySQL, there is the old
321 * 'mysql' driver and the newer 'mysqli' driver.
322 * - variables: Optional map of session variables to set after connecting. This can be
323 * used to adjust lock timeouts or encoding modes and the like.
324 * - connLogger: Optional PSR-3 logger interface instance.
325 * - queryLogger: Optional PSR-3 logger interface instance.
326 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
327 * These will be called in query(), using a simplified version of the SQL that also
328 * includes the agent as a SQL comment.
329 * - trxProfiler: Optional TransactionProfiler instance.
330 * - errorLogger: Optional callback that takes an Exception and logs it.
331 * - cliMode: Whether to consider the execution context that of a CLI script.
332 * - agent: Optional name used to identify the end-user in query profiling/logging.
333 * - srvCache: Optional BagOStuff instance to an APC-style cache.
334 * @return Database|null If the database driver or extension cannot be found
335 * @throws InvalidArgumentException If the database driver or extension cannot be found
338 final public static function factory( $dbType, $p = [] ) {
339 static $canonicalDBTypes = [
340 'mysql' => [ 'mysqli', 'mysql' ],
346 static $classAliases = [
347 'DatabaseMssql' => DatabaseMssql
::class,
348 'DatabaseMysql' => DatabaseMysql
::class,
349 'DatabaseMysqli' => DatabaseMysqli
::class,
350 'DatabaseSqlite' => DatabaseSqlite
::class,
351 'DatabasePostgres' => DatabasePostgres
::class
355 $dbType = strtolower( $dbType );
356 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
357 $possibleDrivers = $canonicalDBTypes[$dbType];
358 if ( !empty( $p['driver'] ) ) {
359 if ( in_array( $p['driver'], $possibleDrivers ) ) {
360 $driver = $p['driver'];
362 throw new InvalidArgumentException( __METHOD__
.
363 " type '$dbType' does not support driver '{$p['driver']}'" );
366 foreach ( $possibleDrivers as $posDriver ) {
367 if ( extension_loaded( $posDriver ) ) {
368 $driver = $posDriver;
377 if ( $driver === false ||
$driver === '' ) {
378 throw new InvalidArgumentException( __METHOD__
.
379 " no viable database extension found for type '$dbType'" );
382 $class = 'Database' . ucfirst( $driver );
383 if ( isset( $classAliases[$class] ) ) {
384 $class = $classAliases[$class];
387 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
388 // Resolve some defaults for b/c
389 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
390 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
391 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
392 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
393 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
394 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
395 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
396 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
397 $p['cliMode'] = isset( $p['cliMode'] ) ?
$p['cliMode'] : ( PHP_SAPI
=== 'cli' );
398 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
399 if ( !isset( $p['connLogger'] ) ) {
400 $p['connLogger'] = new \Psr\Log\
NullLogger();
402 if ( !isset( $p['queryLogger'] ) ) {
403 $p['queryLogger'] = new \Psr\Log\
NullLogger();
405 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
406 if ( !isset( $p['trxProfiler'] ) ) {
407 $p['trxProfiler'] = new TransactionProfiler();
409 if ( !isset( $p['errorLogger'] ) ) {
410 $p['errorLogger'] = function ( Exception
$e ) {
411 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
415 $conn = new $class( $p );
423 public function setLogger( LoggerInterface
$logger ) {
424 $this->queryLogger
= $logger;
427 public function getServerInfo() {
428 return $this->getServerVersion();
431 public function bufferResults( $buffer = null ) {
432 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
433 if ( $buffer !== null ) {
435 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
436 : $this->setFlag( self
::DBO_NOBUFFER
);
443 * Turns on (false) or off (true) the automatic generation and sending
444 * of a "we're sorry, but there has been a database error" page on
445 * database errors. Default is on (false). When turned off, the
446 * code should use lastErrno() and lastError() to handle the
447 * situation as appropriate.
449 * Do not use this function outside of the Database classes.
451 * @param null|bool $ignoreErrors
452 * @return bool The previous value of the flag.
454 protected function ignoreErrors( $ignoreErrors = null ) {
455 $res = $this->getFlag( self
::DBO_IGNORE
);
456 if ( $ignoreErrors !== null ) {
458 ?
$this->setFlag( self
::DBO_IGNORE
)
459 : $this->clearFlag( self
::DBO_IGNORE
);
465 public function trxLevel() {
466 return $this->mTrxLevel
;
469 public function trxTimestamp() {
470 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
473 public function tablePrefix( $prefix = null ) {
474 $old = $this->mTablePrefix
;
475 if ( $prefix !== null ) {
476 $this->mTablePrefix
= $prefix;
477 $this->currentDomain
= ( $this->mDBname
!= '' )
478 ?
new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
)
479 : DatabaseDomain
::newUnspecified();
485 public function dbSchema( $schema = null ) {
486 $old = $this->mSchema
;
487 if ( $schema !== null ) {
488 $this->mSchema
= $schema;
494 public function getLBInfo( $name = null ) {
495 if ( is_null( $name ) ) {
496 return $this->mLBInfo
;
498 if ( array_key_exists( $name, $this->mLBInfo
) ) {
499 return $this->mLBInfo
[$name];
506 public function setLBInfo( $name, $value = null ) {
507 if ( is_null( $value ) ) {
508 $this->mLBInfo
= $name;
510 $this->mLBInfo
[$name] = $value;
514 public function setLazyMasterHandle( IDatabase
$conn ) {
515 $this->lazyMasterHandle
= $conn;
519 * @return IDatabase|null
520 * @see setLazyMasterHandle()
523 protected function getLazyMasterHandle() {
524 return $this->lazyMasterHandle
;
527 public function implicitGroupby() {
531 public function implicitOrderby() {
535 public function lastQuery() {
536 return $this->mLastQuery
;
539 public function doneWrites() {
540 return (bool)$this->mLastWriteTime
;
543 public function lastDoneWrites() {
544 return $this->mLastWriteTime ?
: false;
547 public function writesPending() {
548 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
551 public function writesOrCallbacksPending() {
552 return $this->mTrxLevel
&& (
553 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
557 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
558 if ( !$this->mTrxLevel
) {
560 } elseif ( !$this->mTrxDoneWrites
) {
565 case self
::ESTIMATE_DB_APPLY
:
567 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
568 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
569 // For omitted queries, make them count as something at least
570 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
571 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
574 default: // everything
575 return $this->mTrxWriteDuration
;
579 public function pendingWriteCallers() {
580 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
583 protected function pendingWriteAndCallbackCallers() {
584 if ( !$this->mTrxLevel
) {
588 $fnames = $this->mTrxWriteCallers
;
590 $this->mTrxIdleCallbacks
,
591 $this->mTrxPreCommitCallbacks
,
592 $this->mTrxEndCallbacks
594 foreach ( $callbacks as $callback ) {
595 $fnames[] = $callback[1];
602 public function isOpen() {
603 return $this->mOpened
;
606 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
607 if ( $remember === self
::REMEMBER_PRIOR
) {
608 array_push( $this->priorFlags
, $this->mFlags
);
610 $this->mFlags |
= $flag;
613 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
614 if ( $remember === self
::REMEMBER_PRIOR
) {
615 array_push( $this->priorFlags
, $this->mFlags
);
617 $this->mFlags
&= ~
$flag;
620 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
621 if ( !$this->priorFlags
) {
625 if ( $state === self
::RESTORE_INITIAL
) {
626 $this->mFlags
= reset( $this->priorFlags
);
627 $this->priorFlags
= [];
629 $this->mFlags
= array_pop( $this->priorFlags
);
633 public function getFlag( $flag ) {
634 return !!( $this->mFlags
& $flag );
638 * @param string $name Class field name
640 * @deprecated Since 1.28
642 public function getProperty( $name ) {
646 public function getDomainID() {
647 return $this->currentDomain
->getId();
650 final public function getWikiID() {
651 return $this->getDomainID();
655 * Get information about an index into an object
656 * @param string $table Table name
657 * @param string $index Index name
658 * @param string $fname Calling function name
659 * @return mixed Database-specific index description class or false if the index does not exist
661 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
664 * Wrapper for addslashes()
666 * @param string $s String to be slashed.
667 * @return string Slashed string.
669 abstract function strencode( $s );
671 protected function installErrorHandler() {
672 $this->mPHPError
= false;
673 $this->htmlErrors
= ini_set( 'html_errors', '0' );
674 set_error_handler( [ $this, 'connectionErrorLogger' ] );
678 * @return bool|string
680 protected function restoreErrorHandler() {
681 restore_error_handler();
682 if ( $this->htmlErrors
!== false ) {
683 ini_set( 'html_errors', $this->htmlErrors
);
686 return $this->getLastPHPError();
690 * @return string|bool Last PHP error for this DB (typically connection errors)
692 protected function getLastPHPError() {
693 if ( $this->mPHPError
) {
694 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
695 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
704 * This method should not be used outside of Database classes
707 * @param string $errstr
709 public function connectionErrorLogger( $errno, $errstr ) {
710 $this->mPHPError
= $errstr;
714 * Create a log context to pass to PSR-3 logger functions.
716 * @param array $extras Additional data to add to context
719 protected function getLogContext( array $extras = [] ) {
722 'db_server' => $this->mServer
,
723 'db_name' => $this->mDBname
,
724 'db_user' => $this->mUser
,
730 public function close() {
731 if ( $this->mConn
) {
732 if ( $this->trxLevel() ) {
733 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
736 $closed = $this->closeConnection();
737 $this->mConn
= false;
738 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
739 throw new RuntimeException( "Transaction callbacks still pending." );
743 $this->mOpened
= false;
749 * Make sure isOpen() returns true as a sanity check
751 * @throws DBUnexpectedError
753 protected function assertOpen() {
754 if ( !$this->isOpen() ) {
755 throw new DBUnexpectedError( $this, "DB connection was already closed." );
760 * Closes underlying database connection
762 * @return bool Whether connection was closed successfully
764 abstract protected function closeConnection();
766 public function reportConnectionError( $error = 'Unknown error' ) {
767 $myError = $this->lastError();
773 throw new DBConnectionError( $this, $error );
777 * The DBMS-dependent part of query()
779 * @param string $sql SQL query.
780 * @return ResultWrapper|bool Result object to feed to fetchObject,
781 * fetchRow, ...; or false on failure
783 abstract protected function doQuery( $sql );
786 * Determine whether a query writes to the DB.
787 * Should return true if unsure.
792 protected function isWriteQuery( $sql ) {
794 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
799 * @return string|null
801 protected function getQueryVerb( $sql ) {
802 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
806 * Determine whether a SQL statement is sensitive to isolation level.
807 * A SQL statement is considered transactable if its result could vary
808 * depending on the transaction isolation level. Operational commands
809 * such as 'SET' and 'SHOW' are not considered to be transactable.
814 protected function isTransactableQuery( $sql ) {
816 $this->getQueryVerb( $sql ),
817 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
823 * @param string $sql A SQL query
824 * @return bool Whether $sql is SQL for creating/dropping a new TEMPORARY table
826 protected function registerTempTableOperation( $sql ) {
828 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
832 $this->mSessionTempTables
[$matches[1]] = 1;
835 } elseif ( preg_match(
836 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
840 unset( $this->mSessionTempTables
[$matches[1]] );
843 } elseif ( preg_match(
844 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
848 return isset( $this->mSessionTempTables
[$matches[1]] );
854 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
855 $priorWritesPending = $this->writesOrCallbacksPending();
856 $this->mLastQuery
= $sql;
858 $isWrite = $this->isWriteQuery( $sql ) && !$this->registerTempTableOperation( $sql );
860 $reason = $this->getReadOnlyReason();
861 if ( $reason !== false ) {
862 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
864 # Set a flag indicating that writes have been done
865 $this->mLastWriteTime
= microtime( true );
868 // Add trace comment to the begin of the sql string, right after the operator.
869 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
870 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
872 # Start implicit transactions that wrap the request if DBO_TRX is enabled
873 if ( !$this->mTrxLevel
&& $this->getFlag( self
::DBO_TRX
)
874 && $this->isTransactableQuery( $sql )
876 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
877 $this->mTrxAutomatic
= true;
880 # Keep track of whether the transaction has write queries pending
881 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
882 $this->mTrxDoneWrites
= true;
883 $this->trxProfiler
->transactionWritingIn(
884 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
887 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
888 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
891 # Avoid fatals if close() was called
894 # Send the query to the server
895 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
897 # Try reconnecting if the connection was lost
898 if ( false === $ret && $this->wasErrorReissuable() ) {
899 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
900 # Stash the last error values before anything might clear them
901 $lastError = $this->lastError();
902 $lastErrno = $this->lastErrno();
903 # Update state tracking to reflect transaction loss due to disconnection
904 $this->handleSessionLoss();
905 if ( $this->reconnect() ) {
906 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
907 $this->connLogger
->warning( $msg );
908 $this->queryLogger
->warning(
909 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
911 if ( !$recoverable ) {
912 # Callers may catch the exception and continue to use the DB
913 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
915 # Should be safe to silently retry the query
916 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
919 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
920 $this->connLogger
->error( $msg );
924 if ( false === $ret ) {
925 # Deadlocks cause the entire transaction to abort, not just the statement.
926 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
927 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
928 if ( $this->wasDeadlock() ) {
929 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
930 $tempIgnore = false; // not recoverable
932 # Update state tracking to reflect transaction loss
933 $this->handleSessionLoss();
936 $this->reportQueryError(
937 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
940 $res = $this->resultObject( $ret );
945 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
946 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
947 # generalizeSQL() will probably cut down the query to reasonable
948 # logging size most of the time. The substr is really just a sanity check.
950 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
952 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
955 # Include query transaction state
956 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
958 $startTime = microtime( true );
959 if ( $this->profiler
) {
960 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
962 $ret = $this->doQuery( $commentedSql );
963 if ( $this->profiler
) {
964 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
966 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
968 unset( $queryProfSection ); // profile out (if set)
970 if ( $ret !== false ) {
971 $this->lastPing
= $startTime;
972 if ( $isWrite && $this->mTrxLevel
) {
973 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
974 $this->mTrxWriteCallers
[] = $fname;
978 if ( $sql === self
::PING_QUERY
) {
979 $this->mRTTEstimate
= $queryRuntime;
982 $this->trxProfiler
->recordQueryCompletion(
983 $queryProf, $startTime, $isWrite, $this->affectedRows()
985 $this->queryLogger
->debug( $sql, [
987 'master' => $isMaster,
988 'runtime' => $queryRuntime,
995 * Update the estimated run-time of a query, not counting large row lock times
997 * LoadBalancer can be set to rollback transactions that will create huge replication
998 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
999 * queries, like inserting a row can take a long time due to row locking. This method
1000 * uses some simple heuristics to discount those cases.
1002 * @param string $sql A SQL write query
1003 * @param float $runtime Total runtime, including RTT
1005 private function updateTrxWriteQueryTime( $sql, $runtime ) {
1006 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1007 $indicativeOfReplicaRuntime = true;
1008 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1009 $verb = $this->getQueryVerb( $sql );
1010 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1011 if ( $verb === 'INSERT' ) {
1012 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1013 } elseif ( $verb === 'REPLACE' ) {
1014 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1018 $this->mTrxWriteDuration +
= $runtime;
1019 $this->mTrxWriteQueryCount +
= 1;
1020 if ( $indicativeOfReplicaRuntime ) {
1021 $this->mTrxWriteAdjDuration +
= $runtime;
1022 $this->mTrxWriteAdjQueryCount +
= 1;
1026 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1027 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1028 # Dropped connections also mean that named locks are automatically released.
1029 # Only allow error suppression in autocommit mode or when the lost transaction
1030 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1031 if ( $this->mNamedLocksHeld
) {
1032 return false; // possible critical section violation
1033 } elseif ( $sql === 'COMMIT' ) {
1034 return !$priorWritesPending; // nothing written anyway? (T127428)
1035 } elseif ( $sql === 'ROLLBACK' ) {
1036 return true; // transaction lost...which is also what was requested :)
1037 } elseif ( $this->explicitTrxActive() ) {
1038 return false; // don't drop atomocity
1039 } elseif ( $priorWritesPending ) {
1040 return false; // prior writes lost from implicit transaction
1046 private function handleSessionLoss() {
1047 $this->mTrxLevel
= 0;
1048 $this->mTrxIdleCallbacks
= []; // T67263
1049 $this->mTrxPreCommitCallbacks
= []; // T67263
1050 $this->mSessionTempTables
= [];
1051 $this->mNamedLocksHeld
= [];
1053 // Handle callbacks in mTrxEndCallbacks
1054 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1055 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1057 } catch ( Exception
$e ) {
1058 // Already logged; move on...
1063 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1064 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1065 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1067 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1068 $this->queryLogger
->error(
1069 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1070 $this->getLogContext( [
1071 'method' => __METHOD__
,
1074 'sql1line' => $sql1line,
1078 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1079 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1083 public function freeResult( $res ) {
1086 public function selectField(
1087 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1089 if ( $var === '*' ) { // sanity
1090 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1093 if ( !is_array( $options ) ) {
1094 $options = [ $options ];
1097 $options['LIMIT'] = 1;
1099 $res = $this->select( $table, $var, $cond, $fname, $options );
1100 if ( $res === false ||
!$this->numRows( $res ) ) {
1104 $row = $this->fetchRow( $res );
1106 if ( $row !== false ) {
1107 return reset( $row );
1113 public function selectFieldValues(
1114 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1116 if ( $var === '*' ) { // sanity
1117 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1118 } elseif ( !is_string( $var ) ) { // sanity
1119 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1122 if ( !is_array( $options ) ) {
1123 $options = [ $options ];
1126 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1127 if ( $res === false ) {
1132 foreach ( $res as $row ) {
1133 $values[] = $row->$var;
1140 * Returns an optional USE INDEX clause to go after the table, and a
1141 * string to go at the end of the query.
1143 * @param array $options Associative array of options to be turned into
1144 * an SQL query, valid keys are listed in the function.
1146 * @see Database::select()
1148 protected function makeSelectOptions( $options ) {
1149 $preLimitTail = $postLimitTail = '';
1154 foreach ( $options as $key => $option ) {
1155 if ( is_numeric( $key ) ) {
1156 $noKeyOptions[$option] = true;
1160 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1162 $preLimitTail .= $this->makeOrderBy( $options );
1164 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1165 $postLimitTail .= ' FOR UPDATE';
1168 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1169 $postLimitTail .= ' LOCK IN SHARE MODE';
1172 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1173 $startOpts .= 'DISTINCT';
1176 # Various MySQL extensions
1177 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1178 $startOpts .= ' /*! STRAIGHT_JOIN */';
1181 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1182 $startOpts .= ' HIGH_PRIORITY';
1185 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1186 $startOpts .= ' SQL_BIG_RESULT';
1189 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1190 $startOpts .= ' SQL_BUFFER_RESULT';
1193 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1194 $startOpts .= ' SQL_SMALL_RESULT';
1197 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1198 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1201 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1202 $startOpts .= ' SQL_CACHE';
1205 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1206 $startOpts .= ' SQL_NO_CACHE';
1209 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1210 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1214 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1215 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1220 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1224 * Returns an optional GROUP BY with an optional HAVING
1226 * @param array $options Associative array of options
1228 * @see Database::select()
1231 protected function makeGroupByWithHaving( $options ) {
1233 if ( isset( $options['GROUP BY'] ) ) {
1234 $gb = is_array( $options['GROUP BY'] )
1235 ?
implode( ',', $options['GROUP BY'] )
1236 : $options['GROUP BY'];
1237 $sql .= ' GROUP BY ' . $gb;
1239 if ( isset( $options['HAVING'] ) ) {
1240 $having = is_array( $options['HAVING'] )
1241 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1242 : $options['HAVING'];
1243 $sql .= ' HAVING ' . $having;
1250 * Returns an optional ORDER BY
1252 * @param array $options Associative array of options
1254 * @see Database::select()
1257 protected function makeOrderBy( $options ) {
1258 if ( isset( $options['ORDER BY'] ) ) {
1259 $ob = is_array( $options['ORDER BY'] )
1260 ?
implode( ',', $options['ORDER BY'] )
1261 : $options['ORDER BY'];
1263 return ' ORDER BY ' . $ob;
1269 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1270 $options = [], $join_conds = [] ) {
1271 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1273 return $this->query( $sql, $fname );
1276 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1277 $options = [], $join_conds = []
1279 if ( is_array( $vars ) ) {
1280 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1283 $options = (array)$options;
1284 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1285 ?
$options['USE INDEX']
1288 isset( $options['IGNORE INDEX'] ) &&
1289 is_array( $options['IGNORE INDEX'] )
1291 ?
$options['IGNORE INDEX']
1294 if ( is_array( $table ) ) {
1296 $this->tableNamesWithIndexClauseOrJOIN(
1297 $table, $useIndexes, $ignoreIndexes, $join_conds );
1298 } elseif ( $table != '' ) {
1299 if ( $table[0] == ' ' ) {
1300 $from = ' FROM ' . $table;
1303 $this->tableNamesWithIndexClauseOrJOIN(
1304 [ $table ], $useIndexes, $ignoreIndexes, [] );
1310 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1311 $this->makeSelectOptions( $options );
1313 if ( !empty( $conds ) ) {
1314 if ( is_array( $conds ) ) {
1315 $conds = $this->makeList( $conds, self
::LIST_AND
);
1317 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1318 "WHERE $conds $preLimitTail";
1320 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1323 if ( isset( $options['LIMIT'] ) ) {
1324 $sql = $this->limitResult( $sql, $options['LIMIT'],
1325 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1327 $sql = "$sql $postLimitTail";
1329 if ( isset( $options['EXPLAIN'] ) ) {
1330 $sql = 'EXPLAIN ' . $sql;
1336 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1337 $options = [], $join_conds = []
1339 $options = (array)$options;
1340 $options['LIMIT'] = 1;
1341 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1343 if ( $res === false ) {
1347 if ( !$this->numRows( $res ) ) {
1351 $obj = $this->fetchObject( $res );
1356 public function estimateRowCount(
1357 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1360 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1363 $row = $this->fetchRow( $res );
1364 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1370 public function selectRowCount(
1371 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1374 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1375 // The identifier quotes is primarily for MSSQL.
1376 $rowCountCol = $this->addIdentifierQuotes( "rowcount" );
1377 $tableName = $this->addIdentifierQuotes( "tmp_count" );
1378 $res = $this->query( "SELECT COUNT(*) AS $rowCountCol FROM ($sql) $tableName", $fname );
1381 $row = $this->fetchRow( $res );
1382 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1389 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1390 * It's only slightly flawed. Don't use for anything important.
1392 * @param string $sql A SQL Query
1396 protected static function generalizeSQL( $sql ) {
1397 # This does the same as the regexp below would do, but in such a way
1398 # as to avoid crashing php on some large strings.
1399 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1401 $sql = str_replace( "\\\\", '', $sql );
1402 $sql = str_replace( "\\'", '', $sql );
1403 $sql = str_replace( "\\\"", '', $sql );
1404 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1405 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1407 # All newlines, tabs, etc replaced by single space
1408 $sql = preg_replace( '/\s+/', ' ', $sql );
1411 # except the ones surrounded by characters, e.g. l10n
1412 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1413 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1418 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1419 $info = $this->fieldInfo( $table, $field );
1424 public function indexExists( $table, $index, $fname = __METHOD__
) {
1425 if ( !$this->tableExists( $table ) ) {
1429 $info = $this->indexInfo( $table, $index, $fname );
1430 if ( is_null( $info ) ) {
1433 return $info !== false;
1437 public function tableExists( $table, $fname = __METHOD__
) {
1438 $tableRaw = $this->tableName( $table, 'raw' );
1439 if ( isset( $this->mSessionTempTables
[$tableRaw] ) ) {
1440 return true; // already known to exist
1443 $table = $this->tableName( $table );
1444 $ignoreErrors = true;
1445 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1450 public function indexUnique( $table, $index ) {
1451 $indexInfo = $this->indexInfo( $table, $index );
1453 if ( !$indexInfo ) {
1457 return !$indexInfo[0]->Non_unique
;
1461 * Helper for Database::insert().
1463 * @param array $options
1466 protected function makeInsertOptions( $options ) {
1467 return implode( ' ', $options );
1470 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1471 # No rows to insert, easy just return now
1472 if ( !count( $a ) ) {
1476 $table = $this->tableName( $table );
1478 if ( !is_array( $options ) ) {
1479 $options = [ $options ];
1483 if ( isset( $options['fileHandle'] ) ) {
1484 $fh = $options['fileHandle'];
1486 $options = $this->makeInsertOptions( $options );
1488 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1490 $keys = array_keys( $a[0] );
1493 $keys = array_keys( $a );
1496 $sql = 'INSERT ' . $options .
1497 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1501 foreach ( $a as $row ) {
1507 $sql .= '(' . $this->makeList( $row ) . ')';
1510 $sql .= '(' . $this->makeList( $a ) . ')';
1513 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1515 } elseif ( $fh !== null ) {
1519 return (bool)$this->query( $sql, $fname );
1523 * Make UPDATE options array for Database::makeUpdateOptions
1525 * @param array $options
1528 protected function makeUpdateOptionsArray( $options ) {
1529 if ( !is_array( $options ) ) {
1530 $options = [ $options ];
1535 if ( in_array( 'IGNORE', $options ) ) {
1543 * Make UPDATE options for the Database::update function
1545 * @param array $options The options passed to Database::update
1548 protected function makeUpdateOptions( $options ) {
1549 $opts = $this->makeUpdateOptionsArray( $options );
1551 return implode( ' ', $opts );
1554 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1555 $table = $this->tableName( $table );
1556 $opts = $this->makeUpdateOptions( $options );
1557 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1559 if ( $conds !== [] && $conds !== '*' ) {
1560 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1563 return (bool)$this->query( $sql, $fname );
1566 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1567 if ( !is_array( $a ) ) {
1568 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1574 foreach ( $a as $field => $value ) {
1576 if ( $mode == self
::LIST_AND
) {
1578 } elseif ( $mode == self
::LIST_OR
) {
1587 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1588 $list .= "($value)";
1589 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1592 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1594 // Remove null from array to be handled separately if found
1595 $includeNull = false;
1596 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1597 $includeNull = true;
1598 unset( $value[$nullKey] );
1600 if ( count( $value ) == 0 && !$includeNull ) {
1601 throw new InvalidArgumentException(
1602 __METHOD__
. ": empty input for field $field" );
1603 } elseif ( count( $value ) == 0 ) {
1604 // only check if $field is null
1605 $list .= "$field IS NULL";
1607 // IN clause contains at least one valid element
1608 if ( $includeNull ) {
1609 // Group subconditions to ensure correct precedence
1612 if ( count( $value ) == 1 ) {
1613 // Special-case single values, as IN isn't terribly efficient
1614 // Don't necessarily assume the single key is 0; we don't
1615 // enforce linear numeric ordering on other arrays here.
1616 $value = array_values( $value )[0];
1617 $list .= $field . " = " . $this->addQuotes( $value );
1619 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1621 // if null present in array, append IS NULL
1622 if ( $includeNull ) {
1623 $list .= " OR $field IS NULL)";
1626 } elseif ( $value === null ) {
1627 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1628 $list .= "$field IS ";
1629 } elseif ( $mode == self
::LIST_SET
) {
1630 $list .= "$field = ";
1635 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1637 $list .= "$field = ";
1639 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1646 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1649 foreach ( $data as $base => $sub ) {
1650 if ( count( $sub ) ) {
1651 $conds[] = $this->makeList(
1652 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1658 return $this->makeList( $conds, self
::LIST_OR
);
1660 // Nothing to search for...
1665 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1669 public function bitNot( $field ) {
1673 public function bitAnd( $fieldLeft, $fieldRight ) {
1674 return "($fieldLeft & $fieldRight)";
1677 public function bitOr( $fieldLeft, $fieldRight ) {
1678 return "($fieldLeft | $fieldRight)";
1681 public function buildConcat( $stringList ) {
1682 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1685 public function buildGroupConcatField(
1686 $delim, $table, $field, $conds = '', $join_conds = []
1688 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1690 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1693 public function buildStringCast( $field ) {
1697 public function selectDB( $db ) {
1698 # Stub. Shouldn't cause serious problems if it's not overridden, but
1699 # if your database engine supports a concept similar to MySQL's
1700 # databases you may as well.
1701 $this->mDBname
= $db;
1706 public function getDBname() {
1707 return $this->mDBname
;
1710 public function getServer() {
1711 return $this->mServer
;
1714 public function tableName( $name, $format = 'quoted' ) {
1715 # Skip the entire process when we have a string quoted on both ends.
1716 # Note that we check the end so that we will still quote any use of
1717 # use of `database`.table. But won't break things if someone wants
1718 # to query a database table with a dot in the name.
1719 if ( $this->isQuotedIdentifier( $name ) ) {
1723 # Lets test for any bits of text that should never show up in a table
1724 # name. Basically anything like JOIN or ON which are actually part of
1725 # SQL queries, but may end up inside of the table value to combine
1726 # sql. Such as how the API is doing.
1727 # Note that we use a whitespace test rather than a \b test to avoid
1728 # any remote case where a word like on may be inside of a table name
1729 # surrounded by symbols which may be considered word breaks.
1730 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1734 # Split database and table into proper variables.
1735 # We reverse the explode so that database.table and table both output
1736 # the correct table.
1737 $dbDetails = explode( '.', $name, 3 );
1738 if ( count( $dbDetails ) == 3 ) {
1739 list( $database, $schema, $table ) = $dbDetails;
1740 # We don't want any prefix added in this case
1742 } elseif ( count( $dbDetails ) == 2 ) {
1743 list( $database, $table ) = $dbDetails;
1744 # We don't want any prefix added in this case
1746 # In dbs that support it, $database may actually be the schema
1747 # but that doesn't affect any of the functionality here
1750 list( $table ) = $dbDetails;
1751 if ( isset( $this->tableAliases
[$table] ) ) {
1752 $database = $this->tableAliases
[$table]['dbname'];
1753 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1754 ?
$this->tableAliases
[$table]['schema']
1756 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1757 ?
$this->tableAliases
[$table]['prefix']
1758 : $this->mTablePrefix
;
1761 $schema = $this->mSchema
; # Default schema
1762 $prefix = $this->mTablePrefix
; # Default prefix
1766 # Quote $table and apply the prefix if not quoted.
1767 # $tableName might be empty if this is called from Database::replaceVars()
1768 $tableName = "{$prefix}{$table}";
1769 if ( $format === 'quoted'
1770 && !$this->isQuotedIdentifier( $tableName )
1771 && $tableName !== ''
1773 $tableName = $this->addIdentifierQuotes( $tableName );
1776 # Quote $schema and $database and merge them with the table name if needed
1777 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1778 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1784 * @param string|null $namespace Database or schema
1785 * @param string $relation Name of table, view, sequence, etc...
1786 * @param string $format One of (raw, quoted)
1787 * @return string Relation name with quoted and merged $namespace as needed
1789 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
1790 if ( strlen( $namespace ) ) {
1791 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
1792 $namespace = $this->addIdentifierQuotes( $namespace );
1794 $relation = $namespace . '.' . $relation;
1800 public function tableNames() {
1801 $inArray = func_get_args();
1804 foreach ( $inArray as $name ) {
1805 $retVal[$name] = $this->tableName( $name );
1811 public function tableNamesN() {
1812 $inArray = func_get_args();
1815 foreach ( $inArray as $name ) {
1816 $retVal[] = $this->tableName( $name );
1823 * Get an aliased table name
1824 * e.g. tableName AS newTableName
1826 * @param string $name Table name, see tableName()
1827 * @param string|bool $alias Alias (optional)
1828 * @return string SQL name for aliased table. Will not alias a table to its own name
1830 protected function tableNameWithAlias( $name, $alias = false ) {
1831 if ( !$alias ||
$alias == $name ) {
1832 return $this->tableName( $name );
1834 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1839 * Gets an array of aliased table names
1841 * @param array $tables [ [alias] => table ]
1842 * @return string[] See tableNameWithAlias()
1844 protected function tableNamesWithAlias( $tables ) {
1846 foreach ( $tables as $alias => $table ) {
1847 if ( is_numeric( $alias ) ) {
1850 $retval[] = $this->tableNameWithAlias( $table, $alias );
1857 * Get an aliased field name
1858 * e.g. fieldName AS newFieldName
1860 * @param string $name Field name
1861 * @param string|bool $alias Alias (optional)
1862 * @return string SQL name for aliased field. Will not alias a field to its own name
1864 protected function fieldNameWithAlias( $name, $alias = false ) {
1865 if ( !$alias ||
(string)$alias === (string)$name ) {
1868 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1873 * Gets an array of aliased field names
1875 * @param array $fields [ [alias] => field ]
1876 * @return string[] See fieldNameWithAlias()
1878 protected function fieldNamesWithAlias( $fields ) {
1880 foreach ( $fields as $alias => $field ) {
1881 if ( is_numeric( $alias ) ) {
1884 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1891 * Get the aliased table name clause for a FROM clause
1892 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
1894 * @param array $tables ( [alias] => table )
1895 * @param array $use_index Same as for select()
1896 * @param array $ignore_index Same as for select()
1897 * @param array $join_conds Same as for select()
1900 protected function tableNamesWithIndexClauseOrJOIN(
1901 $tables, $use_index = [], $ignore_index = [], $join_conds = []
1905 $use_index = (array)$use_index;
1906 $ignore_index = (array)$ignore_index;
1907 $join_conds = (array)$join_conds;
1909 foreach ( $tables as $alias => $table ) {
1910 if ( !is_string( $alias ) ) {
1911 // No alias? Set it equal to the table name
1914 // Is there a JOIN clause for this table?
1915 if ( isset( $join_conds[$alias] ) ) {
1916 list( $joinType, $conds ) = $join_conds[$alias];
1917 $tableClause = $joinType;
1918 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1919 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1920 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1922 $tableClause .= ' ' . $use;
1925 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
1926 $ignore = $this->ignoreIndexClause(
1927 implode( ',', (array)$ignore_index[$alias] ) );
1928 if ( $ignore != '' ) {
1929 $tableClause .= ' ' . $ignore;
1932 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
1934 $tableClause .= ' ON (' . $on . ')';
1937 $retJOIN[] = $tableClause;
1938 } elseif ( isset( $use_index[$alias] ) ) {
1939 // Is there an INDEX clause for this table?
1940 $tableClause = $this->tableNameWithAlias( $table, $alias );
1941 $tableClause .= ' ' . $this->useIndexClause(
1942 implode( ',', (array)$use_index[$alias] )
1945 $ret[] = $tableClause;
1946 } elseif ( isset( $ignore_index[$alias] ) ) {
1947 // Is there an INDEX clause for this table?
1948 $tableClause = $this->tableNameWithAlias( $table, $alias );
1949 $tableClause .= ' ' . $this->ignoreIndexClause(
1950 implode( ',', (array)$ignore_index[$alias] )
1953 $ret[] = $tableClause;
1955 $tableClause = $this->tableNameWithAlias( $table, $alias );
1957 $ret[] = $tableClause;
1961 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1962 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1963 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1965 // Compile our final table clause
1966 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
1970 * Allows for index remapping in queries where this is not consistent across DBMS
1972 * @param string $index
1975 protected function indexName( $index ) {
1979 public function addQuotes( $s ) {
1980 if ( $s instanceof Blob
) {
1983 if ( $s === null ) {
1985 } elseif ( is_bool( $s ) ) {
1988 # This will also quote numeric values. This should be harmless,
1989 # and protects against weird problems that occur when they really
1990 # _are_ strings such as article titles and string->number->string
1991 # conversion is not 1:1.
1992 return "'" . $this->strencode( $s ) . "'";
1997 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1998 * MySQL uses `backticks` while basically everything else uses double quotes.
1999 * Since MySQL is the odd one out here the double quotes are our generic
2000 * and we implement backticks in DatabaseMysql.
2005 public function addIdentifierQuotes( $s ) {
2006 return '"' . str_replace( '"', '""', $s ) . '"';
2010 * Returns if the given identifier looks quoted or not according to
2011 * the database convention for quoting identifiers .
2013 * @note Do not use this to determine if untrusted input is safe.
2014 * A malicious user can trick this function.
2015 * @param string $name
2018 public function isQuotedIdentifier( $name ) {
2019 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2026 protected function escapeLikeInternal( $s ) {
2027 return addcslashes( $s, '\%_' );
2030 public function buildLike() {
2031 $params = func_get_args();
2033 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2034 $params = $params[0];
2039 foreach ( $params as $value ) {
2040 if ( $value instanceof LikeMatch
) {
2041 $s .= $value->toString();
2043 $s .= $this->escapeLikeInternal( $value );
2047 return " LIKE {$this->addQuotes( $s )} ";
2050 public function anyChar() {
2051 return new LikeMatch( '_' );
2054 public function anyString() {
2055 return new LikeMatch( '%' );
2058 public function nextSequenceValue( $seqName ) {
2063 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2064 * is only needed because a) MySQL must be as efficient as possible due to
2065 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2066 * which index to pick. Anyway, other databases might have different
2067 * indexes on a given table. So don't bother overriding this unless you're
2069 * @param string $index
2072 public function useIndexClause( $index ) {
2077 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2078 * is only needed because a) MySQL must be as efficient as possible due to
2079 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2080 * which index to pick. Anyway, other databases might have different
2081 * indexes on a given table. So don't bother overriding this unless you're
2083 * @param string $index
2086 public function ignoreIndexClause( $index ) {
2090 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2091 $quotedTable = $this->tableName( $table );
2093 if ( count( $rows ) == 0 ) {
2098 if ( !is_array( reset( $rows ) ) ) {
2102 // @FXIME: this is not atomic, but a trx would break affectedRows()
2103 foreach ( $rows as $row ) {
2104 # Delete rows which collide
2105 if ( $uniqueIndexes ) {
2106 $sql = "DELETE FROM $quotedTable WHERE ";
2108 foreach ( $uniqueIndexes as $index ) {
2115 if ( is_array( $index ) ) {
2117 foreach ( $index as $col ) {
2123 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2126 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2130 $this->query( $sql, $fname );
2133 # Now insert the row
2134 $this->insert( $table, $row, $fname );
2139 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2142 * @param string $table Table name
2143 * @param array|string $rows Row(s) to insert
2144 * @param string $fname Caller function name
2146 * @return ResultWrapper
2148 protected function nativeReplace( $table, $rows, $fname ) {
2149 $table = $this->tableName( $table );
2152 if ( !is_array( reset( $rows ) ) ) {
2156 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2159 foreach ( $rows as $row ) {
2166 $sql .= '(' . $this->makeList( $row ) . ')';
2169 return $this->query( $sql, $fname );
2172 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2175 if ( !count( $rows ) ) {
2176 return true; // nothing to do
2179 if ( !is_array( reset( $rows ) ) ) {
2183 if ( count( $uniqueIndexes ) ) {
2184 $clauses = []; // list WHERE clauses that each identify a single row
2185 foreach ( $rows as $row ) {
2186 foreach ( $uniqueIndexes as $index ) {
2187 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2188 $rowKey = []; // unique key to this row
2189 foreach ( $index as $column ) {
2190 $rowKey[$column] = $row[$column];
2192 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2195 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2200 $useTrx = !$this->mTrxLevel
;
2202 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2205 # Update any existing conflicting row(s)
2206 if ( $where !== false ) {
2207 $ok = $this->update( $table, $set, $where, $fname );
2211 # Now insert any non-conflicting row(s)
2212 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2213 } catch ( Exception
$e ) {
2215 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2220 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2226 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2230 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2233 $delTable = $this->tableName( $delTable );
2234 $joinTable = $this->tableName( $joinTable );
2235 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2236 if ( $conds != '*' ) {
2237 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2241 $this->query( $sql, $fname );
2244 public function textFieldSize( $table, $field ) {
2245 $table = $this->tableName( $table );
2246 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2247 $res = $this->query( $sql, __METHOD__
);
2248 $row = $this->fetchObject( $res );
2252 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2261 public function delete( $table, $conds, $fname = __METHOD__
) {
2263 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2266 $table = $this->tableName( $table );
2267 $sql = "DELETE FROM $table";
2269 if ( $conds != '*' ) {
2270 if ( is_array( $conds ) ) {
2271 $conds = $this->makeList( $conds, self
::LIST_AND
);
2273 $sql .= ' WHERE ' . $conds;
2276 return $this->query( $sql, $fname );
2279 public function insertSelect(
2280 $destTable, $srcTable, $varMap, $conds,
2281 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2283 if ( $this->cliMode
) {
2284 // For massive migrations with downtime, we don't want to select everything
2285 // into memory and OOM, so do all this native on the server side if possible.
2286 return $this->nativeInsertSelect(
2297 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2298 // on only the master (without needing row-based-replication). It also makes it easy to
2299 // know how big the INSERT is going to be.
2301 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2302 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2304 $selectOptions[] = 'FOR UPDATE';
2305 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2311 foreach ( $res as $row ) {
2312 $rows[] = (array)$row;
2315 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2318 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2319 $fname = __METHOD__
,
2320 $insertOptions = [], $selectOptions = []
2322 $destTable = $this->tableName( $destTable );
2324 if ( !is_array( $insertOptions ) ) {
2325 $insertOptions = [ $insertOptions ];
2328 $insertOptions = $this->makeInsertOptions( $insertOptions );
2330 if ( !is_array( $selectOptions ) ) {
2331 $selectOptions = [ $selectOptions ];
2334 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2337 if ( is_array( $srcTable ) ) {
2338 $srcTable = implode( ',', array_map( [ $this, 'tableName' ], $srcTable ) );
2340 $srcTable = $this->tableName( $srcTable );
2343 $sql = "INSERT $insertOptions" .
2344 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2345 " SELECT $startOpts " . implode( ',', $varMap ) .
2346 " FROM $srcTable $useIndex $ignoreIndex ";
2348 if ( $conds != '*' ) {
2349 if ( is_array( $conds ) ) {
2350 $conds = $this->makeList( $conds, self
::LIST_AND
);
2352 $sql .= " WHERE $conds";
2355 $sql .= " $tailOpts";
2357 return $this->query( $sql, $fname );
2361 * Construct a LIMIT query with optional offset. This is used for query
2362 * pages. The SQL should be adjusted so that only the first $limit rows
2363 * are returned. If $offset is provided as well, then the first $offset
2364 * rows should be discarded, and the next $limit rows should be returned.
2365 * If the result of the query is not ordered, then the rows to be returned
2366 * are theoretically arbitrary.
2368 * $sql is expected to be a SELECT, if that makes a difference.
2370 * The version provided by default works in MySQL and SQLite. It will very
2371 * likely need to be overridden for most other DBMSes.
2373 * @param string $sql SQL query we will append the limit too
2374 * @param int $limit The SQL limit
2375 * @param int|bool $offset The SQL offset (default false)
2376 * @throws DBUnexpectedError
2379 public function limitResult( $sql, $limit, $offset = false ) {
2380 if ( !is_numeric( $limit ) ) {
2381 throw new DBUnexpectedError( $this,
2382 "Invalid non-numeric limit passed to limitResult()\n" );
2385 return "$sql LIMIT "
2386 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2390 public function unionSupportsOrderAndLimit() {
2391 return true; // True for almost every DB supported
2394 public function unionQueries( $sqls, $all ) {
2395 $glue = $all ?
') UNION ALL (' : ') UNION (';
2397 return '(' . implode( $glue, $sqls ) . ')';
2400 public function conditional( $cond, $trueVal, $falseVal ) {
2401 if ( is_array( $cond ) ) {
2402 $cond = $this->makeList( $cond, self
::LIST_AND
);
2405 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2408 public function strreplace( $orig, $old, $new ) {
2409 return "REPLACE({$orig}, {$old}, {$new})";
2412 public function getServerUptime() {
2416 public function wasDeadlock() {
2420 public function wasLockTimeout() {
2424 public function wasErrorReissuable() {
2428 public function wasReadOnlyError() {
2433 * Do not use this method outside of Database/DBError classes
2435 * @param integer|string $errno
2436 * @return bool Whether the given query error was a connection drop
2438 public function wasConnectionError( $errno ) {
2442 public function deadlockLoop() {
2443 $args = func_get_args();
2444 $function = array_shift( $args );
2445 $tries = self
::DEADLOCK_TRIES
;
2447 $this->begin( __METHOD__
);
2450 /** @var Exception $e */
2454 $retVal = call_user_func_array( $function, $args );
2456 } catch ( DBQueryError
$e ) {
2457 if ( $this->wasDeadlock() ) {
2458 // Retry after a randomized delay
2459 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2461 // Throw the error back up
2465 } while ( --$tries > 0 );
2467 if ( $tries <= 0 ) {
2468 // Too many deadlocks; give up
2469 $this->rollback( __METHOD__
);
2472 $this->commit( __METHOD__
);
2478 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2479 # Real waits are implemented in the subclass.
2483 public function getReplicaPos() {
2488 public function getMasterPos() {
2493 public function serverIsReadOnly() {
2497 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2498 if ( !$this->mTrxLevel
) {
2499 throw new DBUnexpectedError( $this, "No transaction is active." );
2501 $this->mTrxEndCallbacks
[] = [ $callback, $fname ];
2504 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2505 $this->mTrxIdleCallbacks
[] = [ $callback, $fname ];
2506 if ( !$this->mTrxLevel
) {
2507 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2511 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2512 if ( $this->mTrxLevel
) {
2513 $this->mTrxPreCommitCallbacks
[] = [ $callback, $fname ];
2515 // If no transaction is active, then make one for this callback
2516 $this->startAtomic( __METHOD__
);
2518 call_user_func( $callback );
2519 $this->endAtomic( __METHOD__
);
2520 } catch ( Exception
$e ) {
2521 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2527 final public function setTransactionListener( $name, callable
$callback = null ) {
2529 $this->mTrxRecurringCallbacks
[$name] = $callback;
2531 unset( $this->mTrxRecurringCallbacks
[$name] );
2536 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2538 * This method should not be used outside of Database/LoadBalancer
2540 * @param bool $suppress
2543 final public function setTrxEndCallbackSuppression( $suppress ) {
2544 $this->mTrxEndCallbacksSuppressed
= $suppress;
2548 * Actually run and consume any "on transaction idle/resolution" callbacks.
2550 * This method should not be used outside of Database/LoadBalancer
2552 * @param integer $trigger IDatabase::TRIGGER_* constant
2556 public function runOnTransactionIdleCallbacks( $trigger ) {
2557 if ( $this->mTrxEndCallbacksSuppressed
) {
2561 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
2562 /** @var Exception $e */
2563 $e = null; // first exception
2564 do { // callbacks may add callbacks :)
2565 $callbacks = array_merge(
2566 $this->mTrxIdleCallbacks
,
2567 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2569 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2570 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2571 foreach ( $callbacks as $callback ) {
2573 list( $phpCallback ) = $callback;
2574 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
2575 call_user_func_array( $phpCallback, [ $trigger ] );
2577 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
2579 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
2581 } catch ( Exception
$ex ) {
2582 call_user_func( $this->errorLogger
, $ex );
2584 // Some callbacks may use startAtomic/endAtomic, so make sure
2585 // their transactions are ended so other callbacks don't fail
2586 if ( $this->trxLevel() ) {
2587 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2591 } while ( count( $this->mTrxIdleCallbacks
) );
2593 if ( $e instanceof Exception
) {
2594 throw $e; // re-throw any first exception
2599 * Actually run and consume any "on transaction pre-commit" callbacks.
2601 * This method should not be used outside of Database/LoadBalancer
2606 public function runOnTransactionPreCommitCallbacks() {
2607 $e = null; // first exception
2608 do { // callbacks may add callbacks :)
2609 $callbacks = $this->mTrxPreCommitCallbacks
;
2610 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2611 foreach ( $callbacks as $callback ) {
2613 list( $phpCallback ) = $callback;
2614 call_user_func( $phpCallback );
2615 } catch ( Exception
$ex ) {
2616 call_user_func( $this->errorLogger
, $ex );
2620 } while ( count( $this->mTrxPreCommitCallbacks
) );
2622 if ( $e instanceof Exception
) {
2623 throw $e; // re-throw any first exception
2628 * Actually run any "transaction listener" callbacks.
2630 * This method should not be used outside of Database/LoadBalancer
2632 * @param integer $trigger IDatabase::TRIGGER_* constant
2636 public function runTransactionListenerCallbacks( $trigger ) {
2637 if ( $this->mTrxEndCallbacksSuppressed
) {
2641 /** @var Exception $e */
2642 $e = null; // first exception
2644 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2646 $phpCallback( $trigger, $this );
2647 } catch ( Exception
$ex ) {
2648 call_user_func( $this->errorLogger
, $ex );
2653 if ( $e instanceof Exception
) {
2654 throw $e; // re-throw any first exception
2658 final public function startAtomic( $fname = __METHOD__
) {
2659 if ( !$this->mTrxLevel
) {
2660 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2661 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2662 // in all changes being in one transaction to keep requests transactional.
2663 if ( !$this->getFlag( self
::DBO_TRX
) ) {
2664 $this->mTrxAutomaticAtomic
= true;
2668 $this->mTrxAtomicLevels
[] = $fname;
2671 final public function endAtomic( $fname = __METHOD__
) {
2672 if ( !$this->mTrxLevel
) {
2673 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2675 if ( !$this->mTrxAtomicLevels ||
2676 array_pop( $this->mTrxAtomicLevels
) !== $fname
2678 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2681 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2682 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2686 final public function doAtomicSection( $fname, callable
$callback ) {
2687 $this->startAtomic( $fname );
2689 $res = call_user_func_array( $callback, [ $this, $fname ] );
2690 } catch ( Exception
$e ) {
2691 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2694 $this->endAtomic( $fname );
2699 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2700 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2701 if ( $this->mTrxLevel
) {
2702 if ( $this->mTrxAtomicLevels
) {
2703 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2704 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2705 throw new DBUnexpectedError( $this, $msg );
2706 } elseif ( !$this->mTrxAutomatic
) {
2707 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2708 throw new DBUnexpectedError( $this, $msg );
2710 // @TODO: make this an exception at some point
2711 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2712 $this->queryLogger
->error( $msg );
2713 return; // join the main transaction set
2715 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2716 // @TODO: make this an exception at some point
2717 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2718 $this->queryLogger
->error( $msg );
2719 return; // let any writes be in the main transaction
2722 // Avoid fatals if close() was called
2723 $this->assertOpen();
2725 $this->doBegin( $fname );
2726 $this->mTrxTimestamp
= microtime( true );
2727 $this->mTrxFname
= $fname;
2728 $this->mTrxDoneWrites
= false;
2729 $this->mTrxAutomaticAtomic
= false;
2730 $this->mTrxAtomicLevels
= [];
2731 $this->mTrxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2732 $this->mTrxWriteDuration
= 0.0;
2733 $this->mTrxWriteQueryCount
= 0;
2734 $this->mTrxWriteAdjDuration
= 0.0;
2735 $this->mTrxWriteAdjQueryCount
= 0;
2736 $this->mTrxWriteCallers
= [];
2737 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2738 // Get an estimate of the replica DB lag before then, treating estimate staleness
2739 // as lag itself just to be safe
2740 $status = $this->getApproximateLagStatus();
2741 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2742 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
2743 // caller will think its OK to muck around with the transaction just because startAtomic()
2744 // has not yet completed (e.g. setting mTrxAtomicLevels).
2745 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2749 * Issues the BEGIN command to the database server.
2751 * @see Database::begin()
2752 * @param string $fname
2754 protected function doBegin( $fname ) {
2755 $this->query( 'BEGIN', $fname );
2756 $this->mTrxLevel
= 1;
2759 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2760 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2761 // There are still atomic sections open. This cannot be ignored
2762 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2763 throw new DBUnexpectedError(
2765 "$fname: Got COMMIT while atomic sections $levels are still open."
2769 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2770 if ( !$this->mTrxLevel
) {
2771 return; // nothing to do
2772 } elseif ( !$this->mTrxAutomatic
) {
2773 throw new DBUnexpectedError(
2775 "$fname: Flushing an explicit transaction, getting out of sync."
2779 if ( !$this->mTrxLevel
) {
2780 $this->queryLogger
->error(
2781 "$fname: No transaction to commit, something got out of sync." );
2782 return; // nothing to do
2783 } elseif ( $this->mTrxAutomatic
) {
2784 // @TODO: make this an exception at some point
2785 $msg = "$fname: Explicit commit of implicit transaction.";
2786 $this->queryLogger
->error( $msg );
2787 return; // wait for the main transaction set commit round
2791 // Avoid fatals if close() was called
2792 $this->assertOpen();
2794 $this->runOnTransactionPreCommitCallbacks();
2795 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2796 $this->doCommit( $fname );
2797 if ( $this->mTrxDoneWrites
) {
2798 $this->mLastWriteTime
= microtime( true );
2799 $this->trxProfiler
->transactionWritingOut(
2800 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2803 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2804 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
2808 * Issues the COMMIT command to the database server.
2810 * @see Database::commit()
2811 * @param string $fname
2813 protected function doCommit( $fname ) {
2814 if ( $this->mTrxLevel
) {
2815 $this->query( 'COMMIT', $fname );
2816 $this->mTrxLevel
= 0;
2820 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2821 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2822 if ( !$this->mTrxLevel
) {
2823 return; // nothing to do
2826 if ( !$this->mTrxLevel
) {
2827 $this->queryLogger
->error(
2828 "$fname: No transaction to rollback, something got out of sync." );
2829 return; // nothing to do
2830 } elseif ( $this->getFlag( self
::DBO_TRX
) ) {
2831 throw new DBUnexpectedError(
2833 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2838 // Avoid fatals if close() was called
2839 $this->assertOpen();
2841 $this->doRollback( $fname );
2842 $this->mTrxAtomicLevels
= [];
2843 if ( $this->mTrxDoneWrites
) {
2844 $this->trxProfiler
->transactionWritingOut(
2845 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
2848 $this->mTrxIdleCallbacks
= []; // clear
2849 $this->mTrxPreCommitCallbacks
= []; // clear
2850 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
2851 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
2855 * Issues the ROLLBACK command to the database server.
2857 * @see Database::rollback()
2858 * @param string $fname
2860 protected function doRollback( $fname ) {
2861 if ( $this->mTrxLevel
) {
2862 # Disconnects cause rollback anyway, so ignore those errors
2863 $ignoreErrors = true;
2864 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
2865 $this->mTrxLevel
= 0;
2869 public function flushSnapshot( $fname = __METHOD__
) {
2870 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
2871 // This only flushes transactions to clear snapshots, not to write data
2872 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
2873 throw new DBUnexpectedError(
2875 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
2879 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2882 public function explicitTrxActive() {
2883 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
2886 public function duplicateTableStructure(
2887 $oldName, $newName, $temporary = false, $fname = __METHOD__
2889 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2892 public function listTables( $prefix = null, $fname = __METHOD__
) {
2893 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2896 public function listViews( $prefix = null, $fname = __METHOD__
) {
2897 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2900 public function timestamp( $ts = 0 ) {
2901 $t = new ConvertibleTimestamp( $ts );
2902 // Let errors bubble up to avoid putting garbage in the DB
2903 return $t->getTimestamp( TS_MW
);
2906 public function timestampOrNull( $ts = null ) {
2907 if ( is_null( $ts ) ) {
2910 return $this->timestamp( $ts );
2915 * Take the result from a query, and wrap it in a ResultWrapper if
2916 * necessary. Boolean values are passed through as is, to indicate success
2917 * of write queries or failure.
2919 * Once upon a time, Database::query() returned a bare MySQL result
2920 * resource, and it was necessary to call this function to convert it to
2921 * a wrapper. Nowadays, raw database objects are never exposed to external
2922 * callers, so this is unnecessary in external code.
2924 * @param bool|ResultWrapper|resource|object $result
2925 * @return bool|ResultWrapper
2927 protected function resultObject( $result ) {
2930 } elseif ( $result instanceof ResultWrapper
) {
2932 } elseif ( $result === true ) {
2933 // Successful write query
2936 return new ResultWrapper( $this, $result );
2940 public function ping( &$rtt = null ) {
2941 // Avoid hitting the server if it was hit recently
2942 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
2943 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
2944 $rtt = $this->mRTTEstimate
;
2945 return true; // don't care about $rtt
2949 // This will reconnect if possible or return false if not
2950 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
2951 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
2952 $this->restoreFlags( self
::RESTORE_PRIOR
);
2955 $rtt = $this->mRTTEstimate
;
2964 protected function reconnect() {
2965 $this->closeConnection();
2966 $this->mOpened
= false;
2967 $this->mConn
= false;
2969 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
2970 $this->lastPing
= microtime( true );
2972 } catch ( DBConnectionError
$e ) {
2979 public function getSessionLagStatus() {
2980 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
2984 * Get the replica DB lag when the current transaction started
2986 * This is useful when transactions might use snapshot isolation
2987 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
2988 * is this lag plus transaction duration. If they don't, it is still
2989 * safe to be pessimistic. This returns null if there is no transaction.
2991 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
2994 protected function getTransactionLagStatus() {
2995 return $this->mTrxLevel
2996 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3001 * Get a replica DB lag estimate for this server
3003 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3006 protected function getApproximateLagStatus() {
3008 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3009 'since' => microtime( true )
3014 * Merge the result of getSessionLagStatus() for several DBs
3015 * using the most pessimistic values to estimate the lag of
3016 * any data derived from them in combination
3018 * This is information is useful for caching modules
3020 * @see WANObjectCache::set()
3021 * @see WANObjectCache::getWithSetCallback()
3023 * @param IDatabase $db1
3024 * @param IDatabase ...
3025 * @return array Map of values:
3026 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3027 * - since: oldest UNIX timestamp of any of the DB lag estimates
3028 * - pending: whether any of the DBs have uncommitted changes
3031 public static function getCacheSetOptions( IDatabase
$db1 ) {
3032 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3033 foreach ( func_get_args() as $db ) {
3034 /** @var IDatabase $db */
3035 $status = $db->getSessionLagStatus();
3036 if ( $status['lag'] === false ) {
3037 $res['lag'] = false;
3038 } elseif ( $res['lag'] !== false ) {
3039 $res['lag'] = max( $res['lag'], $status['lag'] );
3041 $res['since'] = min( $res['since'], $status['since'] );
3042 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3048 public function getLag() {
3052 public function maxListLen() {
3056 public function encodeBlob( $b ) {
3060 public function decodeBlob( $b ) {
3061 if ( $b instanceof Blob
) {
3067 public function setSessionOptions( array $options ) {
3070 public function sourceFile(
3072 callable
$lineCallback = null,
3073 callable
$resultCallback = null,
3075 callable
$inputCallback = null
3077 MediaWiki\
suppressWarnings();
3078 $fp = fopen( $filename, 'r' );
3079 MediaWiki\restoreWarnings
();
3081 if ( false === $fp ) {
3082 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3086 $fname = __METHOD__
. "( $filename )";
3090 $error = $this->sourceStream(
3091 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3092 } catch ( Exception
$e ) {
3102 public function setSchemaVars( $vars ) {
3103 $this->mSchemaVars
= $vars;
3106 public function sourceStream(
3108 callable
$lineCallback = null,
3109 callable
$resultCallback = null,
3110 $fname = __METHOD__
,
3111 callable
$inputCallback = null
3115 while ( !feof( $fp ) ) {
3116 if ( $lineCallback ) {
3117 call_user_func( $lineCallback );
3120 $line = trim( fgets( $fp ) );
3122 if ( $line == '' ) {
3126 if ( '-' == $line[0] && '-' == $line[1] ) {
3134 $done = $this->streamStatementEnd( $cmd, $line );
3138 if ( $done ||
feof( $fp ) ) {
3139 $cmd = $this->replaceVars( $cmd );
3141 if ( !$inputCallback ||
call_user_func( $inputCallback, $cmd ) ) {
3142 $res = $this->query( $cmd, $fname );
3144 if ( $resultCallback ) {
3145 call_user_func( $resultCallback, $res, $this );
3148 if ( false === $res ) {
3149 $err = $this->lastError();
3151 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3162 * Called by sourceStream() to check if we've reached a statement end
3164 * @param string &$sql SQL assembled so far
3165 * @param string &$newLine New line about to be added to $sql
3166 * @return bool Whether $newLine contains end of the statement
3168 public function streamStatementEnd( &$sql, &$newLine ) {
3169 if ( $this->delimiter
) {
3171 $newLine = preg_replace(
3172 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3173 if ( $newLine != $prev ) {
3182 * Database independent variable replacement. Replaces a set of variables
3183 * in an SQL statement with their contents as given by $this->getSchemaVars().
3185 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3187 * - '{$var}' should be used for text and is passed through the database's
3189 * - `{$var}` should be used for identifiers (e.g. table and database names).
3190 * It is passed through the database's addIdentifierQuotes method which
3191 * can be overridden if the database uses something other than backticks.
3192 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3193 * database's tableName method.
3194 * - / *i* / passes the name that follows through the database's indexName method.
3195 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3196 * its use should be avoided. In 1.24 and older, string encoding was applied.
3198 * @param string $ins SQL statement to replace variables in
3199 * @return string The new SQL statement with variables replaced
3201 protected function replaceVars( $ins ) {
3202 $vars = $this->getSchemaVars();
3203 return preg_replace_callback(
3205 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3206 \'\{\$ (\w+) }\' | # 3. addQuotes
3207 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3208 /\*\$ (\w+) \*/ # 5. leave unencoded
3210 function ( $m ) use ( $vars ) {
3211 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3212 // check for both nonexistent keys *and* the empty string.
3213 if ( isset( $m[1] ) && $m[1] !== '' ) {
3214 if ( $m[1] === 'i' ) {
3215 return $this->indexName( $m[2] );
3217 return $this->tableName( $m[2] );
3219 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3220 return $this->addQuotes( $vars[$m[3]] );
3221 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3222 return $this->addIdentifierQuotes( $vars[$m[4]] );
3223 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3224 return $vars[$m[5]];
3234 * Get schema variables. If none have been set via setSchemaVars(), then
3235 * use some defaults from the current object.
3239 protected function getSchemaVars() {
3240 if ( $this->mSchemaVars
) {
3241 return $this->mSchemaVars
;
3243 return $this->getDefaultSchemaVars();
3248 * Get schema variables to use if none have been set via setSchemaVars().
3250 * Override this in derived classes to provide variables for tables.sql
3251 * and SQL patch files.
3255 protected function getDefaultSchemaVars() {
3259 public function lockIsFree( $lockName, $method ) {
3263 public function lock( $lockName, $method, $timeout = 5 ) {
3264 $this->mNamedLocksHeld
[$lockName] = 1;
3269 public function unlock( $lockName, $method ) {
3270 unset( $this->mNamedLocksHeld
[$lockName] );
3275 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3276 if ( $this->writesOrCallbacksPending() ) {
3277 // This only flushes transactions to clear snapshots, not to write data
3278 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3279 throw new DBUnexpectedError(
3281 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3285 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3289 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3290 if ( $this->trxLevel() ) {
3291 // There is a good chance an exception was thrown, causing any early return
3292 // from the caller. Let any error handler get a chance to issue rollback().
3293 // If there isn't one, let the error bubble up and trigger server-side rollback.
3294 $this->onTransactionResolution(
3295 function () use ( $lockKey, $fname ) {
3296 $this->unlock( $lockKey, $fname );
3301 $this->unlock( $lockKey, $fname );
3305 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3310 public function namedLocksEnqueue() {
3314 public function tableLocksHaveTransactionScope() {
3318 final public function lockTables( array $read, array $write, $method ) {
3319 if ( $this->writesOrCallbacksPending() ) {
3320 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
3323 if ( $this->tableLocksHaveTransactionScope() ) {
3324 $this->startAtomic( $method );
3327 return $this->doLockTables( $read, $write, $method );
3330 protected function doLockTables( array $read, array $write, $method ) {
3334 final public function unlockTables( $method ) {
3335 if ( $this->tableLocksHaveTransactionScope() ) {
3336 $this->endAtomic( $method );
3338 return true; // locks released on COMMIT/ROLLBACK
3341 return $this->doUnlockTables( $method );
3344 protected function doUnlockTables( $method ) {
3350 * @param string $tableName
3351 * @param string $fName
3352 * @return bool|ResultWrapper
3355 public function dropTable( $tableName, $fName = __METHOD__
) {
3356 if ( !$this->tableExists( $tableName, $fName ) ) {
3359 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3361 return $this->query( $sql, $fName );
3364 public function getInfinity() {
3368 public function encodeExpiry( $expiry ) {
3369 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3370 ?
$this->getInfinity()
3371 : $this->timestamp( $expiry );
3374 public function decodeExpiry( $expiry, $format = TS_MW
) {
3375 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3379 return ConvertibleTimestamp
::convert( $format, $expiry );
3382 public function setBigSelects( $value = true ) {
3386 public function isReadOnly() {
3387 return ( $this->getReadOnlyReason() !== false );
3391 * @return string|bool Reason this DB is read-only or false if it is not
3393 protected function getReadOnlyReason() {
3394 $reason = $this->getLBInfo( 'readOnlyReason' );
3396 return is_string( $reason ) ?
$reason : false;
3399 public function setTableAliases( array $aliases ) {
3400 $this->tableAliases
= $aliases;
3404 * @return bool Whether a DB user is required to access the DB
3407 protected function requiresDatabaseUser() {
3412 * Get the underlying binding handle, mConn
3414 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
3415 * This catches broken callers than catch and ignore disconnection exceptions.
3416 * Unlike checking isOpen(), this is safe to call inside of open().
3418 * @return resource|object
3419 * @throws DBUnexpectedError
3422 protected function getBindingHandle() {
3423 if ( !$this->mConn
) {
3424 throw new DBUnexpectedError(
3426 'DB connection was already closed or the connection dropped.'
3430 return $this->mConn
;
3437 public function __toString() {
3438 return (string)$this->mConn
;
3442 * Make sure that copies do not share the same client binding handle
3443 * @throws DBConnectionError
3445 public function __clone() {
3446 $this->connLogger
->warning(
3447 "Cloning " . static::class . " is not recomended; forking connection:\n" .
3448 ( new RuntimeException() )->getTraceAsString()
3451 if ( $this->isOpen() ) {
3452 // Open a new connection resource without messing with the old one
3453 $this->mOpened
= false;
3454 $this->mConn
= false;
3455 $this->mTrxEndCallbacks
= []; // don't copy
3456 $this->handleSessionLoss(); // no trx or locks anymore
3457 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3458 $this->lastPing
= microtime( true );
3463 * Called by serialize. Throw an exception when DB connection is serialized.
3464 * This causes problems on some database engines because the connection is
3465 * not restored on unserialize.
3467 public function __sleep() {
3468 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3469 'the connection is not restored on wakeup.' );
3473 * Run a few simple sanity checks and close dangling connections
3475 public function __destruct() {
3476 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3477 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3480 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3481 if ( $danglingWriters ) {
3482 $fnames = implode( ', ', $danglingWriters );
3483 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3486 if ( $this->mConn
) {
3487 // Avoid connection leaks for sanity. Normally, resources close at script completion.
3488 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
3489 \MediaWiki\
suppressWarnings();
3490 $this->closeConnection();
3491 \MediaWiki\restoreWarnings
();
3492 $this->mConn
= false;
3493 $this->mOpened
= false;
3498 class_alias( Database
::class, 'DatabaseBase' ); // b/c for old name
3499 class_alias( Database
::class, 'Database' ); // b/c global alias