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 Psr\Log\NullLogger
;
31 use Wikimedia\ScopedCallback
;
32 use Wikimedia\Timestamp\ConvertibleTimestamp
;
37 use InvalidArgumentException
;
38 use UnexpectedValueException
;
43 * Relational database abstraction object
48 abstract class Database
implements IDatabase
, IMaintainableDatabase
, LoggerAwareInterface
{
49 /** @var string Server that this instance is currently connected to */
51 /** @var string User that this instance is currently connected under the name of */
53 /** @var string Password used to establish the current connection */
55 /** @var array[] Map of (table => (dbname, schema, prefix) map) */
56 protected $tableAliases = [];
57 /** @var string[] Map of (index alias => index) */
58 protected $indexAliases = [];
59 /** @var bool Whether this PHP instance is for a CLI script */
61 /** @var string Agent name for query profiling */
63 /** @var int Bitfield of class DBO_* constants */
65 /** @var array LoadBalancer tracking information */
66 protected $lbInfo = [];
67 /** @var array|bool Variables use for schema element placeholders */
68 protected $schemaVars = false;
69 /** @var array Parameters used by initConnection() to establish a connection */
70 protected $connectionParams = [];
71 /** @var array SQL variables values to use for all new connections */
72 protected $connectionVariables = [];
73 /** @var string Current SQL query delimiter */
74 protected $delimiter = ';';
75 /** @var string|bool|null Stashed value of html_errors INI setting */
76 protected $htmlErrors;
77 /** @var int Row batch size to use for emulated INSERT SELECT queries */
78 protected $nonNativeInsertSelectBatchSize = 10000;
80 /** @var BagOStuff APC cache */
82 /** @var LoggerInterface */
83 protected $connLogger;
84 /** @var LoggerInterface */
85 protected $queryLogger;
86 /** @var callable Error logging callback */
87 protected $errorLogger;
88 /** @var callable Deprecation logging callback */
89 protected $deprecationLogger;
90 /** @var callable|null */
92 /** @var TransactionProfiler */
93 protected $trxProfiler;
94 /** @var DatabaseDomain */
95 protected $currentDomain;
96 /** @var object|resource|null Database connection */
99 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
100 private $lazyMasterHandle;
102 /** @var array Map of (name => 1) for locks obtained via lock() */
103 protected $sessionNamedLocks = [];
104 /** @var array Map of (table name => 1) for TEMPORARY tables */
105 protected $sessionTempTables = [];
107 /** @var int Whether there is an active transaction (1 or 0) */
108 protected $trxLevel = 0;
109 /** @var string Hexidecimal string if a transaction is active or empty string otherwise */
110 protected $trxShortId = '';
111 /** @var int Transaction status */
112 protected $trxStatus = self
::STATUS_TRX_NONE
;
113 /** @var Exception|null The last error that caused the status to become STATUS_TRX_ERROR */
114 protected $trxStatusCause;
115 /** @var array|null Error details of the last statement-only rollback */
116 private $trxStatusIgnoredCause;
117 /** @var float|null UNIX timestamp at the time of BEGIN for the last transaction */
118 private $trxTimestamp = null;
119 /** @var float Replication lag estimate at the time of BEGIN for the last transaction */
120 private $trxReplicaLag = null;
121 /** @var string Name of the function that start the last transaction */
122 private $trxFname = null;
123 /** @var bool Whether possible write queries were done in the last transaction started */
124 private $trxDoneWrites = false;
125 /** @var bool Whether the current transaction was started implicitly due to DBO_TRX */
126 private $trxAutomatic = false;
127 /** @var int Counter for atomic savepoint identifiers (reset with each transaction) */
128 private $trxAtomicCounter = 0;
129 /** @var array List of (name, unique ID, savepoint ID) for each active atomic section level */
130 private $trxAtomicLevels = [];
131 /** @var bool Whether the current transaction was started implicitly by startAtomic() */
132 private $trxAutomaticAtomic = false;
133 /** @var string[] Write query callers of the current transaction */
134 private $trxWriteCallers = [];
135 /** @var float Seconds spent in write queries for the current transaction */
136 private $trxWriteDuration = 0.0;
137 /** @var int Number of write queries for the current transaction */
138 private $trxWriteQueryCount = 0;
139 /** @var int Number of rows affected by write queries for the current transaction */
140 private $trxWriteAffectedRows = 0;
141 /** @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries */
142 private $trxWriteAdjDuration = 0.0;
143 /** @var int Number of write queries counted in trxWriteAdjDuration */
144 private $trxWriteAdjQueryCount = 0;
145 /** @var array[] List of (callable, method name, atomic section id) */
146 private $trxIdleCallbacks = [];
147 /** @var array[] List of (callable, method name, atomic section id) */
148 private $trxPreCommitCallbacks = [];
149 /** @var array[] List of (callable, method name, atomic section id) */
150 private $trxEndCallbacks = [];
151 /** @var callable[] Map of (name => callable) */
152 private $trxRecurringCallbacks = [];
153 /** @var bool Whether to suppress triggering of transaction end callbacks */
154 private $trxEndCallbacksSuppressed = false;
156 /** @var int[] Prior flags member variable values */
157 private $priorFlags = [];
159 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
160 protected $affectedRowCount;
162 /** @var float UNIX timestamp */
163 private $lastPing = 0.0;
164 /** @var string The last SQL query attempted */
165 private $lastQuery = '';
166 /** @var float|bool UNIX timestamp of last write query */
167 private $lastWriteTime = false;
168 /** @var string|bool */
169 private $lastPhpError = false;
170 /** @var float Query rount trip time estimate */
171 private $lastRoundTripEstimate = 0.0;
173 /** @var string Lock granularity is on the level of the entire database */
174 const ATTR_DB_LEVEL_LOCKING
= 'db-level-locking';
175 /** @var string The SCHEMA keyword refers to a grouping of tables in a database */
176 const ATTR_SCHEMAS_AS_TABLE_GROUPS
= 'supports-schemas';
178 /** @var int New Database instance will not be connected yet when returned */
179 const NEW_UNCONNECTED
= 0;
180 /** @var int New Database instance will already be connected when returned */
181 const NEW_CONNECTED
= 1;
183 /** @var int Transaction is in a error state requiring a full or savepoint rollback */
184 const STATUS_TRX_ERROR
= 1;
185 /** @var int Transaction is active and in a normal state */
186 const STATUS_TRX_OK
= 2;
187 /** @var int No transaction is active */
188 const STATUS_TRX_NONE
= 3;
190 /** @var string Idiom used when a cancelable atomic section started the transaction */
191 private static $NOT_APPLICABLE = 'n/a';
192 /** @var string Prefix to the atomic section counter used to make savepoint IDs */
193 private static $SAVEPOINT_PREFIX = 'wikimedia_rdbms_atomic';
195 /** @var int Writes to this temporary table do not affect lastDoneWrites() */
196 private static $TEMP_NORMAL = 1;
197 /** @var int Writes to this temporary table effect lastDoneWrites() */
198 private static $TEMP_PSEUDO_PERMANENT = 2;
200 /** Number of times to re-try an operation in case of deadlock */
201 private static $DEADLOCK_TRIES = 4;
202 /** Minimum time to wait before retry, in microseconds */
203 private static $DEADLOCK_DELAY_MIN = 500000;
204 /** Maximum time to wait before retry */
205 private static $DEADLOCK_DELAY_MAX = 1500000;
207 /** How long before it is worth doing a dummy query to test the connection */
208 private static $PING_TTL = 1.0;
209 private static $PING_QUERY = 'SELECT 1 AS ping';
211 private static $TINY_WRITE_SEC = 0.010;
212 private static $SLOW_WRITE_SEC = 0.500;
213 private static $SMALL_WRITE_ROWS = 100;
216 * @note exceptions for missing libraries/drivers should be thrown in initConnection()
217 * @param array $params Parameters passed from Database::factory()
219 protected function __construct( array $params ) {
220 foreach ( [ 'host', 'user', 'password', 'dbname', 'schema', 'tablePrefix' ] as $name ) {
221 $this->connectionParams
[$name] = $params[$name];
224 $this->cliMode
= $params['cliMode'];
225 // Agent name is added to SQL queries in a comment, so make sure it can't break out
226 $this->agent
= str_replace( '/', '-', $params['agent'] );
228 $this->flags
= $params['flags'];
229 if ( $this->flags
& self
::DBO_DEFAULT
) {
230 if ( $this->cliMode
) {
231 $this->flags
&= ~self
::DBO_TRX
;
233 $this->flags |
= self
::DBO_TRX
;
236 // Disregard deprecated DBO_IGNORE flag (T189999)
237 $this->flags
&= ~self
::DBO_IGNORE
;
239 $this->connectionVariables
= $params['variables'];
241 $this->srvCache
= $params['srvCache'] ??
new HashBagOStuff();
243 $this->profiler
= is_callable( $params['profiler'] ) ?
$params['profiler'] : null;
244 $this->trxProfiler
= $params['trxProfiler'];
245 $this->connLogger
= $params['connLogger'];
246 $this->queryLogger
= $params['queryLogger'];
247 $this->errorLogger
= $params['errorLogger'];
248 $this->deprecationLogger
= $params['deprecationLogger'];
250 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
251 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'];
254 // Set initial dummy domain until open() sets the final DB/prefix
255 $this->currentDomain
= new DatabaseDomain(
256 $params['dbname'] != '' ?
$params['dbname'] : null,
257 $params['schema'] != '' ?
$params['schema'] : null,
258 $params['tablePrefix']
263 * Initialize the connection to the database over the wire (or to local files)
265 * @throws LogicException
266 * @throws InvalidArgumentException
267 * @throws DBConnectionError
270 final public function initConnection() {
271 if ( $this->isOpen() ) {
272 throw new LogicException( __METHOD__
. ': already connected.' );
274 // Establish the connection
275 $this->doInitConnection();
279 * Actually connect to the database over the wire (or to local files)
281 * @throws InvalidArgumentException
282 * @throws DBConnectionError
285 protected function doInitConnection() {
286 if ( strlen( $this->connectionParams
['user'] ) ) {
288 $this->connectionParams
['host'],
289 $this->connectionParams
['user'],
290 $this->connectionParams
['password'],
291 $this->connectionParams
['dbname'],
292 $this->connectionParams
['schema'],
293 $this->connectionParams
['tablePrefix']
296 throw new InvalidArgumentException( "No database user provided." );
301 * Open a new connection to the database (closing any existing one)
303 * @param string $server Database server host
304 * @param string $user Database user name
305 * @param string $password Database user password
306 * @param string $dbName Database name
307 * @param string|null $schema Database schema name
308 * @param string $tablePrefix Table prefix
309 * @throws DBConnectionError
311 abstract protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix );
314 * Construct a Database subclass instance given a database type and parameters
316 * This also connects to the database immediately upon object construction
318 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
319 * @param array $p Parameter map with keys:
320 * - host : The hostname of the DB server
321 * - user : The name of the database user the client operates under
322 * - password : The password for the database user
323 * - dbname : The name of the database to use where queries do not specify one.
324 * The database must exist or an error might be thrown. Setting this to the empty string
325 * will avoid any such errors and make the handle have no implicit database scope. This is
326 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
327 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
328 * in which user names and such are defined, e.g. users are database-specific in Postgres.
329 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
330 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
331 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
332 * recognized in queries. This can be used in place of schemas for handle site farms.
333 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
334 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
335 * flag in place UNLESS this this database simply acts as a key/value store.
336 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
337 * 'mysqli' driver; the old one 'mysql' has been removed.
338 * - variables: Optional map of session variables to set after connecting. This can be
339 * used to adjust lock timeouts or encoding modes and the like.
340 * - connLogger: Optional PSR-3 logger interface instance.
341 * - queryLogger: Optional PSR-3 logger interface instance.
342 * - profiler : Optional callback that takes a section name argument and returns
343 * a ScopedCallback instance that ends the profile section in its destructor.
344 * These will be called in query(), using a simplified version of the SQL that
345 * also includes the agent as a SQL comment.
346 * - trxProfiler: Optional TransactionProfiler instance.
347 * - errorLogger: Optional callback that takes an Exception and logs it.
348 * - deprecationLogger: Optional callback that takes a string and logs it.
349 * - cliMode: Whether to consider the execution context that of a CLI script.
350 * - agent: Optional name used to identify the end-user in query profiling/logging.
351 * - srvCache: Optional BagOStuff instance to an APC-style cache.
352 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
353 * @param int $connect One of the class constants (NEW_CONNECTED, NEW_UNCONNECTED) [optional]
354 * @return Database|null If the database driver or extension cannot be found
355 * @throws InvalidArgumentException If the database driver or extension cannot be found
358 final public static function factory( $dbType, $p = [], $connect = self
::NEW_CONNECTED
) {
359 $class = self
::getClass( $dbType, $p['driver'] ??
null );
361 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
362 // Resolve some defaults for b/c
363 $p['host'] = $p['host'] ??
false;
364 $p['user'] = $p['user'] ??
false;
365 $p['password'] = $p['password'] ??
false;
366 $p['dbname'] = $p['dbname'] ??
false;
367 $p['flags'] = $p['flags'] ??
0;
368 $p['variables'] = $p['variables'] ??
[];
369 $p['tablePrefix'] = $p['tablePrefix'] ??
'';
370 $p['schema'] = $p['schema'] ??
null;
371 $p['cliMode'] = $p['cliMode'] ??
( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
372 $p['agent'] = $p['agent'] ??
'';
373 if ( !isset( $p['connLogger'] ) ) {
374 $p['connLogger'] = new NullLogger();
376 if ( !isset( $p['queryLogger'] ) ) {
377 $p['queryLogger'] = new NullLogger();
379 $p['profiler'] = $p['profiler'] ??
null;
380 if ( !isset( $p['trxProfiler'] ) ) {
381 $p['trxProfiler'] = new TransactionProfiler();
383 if ( !isset( $p['errorLogger'] ) ) {
384 $p['errorLogger'] = function ( Exception
$e ) {
385 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
388 if ( !isset( $p['deprecationLogger'] ) ) {
389 $p['deprecationLogger'] = function ( $msg ) {
390 trigger_error( $msg, E_USER_DEPRECATED
);
394 /** @var Database $conn */
395 $conn = new $class( $p );
396 if ( $connect == self
::NEW_CONNECTED
) {
397 $conn->initConnection();
407 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
408 * @param string|null $driver Optional name of a specific DB client driver
409 * @return array Map of (Database::ATTR_* constant => value) for all such constants
410 * @throws InvalidArgumentException
413 final public static function attributesFromType( $dbType, $driver = null ) {
415 self
::ATTR_DB_LEVEL_LOCKING
=> false,
416 self
::ATTR_SCHEMAS_AS_TABLE_GROUPS
=> false
419 $class = self
::getClass( $dbType, $driver );
421 return call_user_func( [ $class, 'getAttributes' ] ) +
$defaults;
425 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
426 * @param string|null $driver Optional name of a specific DB client driver
427 * @return string Database subclass name to use
428 * @throws InvalidArgumentException
430 private static function getClass( $dbType, $driver = null ) {
431 // For database types with built-in support, the below maps type to IDatabase
432 // implementations. For types with multipe driver implementations (PHP extensions),
433 // an array can be used, keyed by extension name. In case of an array, the
434 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
435 // we auto-detect the first available driver. For types without built-in support,
436 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
437 static $builtinTypes = [
438 'mssql' => DatabaseMssql
::class,
439 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
440 'sqlite' => DatabaseSqlite
::class,
441 'postgres' => DatabasePostgres
::class,
444 $dbType = strtolower( $dbType );
447 if ( isset( $builtinTypes[$dbType] ) ) {
448 $possibleDrivers = $builtinTypes[$dbType];
449 if ( is_string( $possibleDrivers ) ) {
450 $class = $possibleDrivers;
451 } elseif ( (string)$driver !== '' ) {
452 if ( !isset( $possibleDrivers[$driver] ) ) {
453 throw new InvalidArgumentException( __METHOD__
.
454 " type '$dbType' does not support driver '{$driver}'" );
457 $class = $possibleDrivers[$driver];
459 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
460 if ( extension_loaded( $posDriver ) ) {
461 $class = $possibleClass;
467 $class = 'Database' . ucfirst( $dbType );
470 if ( $class === false ) {
471 throw new InvalidArgumentException( __METHOD__
.
472 " no viable database extension found for type '$dbType'" );
479 * @return array Map of (Database::ATTR_* constant => value
482 protected static function getAttributes() {
487 * Set the PSR-3 logger interface to use for query logging. (The logger
488 * interfaces for connection logging and error logging can be set with the
491 * @param LoggerInterface $logger
493 public function setLogger( LoggerInterface
$logger ) {
494 $this->queryLogger
= $logger;
497 public function getServerInfo() {
498 return $this->getServerVersion();
501 public function bufferResults( $buffer = null ) {
502 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
503 if ( $buffer !== null ) {
505 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
506 : $this->setFlag( self
::DBO_NOBUFFER
);
512 public function trxLevel() {
513 return $this->trxLevel
;
516 public function trxTimestamp() {
517 return $this->trxLevel ?
$this->trxTimestamp
: null;
521 * @return int One of the STATUS_TRX_* class constants
524 public function trxStatus() {
525 return $this->trxStatus
;
528 public function tablePrefix( $prefix = null ) {
529 $old = $this->currentDomain
->getTablePrefix();
530 if ( $prefix !== null ) {
531 $this->currentDomain
= new DatabaseDomain(
532 $this->currentDomain
->getDatabase(),
533 $this->currentDomain
->getSchema(),
541 public function dbSchema( $schema = null ) {
542 if ( strlen( $schema ) && $this->getDBname() === null ) {
543 throw new DBUnexpectedError( $this, "Cannot set schema to '$schema'; no database set." );
546 $old = $this->currentDomain
->getSchema();
547 if ( $schema !== null ) {
548 $this->currentDomain
= new DatabaseDomain(
549 $this->currentDomain
->getDatabase(),
550 // DatabaseDomain uses null for unspecified schemas
551 strlen( $schema ) ?
$schema : null,
552 $this->currentDomain
->getTablePrefix()
560 * @return string Schema to use to qualify relations in queries
562 protected function relationSchemaQualifier() {
563 return $this->dbSchema();
566 public function getLBInfo( $name = null ) {
567 if ( is_null( $name ) ) {
568 return $this->lbInfo
;
571 if ( array_key_exists( $name, $this->lbInfo
) ) {
572 return $this->lbInfo
[$name];
578 public function setLBInfo( $name, $value = null ) {
579 if ( is_null( $value ) ) {
580 $this->lbInfo
= $name;
582 $this->lbInfo
[$name] = $value;
586 public function setLazyMasterHandle( IDatabase
$conn ) {
587 $this->lazyMasterHandle
= $conn;
591 * @return IDatabase|null
592 * @see setLazyMasterHandle()
595 protected function getLazyMasterHandle() {
596 return $this->lazyMasterHandle
;
599 public function implicitGroupby() {
603 public function implicitOrderby() {
607 public function lastQuery() {
608 return $this->lastQuery
;
611 public function doneWrites() {
612 return (bool)$this->lastWriteTime
;
615 public function lastDoneWrites() {
616 return $this->lastWriteTime ?
: false;
619 public function writesPending() {
620 return $this->trxLevel
&& $this->trxDoneWrites
;
623 public function writesOrCallbacksPending() {
624 return $this->trxLevel
&& (
625 $this->trxDoneWrites ||
626 $this->trxIdleCallbacks ||
627 $this->trxPreCommitCallbacks ||
628 $this->trxEndCallbacks
632 public function preCommitCallbacksPending() {
633 return $this->trxLevel
&& $this->trxPreCommitCallbacks
;
637 * @return string|null
639 final protected function getTransactionRoundId() {
640 // If transaction round participation is enabled, see if one is active
641 if ( $this->getFlag( self
::DBO_TRX
) ) {
642 $id = $this->getLBInfo( 'trxRoundId' );
644 return is_string( $id ) ?
$id : null;
650 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
651 if ( !$this->trxLevel
) {
653 } elseif ( !$this->trxDoneWrites
) {
658 case self
::ESTIMATE_DB_APPLY
:
659 return $this->pingAndCalculateLastTrxApplyTime();
660 default: // everything
661 return $this->trxWriteDuration
;
666 * @return float Time to apply writes to replicas based on trxWrite* fields
668 private function pingAndCalculateLastTrxApplyTime() {
671 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
672 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
673 // For omitted queries, make them count as something at least
674 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
675 $applyTime +
= self
::$TINY_WRITE_SEC * $omitted;
680 public function pendingWriteCallers() {
681 return $this->trxLevel ?
$this->trxWriteCallers
: [];
684 public function pendingWriteRowsAffected() {
685 return $this->trxWriteAffectedRows
;
689 * List the methods that have write queries or callbacks for the current transaction
691 * This method should not be used outside of Database/LoadBalancer
696 public function pendingWriteAndCallbackCallers() {
697 $fnames = $this->pendingWriteCallers();
699 $this->trxIdleCallbacks
,
700 $this->trxPreCommitCallbacks
,
701 $this->trxEndCallbacks
703 foreach ( $callbacks as $callback ) {
704 $fnames[] = $callback[1];
714 private function flatAtomicSectionList() {
715 return array_reduce( $this->trxAtomicLevels
, function ( $accum, $v ) {
716 return $accum === null ?
$v[0] : "$accum, " . $v[0];
720 public function isOpen() {
721 return (bool)$this->conn
;
724 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
725 if ( ( $flag & self
::DBO_IGNORE
) ) {
726 throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
729 if ( $remember === self
::REMEMBER_PRIOR
) {
730 array_push( $this->priorFlags
, $this->flags
);
732 $this->flags |
= $flag;
735 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
736 if ( ( $flag & self
::DBO_IGNORE
) ) {
737 throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
740 if ( $remember === self
::REMEMBER_PRIOR
) {
741 array_push( $this->priorFlags
, $this->flags
);
743 $this->flags
&= ~
$flag;
746 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
747 if ( !$this->priorFlags
) {
751 if ( $state === self
::RESTORE_INITIAL
) {
752 $this->flags
= reset( $this->priorFlags
);
753 $this->priorFlags
= [];
755 $this->flags
= array_pop( $this->priorFlags
);
759 public function getFlag( $flag ) {
760 return (bool)( $this->flags
& $flag );
764 * @param string $name Class field name
766 * @deprecated Since 1.28
768 public function getProperty( $name ) {
772 public function getDomainID() {
773 return $this->currentDomain
->getId();
776 final public function getWikiID() {
777 return $this->getDomainID();
781 * Get information about an index into an object
782 * @param string $table Table name
783 * @param string $index Index name
784 * @param string $fname Calling function name
785 * @return mixed Database-specific index description class or false if the index does not exist
787 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
790 * Wrapper for addslashes()
792 * @param string $s String to be slashed.
793 * @return string Slashed string.
795 abstract function strencode( $s );
798 * Set a custom error handler for logging errors during database connection
800 protected function installErrorHandler() {
801 $this->lastPhpError
= false;
802 $this->htmlErrors
= ini_set( 'html_errors', '0' );
803 set_error_handler( [ $this, 'connectionErrorLogger' ] );
807 * Restore the previous error handler and return the last PHP error for this DB
809 * @return bool|string
811 protected function restoreErrorHandler() {
812 restore_error_handler();
813 if ( $this->htmlErrors
!== false ) {
814 ini_set( 'html_errors', $this->htmlErrors
);
817 return $this->getLastPHPError();
821 * @return string|bool Last PHP error for this DB (typically connection errors)
823 protected function getLastPHPError() {
824 if ( $this->lastPhpError
) {
825 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->lastPhpError
);
826 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
835 * Error handler for logging errors during database connection
836 * This method should not be used outside of Database classes
839 * @param string $errstr
841 public function connectionErrorLogger( $errno, $errstr ) {
842 $this->lastPhpError
= $errstr;
846 * Create a log context to pass to PSR-3 logger functions.
848 * @param array $extras Additional data to add to context
851 protected function getLogContext( array $extras = [] ) {
854 'db_server' => $this->server
,
855 'db_name' => $this->getDBname(),
856 'db_user' => $this->user
,
862 final public function close() {
863 $exception = null; // error to throw after disconnecting
865 $wasOpen = (bool)$this->conn
;
866 // This should mostly do nothing if the connection is already closed
868 // Roll back any dangling transaction first
869 if ( $this->trxLevel
) {
870 if ( $this->trxAtomicLevels
) {
871 // Cannot let incomplete atomic sections be committed
872 $levels = $this->flatAtomicSectionList();
873 $exception = new DBUnexpectedError(
875 __METHOD__
. ": atomic sections $levels are still open."
877 } elseif ( $this->trxAutomatic
) {
878 // Only the connection manager can commit non-empty DBO_TRX transactions
879 // (empty ones we can silently roll back)
880 if ( $this->writesOrCallbacksPending() ) {
881 $exception = new DBUnexpectedError(
884 ": mass commit/rollback of peer transaction required (DBO_TRX set)."
888 // Manual transactions should have been committed or rolled
889 // back, even if empty.
890 $exception = new DBUnexpectedError(
892 __METHOD__
. ": transaction is still open (from {$this->trxFname})."
896 if ( $this->trxEndCallbacksSuppressed
) {
897 $exception = $exception ?
: new DBUnexpectedError(
899 __METHOD__
. ': callbacks are suppressed; cannot properly commit.'
903 // Rollback the changes and run any callbacks as needed
904 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
907 // Close the actual connection in the binding handle
908 $closed = $this->closeConnection();
910 $closed = true; // already closed; nothing to do
915 // Throw any unexpected errors after having disconnected
916 if ( $exception instanceof Exception
) {
920 // Note that various subclasses call close() at the start of open(), which itself is
921 // called by replaceLostConnection(). In that case, just because onTransactionResolution()
922 // callbacks are pending does not mean that an exception should be thrown. Rather, they
923 // will be executed after the reconnection step.
925 // Sanity check that no callbacks are dangling
926 $fnames = $this->pendingWriteAndCallbackCallers();
928 throw new RuntimeException(
929 "Transaction callbacks are still pending:\n" . implode( ', ', $fnames )
938 * Make sure there is an open connection handle (alive or not) as a sanity check
940 * This guards against fatal errors to the binding handle not being defined
941 * in cases where open() was never called or close() was already called
943 * @throws DBUnexpectedError
945 final protected function assertHasConnectionHandle() {
946 if ( !$this->isOpen() ) {
947 throw new DBUnexpectedError( $this, "DB connection was already closed." );
952 * Make sure that this server is not marked as a replica nor read-only as a sanity check
954 * @throws DBReadOnlyRoleError
955 * @throws DBReadOnlyError
957 protected function assertIsWritableMaster() {
958 if ( $this->getLBInfo( 'replica' ) === true ) {
959 throw new DBReadOnlyRoleError(
961 'Write operations are not allowed on replica database connections.'
964 $reason = $this->getReadOnlyReason();
965 if ( $reason !== false ) {
966 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
971 * Closes underlying database connection
973 * @return bool Whether connection was closed successfully
975 abstract protected function closeConnection();
978 * Run a query and return a DBMS-dependent wrapper or boolean
980 * This is meant to handle the basic command of actually sending a query to the
981 * server via the driver. No implicit transaction, reconnection, nor retry logic
982 * should happen here. The higher level query() method is designed to handle those
983 * sorts of concerns. This method should not trigger such higher level methods.
985 * The lastError() and lastErrno() methods should meaningfully reflect what error,
986 * if any, occured during the last call to this method. Methods like executeQuery(),
987 * query(), select(), insert(), update(), delete(), and upsert() implement their calls
988 * to doQuery() such that an immediately subsequent call to lastError()/lastErrno()
989 * meaningfully reflects any error that occured during that public query method call.
991 * For SELECT queries, this returns either:
992 * - a) A driver-specific value/resource, only on success. This can be iterated
993 * over by calling fetchObject()/fetchRow() until there are no more rows.
994 * Alternatively, the result can be passed to resultObject() to obtain a
995 * ResultWrapper instance which can then be iterated over via "foreach".
996 * - b) False, on any query failure
998 * For non-SELECT queries, this returns either:
999 * - a) A driver-specific value/resource, only on success
1000 * - b) True, only on success (e.g. no meaningful result other than "OK")
1001 * - c) False, on any query failure
1003 * @param string $sql SQL query
1004 * @return mixed|bool An object, resource, or true on success; false on failure
1006 abstract protected function doQuery( $sql );
1009 * Determine whether a query writes to the DB. When in doubt, this returns true.
1013 * - Subsequent web requests should not need to wait for replication from
1014 * the master position seen by this web request, unless this request made
1015 * changes to the master. This is handled by ChronologyProtector by checking
1016 * doneWrites() at the end of the request. doneWrites() returns true if any
1017 * query set lastWriteTime; which query() does based on isWriteQuery().
1019 * - Reject write queries to replica DBs, in query().
1021 * @param string $sql
1024 protected function isWriteQuery( $sql ) {
1025 // BEGIN and COMMIT queries are considered read queries here.
1026 // Database backends and drivers (MySQL, MariaDB, php-mysqli) generally
1027 // treat these as write queries, in that their results have "affected rows"
1028 // as meta data as from writes, instead of "num rows" as from reads.
1029 // But, we treat them as read queries because when reading data (from
1030 // either replica or master) we use transactions to enable repeatable-read
1031 // snapshots, which ensures we get consistent results from the same snapshot
1032 // for all queries within a request. Use cases:
1033 // - Treating these as writes would trigger ChronologyProtector (see method doc).
1034 // - We use this method to reject writes to replicas, but we need to allow
1035 // use of transactions on replicas for read snapshots. This is fine given
1036 // that transactions by themselves don't make changes, only actual writes
1037 // within the transaction matter, which we still detect.
1039 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SAVEPOINT|RELEASE|SET|SHOW|EXPLAIN|USE|\(SELECT)\b/i',
1045 * @param string $sql
1046 * @return string|null
1048 protected function getQueryVerb( $sql ) {
1049 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
1053 * Determine whether a SQL statement is sensitive to isolation level.
1055 * A SQL statement is considered transactable if its result could vary
1056 * depending on the transaction isolation level. Operational commands
1057 * such as 'SET' and 'SHOW' are not considered to be transactable.
1059 * Main purpose: Used by query() to decide whether to begin a transaction
1060 * before the current query (in DBO_TRX mode, on by default).
1062 * @param string $sql
1065 protected function isTransactableQuery( $sql ) {
1067 $this->getQueryVerb( $sql ),
1068 [ 'BEGIN', 'ROLLBACK', 'COMMIT', 'SET', 'SHOW', 'CREATE', 'ALTER', 'USE' ],
1074 * @param string $sql A SQL query
1075 * @param bool $pseudoPermanent Treat any table from CREATE TEMPORARY as pseudo-permanent
1076 * @return int|null A self::TEMP_* constant for temp table operations or null otherwise
1078 protected function registerTempTableWrite( $sql, $pseudoPermanent ) {
1079 static $qt = '[`"\']?(\w+)[`"\']?'; // quoted table
1082 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?' . $qt . '/i',
1086 $type = $pseudoPermanent ? self
::$TEMP_PSEUDO_PERMANENT : self
::$TEMP_NORMAL;
1087 $this->sessionTempTables
[$matches[1]] = $type;
1090 } elseif ( preg_match(
1091 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt . '/i',
1095 $type = $this->sessionTempTables
[$matches[1]] ??
null;
1096 unset( $this->sessionTempTables
[$matches[1]] );
1099 } elseif ( preg_match(
1100 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt . '/i',
1104 return $this->sessionTempTables
[$matches[1]] ??
null;
1105 } elseif ( preg_match(
1106 '/^(?:(?:INSERT|REPLACE)\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+' . $qt . '/i',
1110 return $this->sessionTempTables
[$matches[1]] ??
null;
1116 public function query( $sql, $fname = __METHOD__
, $flags = 0 ) {
1117 $flags = (int)$flags; // b/c; this field used to be a bool
1118 // Sanity check that the SQL query is appropriate in the current context and is
1119 // allowed for an outside caller (e.g. does not break transaction/session tracking).
1120 $this->assertQueryIsCurrentlyAllowed( $sql, $fname );
1122 // Send the query to the server and fetch any corresponding errors
1123 list( $ret, $err, $errno, $unignorable ) = $this->executeQuery( $sql, $fname, $flags );
1124 if ( $ret === false ) {
1125 $ignoreErrors = $this->hasFlags( $flags, self
::QUERY_SILENCE_ERRORS
);
1126 // Throw an error unless both the ignore flag was set and a rollback is not needed
1127 $this->reportQueryError( $err, $errno, $sql, $fname, $ignoreErrors && !$unignorable );
1130 return $this->resultObject( $ret );
1134 * Execute a query, retrying it if there is a recoverable connection loss
1136 * This is similar to query() except:
1137 * - It does not prevent all non-ROLLBACK queries if there is a corrupted transaction
1138 * - It does not disallow raw queries that are supposed to use dedicated IDatabase methods
1139 * - It does not throw exceptions for common error cases
1141 * This is meant for internal use with Database subclasses.
1143 * @param string $sql Original SQL query
1144 * @param string $fname Name of the calling function
1145 * @param int $flags Bitfield of class QUERY_* constants
1146 * @return array An n-tuple of:
1147 * - mixed|bool: An object, resource, or true on success; false on failure
1148 * - string: The result of calling lastError()
1149 * - int: The result of calling lastErrno()
1150 * - bool: Whether a rollback is needed to allow future non-rollback queries
1151 * @throws DBUnexpectedError
1153 final protected function executeQuery( $sql, $fname, $flags ) {
1154 $this->assertHasConnectionHandle();
1156 $priorTransaction = $this->trxLevel
;
1158 if ( $this->isWriteQuery( $sql ) ) {
1159 # In theory, non-persistent writes are allowed in read-only mode, but due to things
1160 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1161 $this->assertIsWritableMaster();
1162 # Do not treat temporary table writes as "meaningful writes" since they are only
1163 # visible to one session and are not permanent. Profile them as reads. Integration
1164 # tests can override this behavior via $flags.
1165 $pseudoPermanent = $this->hasFlags( $flags, self
::QUERY_PSEUDO_PERMANENT
);
1166 $tableType = $this->registerTempTableWrite( $sql, $pseudoPermanent );
1167 $isPermWrite = ( $tableType !== self
::$TEMP_NORMAL );
1168 # DBConnRef uses QUERY_REPLICA_ROLE to enforce the replica role for raw SQL queries
1169 if ( $isPermWrite && $this->hasFlags( $flags, self
::QUERY_REPLICA_ROLE
) ) {
1170 throw new DBReadOnlyRoleError( $this, "Cannot write; target role is DB_REPLICA" );
1173 $isPermWrite = false;
1176 // Add trace comment to the begin of the sql string, right after the operator.
1177 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
1178 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
1180 // Send the query to the server and fetch any corresponding errors
1181 list( $ret, $err, $errno, $recoverableSR, $recoverableCL, $reconnected ) =
1182 $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1184 // Check if the query failed due to a recoverable connection loss
1185 $allowRetry = !$this->hasFlags( $flags, self
::QUERY_NO_RETRY
);
1186 if ( $ret === false && $recoverableCL && $reconnected && $allowRetry ) {
1187 // Silently resend the query to the server since it is safe and possible
1188 list( $ret, $err, $errno, $recoverableSR, $recoverableCL ) =
1189 $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1192 $corruptedTrx = false;
1194 if ( $ret === false ) {
1195 if ( $priorTransaction ) {
1196 if ( $recoverableSR ) {
1197 # We're ignoring an error that caused just the current query to be aborted.
1198 # But log the cause so we can log a deprecation notice if a caller actually
1200 $this->trxStatusIgnoredCause
= [ $err, $errno, $fname ];
1201 } elseif ( !$recoverableCL ) {
1202 # Either the query was aborted or all queries after BEGIN where aborted.
1203 # In the first case, the only options going forward are (a) ROLLBACK, or
1204 # (b) ROLLBACK TO SAVEPOINT (if one was set). If the later case, the only
1205 # option is ROLLBACK, since the snapshots would have been released.
1206 $corruptedTrx = true; // cannot recover
1207 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
1208 $this->trxStatusCause
=
1209 $this->getQueryExceptionAndLog( $err, $errno, $sql, $fname );
1210 $this->trxStatusIgnoredCause
= null;
1215 return [ $ret, $err, $errno, $corruptedTrx ];
1219 * Wrapper for doQuery() that handles DBO_TRX, profiling, logging, affected row count
1220 * tracking, and reconnects (without retry) on query failure due to connection loss
1222 * @param string $sql Original SQL query
1223 * @param string $commentedSql SQL query with debugging/trace comment
1224 * @param bool $isPermWrite Whether the query is a (non-temporary table) write
1225 * @param string $fname Name of the calling function
1226 * @param int $flags Bitfield of class QUERY_* constants
1227 * @return array An n-tuple of:
1228 * - mixed|bool: An object, resource, or true on success; false on failure
1229 * - string: The result of calling lastError()
1230 * - int: The result of calling lastErrno()
1231 * - bool: Whether a statement rollback error occured
1232 * - bool: Whether a disconnect *both* happened *and* was recoverable
1233 * - bool: Whether a reconnection attempt was *both* made *and* succeeded
1234 * @throws DBUnexpectedError
1236 private function executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags ) {
1237 $priorWritesPending = $this->writesOrCallbacksPending();
1239 if ( ( $flags & self
::QUERY_IGNORE_DBO_TRX
) == 0 ) {
1240 $this->beginIfImplied( $sql, $fname );
1243 // Keep track of whether the transaction has write queries pending
1244 if ( $isPermWrite ) {
1245 $this->lastWriteTime
= microtime( true );
1246 if ( $this->trxLevel
&& !$this->trxDoneWrites
) {
1247 $this->trxDoneWrites
= true;
1248 $this->trxProfiler
->transactionWritingIn(
1249 $this->server
, $this->getDomainID(), $this->trxShortId
);
1253 $prefix = !is_null( $this->getLBInfo( 'master' ) ) ?
'query-m: ' : 'query: ';
1254 $generalizedSql = new GeneralizedSql( $sql, $this->trxShortId
, $prefix );
1256 $startTime = microtime( true );
1257 $ps = $this->profiler
1258 ?
( $this->profiler
)( $generalizedSql->stringify() )
1260 $this->affectedRowCount
= null;
1261 $this->lastQuery
= $sql;
1262 $ret = $this->doQuery( $commentedSql );
1263 $lastError = $this->lastError();
1264 $lastErrno = $this->lastErrno();
1266 $this->affectedRowCount
= $this->affectedRows();
1267 unset( $ps ); // profile out (if set)
1268 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1270 $recoverableSR = false; // recoverable statement rollback?
1271 $recoverableCL = false; // recoverable connection loss?
1272 $reconnected = false; // reconnection both attempted and succeeded?
1274 if ( $ret !== false ) {
1275 $this->lastPing
= $startTime;
1276 if ( $isPermWrite && $this->trxLevel
) {
1277 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1278 $this->trxWriteCallers
[] = $fname;
1280 } elseif ( $this->wasConnectionError( $lastErrno ) ) {
1281 # Check if no meaningful session state was lost
1282 $recoverableCL = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1283 # Update session state tracking and try to restore the connection
1284 $reconnected = $this->replaceLostConnection( __METHOD__
);
1286 # Check if only the last query was rolled back
1287 $recoverableSR = $this->wasKnownStatementRollbackError();
1290 if ( $sql === self
::$PING_QUERY ) {
1291 $this->lastRoundTripEstimate
= $queryRuntime;
1294 $this->trxProfiler
->recordQueryCompletion(
1298 $isPermWrite ?
$this->affectedRows() : $this->numRows( $ret )
1301 // Avoid the overhead of logging calls unless debug mode is enabled
1302 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
1303 $this->queryLogger
->debug(
1304 "{method} [{runtime}s]: $sql",
1307 'db_host' => $this->getServer(),
1308 'domain' => $this->getDomainID(),
1309 'runtime' => round( $queryRuntime, 3 )
1314 return [ $ret, $lastError, $lastErrno, $recoverableSR, $recoverableCL, $reconnected ];
1318 * Start an implicit transaction if DBO_TRX is enabled and no transaction is active
1320 * @param string $sql
1321 * @param string $fname
1323 private function beginIfImplied( $sql, $fname ) {
1326 $this->getFlag( self
::DBO_TRX
) &&
1327 $this->isTransactableQuery( $sql )
1329 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
1330 $this->trxAutomatic
= true;
1335 * Update the estimated run-time of a query, not counting large row lock times
1337 * LoadBalancer can be set to rollback transactions that will create huge replication
1338 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1339 * queries, like inserting a row can take a long time due to row locking. This method
1340 * uses some simple heuristics to discount those cases.
1342 * @param string $sql A SQL write query
1343 * @param float $runtime Total runtime, including RTT
1344 * @param int $affected Affected row count
1346 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1347 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1348 $indicativeOfReplicaRuntime = true;
1349 if ( $runtime > self
::$SLOW_WRITE_SEC ) {
1350 $verb = $this->getQueryVerb( $sql );
1351 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1352 if ( $verb === 'INSERT' ) {
1353 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::$SMALL_WRITE_ROWS;
1354 } elseif ( $verb === 'REPLACE' ) {
1355 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::$SMALL_WRITE_ROWS / 2;
1359 $this->trxWriteDuration +
= $runtime;
1360 $this->trxWriteQueryCount +
= 1;
1361 $this->trxWriteAffectedRows +
= $affected;
1362 if ( $indicativeOfReplicaRuntime ) {
1363 $this->trxWriteAdjDuration +
= $runtime;
1364 $this->trxWriteAdjQueryCount +
= 1;
1369 * Error out if the DB is not in a valid state for a query via query()
1371 * @param string $sql
1372 * @param string $fname
1373 * @throws DBTransactionStateError
1375 private function assertQueryIsCurrentlyAllowed( $sql, $fname ) {
1376 $verb = $this->getQueryVerb( $sql );
1377 if ( $verb === 'USE' ) {
1378 throw new DBUnexpectedError( $this, "Got USE query; use selectDomain() instead." );
1381 if ( $verb === 'ROLLBACK' ) { // transaction/savepoint
1385 if ( $this->trxStatus
< self
::STATUS_TRX_OK
) {
1386 throw new DBTransactionStateError(
1388 "Cannot execute query from $fname while transaction status is ERROR.",
1390 $this->trxStatusCause
1392 } elseif ( $this->trxStatus
=== self
::STATUS_TRX_OK
&& $this->trxStatusIgnoredCause
) {
1393 list( $iLastError, $iLastErrno, $iFname ) = $this->trxStatusIgnoredCause
;
1394 call_user_func( $this->deprecationLogger
,
1395 "Caller from $fname ignored an error originally raised from $iFname: " .
1396 "[$iLastErrno] $iLastError"
1398 $this->trxStatusIgnoredCause
= null;
1402 public function assertNoOpenTransactions() {
1403 if ( $this->explicitTrxActive() ) {
1404 throw new DBTransactionError(
1406 "Explicit transaction still active. A caller may have caught an error. "
1407 . "Open transactions: " . $this->flatAtomicSectionList()
1413 * Determine whether it is safe to retry queries after a database connection is lost
1415 * @param string $sql SQL query
1416 * @param bool $priorWritesPending Whether there is a transaction open with
1417 * possible write queries or transaction pre-commit/idle callbacks
1418 * waiting on it to finish.
1419 * @return bool True if it is safe to retry the query, false otherwise
1421 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1422 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1423 # Dropped connections also mean that named locks are automatically released.
1424 # Only allow error suppression in autocommit mode or when the lost transaction
1425 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1426 if ( $this->sessionNamedLocks
) {
1427 return false; // possible critical section violation
1428 } elseif ( $this->sessionTempTables
) {
1429 return false; // tables might be queried latter
1430 } elseif ( $sql === 'COMMIT' ) {
1431 return !$priorWritesPending; // nothing written anyway? (T127428)
1432 } elseif ( $sql === 'ROLLBACK' ) {
1433 return true; // transaction lost...which is also what was requested :)
1434 } elseif ( $this->explicitTrxActive() ) {
1435 return false; // don't drop atomocity and explicit snapshots
1436 } elseif ( $priorWritesPending ) {
1437 return false; // prior writes lost from implicit transaction
1444 * Clean things up after session (and thus transaction) loss before reconnect
1446 private function handleSessionLossPreconnect() {
1447 // Clean up tracking of session-level things...
1448 // https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
1449 // https://www.postgresql.org/docs/9.2/static/sql-createtable.html (ignoring ON COMMIT)
1450 $this->sessionTempTables
= [];
1451 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1452 // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1453 $this->sessionNamedLocks
= [];
1454 // Session loss implies transaction loss
1455 $this->trxLevel
= 0;
1456 $this->trxAtomicCounter
= 0;
1457 $this->trxIdleCallbacks
= []; // T67263; transaction already lost
1458 $this->trxPreCommitCallbacks
= []; // T67263; transaction already lost
1459 // @note: leave trxRecurringCallbacks in place
1460 if ( $this->trxDoneWrites
) {
1461 $this->trxProfiler
->transactionWritingOut(
1463 $this->getDomainID(),
1465 $this->pendingWriteQueryDuration( self
::ESTIMATE_TOTAL
),
1466 $this->trxWriteAffectedRows
1472 * Clean things up after session (and thus transaction) loss after reconnect
1474 private function handleSessionLossPostconnect() {
1476 // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
1477 // If callback suppression is set then the array will remain unhandled.
1478 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1479 } catch ( Exception
$ex ) {
1480 // Already logged; move on...
1483 // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener()
1484 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1485 } catch ( Exception
$ex ) {
1486 // Already logged; move on...
1491 * Checks whether the cause of the error is detected to be a timeout.
1493 * It returns false by default, and not all engines support detecting this yet.
1494 * If this returns false, it will be treated as a generic query error.
1496 * @param string $error Error text
1497 * @param int $errno Error number
1500 protected function wasQueryTimeout( $error, $errno ) {
1505 * Report a query error. Log the error, and if neither the object ignore
1506 * flag nor the $ignoreErrors flag is set, throw a DBQueryError.
1508 * @param string $error
1510 * @param string $sql
1511 * @param string $fname
1512 * @param bool $ignore
1513 * @throws DBQueryError
1515 public function reportQueryError( $error, $errno, $sql, $fname, $ignore = false ) {
1517 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1519 $exception = $this->getQueryExceptionAndLog( $error, $errno, $sql, $fname );
1526 * @param string $error
1527 * @param string|int $errno
1528 * @param string $sql
1529 * @param string $fname
1532 private function getQueryExceptionAndLog( $error, $errno, $sql, $fname ) {
1533 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1534 $this->queryLogger
->error(
1535 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1536 $this->getLogContext( [
1537 'method' => __METHOD__
,
1540 'sql1line' => $sql1line,
1542 'trace' => ( new RuntimeException() )->getTraceAsString()
1545 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1546 if ( $this->wasQueryTimeout( $error, $errno ) ) {
1547 $e = new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1548 } elseif ( $this->wasConnectionError( $errno ) ) {
1549 $e = new DBQueryDisconnectedError( $this, $error, $errno, $sql, $fname );
1551 $e = new DBQueryError( $this, $error, $errno, $sql, $fname );
1557 public function freeResult( $res ) {
1560 public function selectField(
1561 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1563 if ( $var === '*' ) { // sanity
1564 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1567 if ( !is_array( $options ) ) {
1568 $options = [ $options ];
1571 $options['LIMIT'] = 1;
1573 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1574 if ( $res === false ) {
1575 throw new DBUnexpectedError( $this, "Got false from select()" );
1578 $row = $this->fetchRow( $res );
1579 if ( $row === false ) {
1583 return reset( $row );
1586 public function selectFieldValues(
1587 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1589 if ( $var === '*' ) { // sanity
1590 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1591 } elseif ( !is_string( $var ) ) { // sanity
1592 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1595 if ( !is_array( $options ) ) {
1596 $options = [ $options ];
1599 $res = $this->select( $table, [ 'value' => $var ], $cond, $fname, $options, $join_conds );
1600 if ( $res === false ) {
1601 throw new DBUnexpectedError( $this, "Got false from select()" );
1605 foreach ( $res as $row ) {
1606 $values[] = $row->value
;
1613 * Returns an optional USE INDEX clause to go after the table, and a
1614 * string to go at the end of the query.
1616 * @param array $options Associative array of options to be turned into
1617 * an SQL query, valid keys are listed in the function.
1619 * @see Database::select()
1621 protected function makeSelectOptions( $options ) {
1622 $preLimitTail = $postLimitTail = '';
1627 foreach ( $options as $key => $option ) {
1628 if ( is_numeric( $key ) ) {
1629 $noKeyOptions[$option] = true;
1633 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1635 $preLimitTail .= $this->makeOrderBy( $options );
1637 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1638 $postLimitTail .= ' FOR UPDATE';
1641 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1642 $postLimitTail .= ' LOCK IN SHARE MODE';
1645 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1646 $startOpts .= 'DISTINCT';
1649 # Various MySQL extensions
1650 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1651 $startOpts .= ' /*! STRAIGHT_JOIN */';
1654 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1655 $startOpts .= ' HIGH_PRIORITY';
1658 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1659 $startOpts .= ' SQL_BIG_RESULT';
1662 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1663 $startOpts .= ' SQL_BUFFER_RESULT';
1666 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1667 $startOpts .= ' SQL_SMALL_RESULT';
1670 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1671 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1674 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1675 $startOpts .= ' SQL_CACHE';
1678 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1679 $startOpts .= ' SQL_NO_CACHE';
1682 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1683 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1687 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1688 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1693 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1697 * Returns an optional GROUP BY with an optional HAVING
1699 * @param array $options Associative array of options
1701 * @see Database::select()
1704 protected function makeGroupByWithHaving( $options ) {
1706 if ( isset( $options['GROUP BY'] ) ) {
1707 $gb = is_array( $options['GROUP BY'] )
1708 ?
implode( ',', $options['GROUP BY'] )
1709 : $options['GROUP BY'];
1710 $sql .= ' GROUP BY ' . $gb;
1712 if ( isset( $options['HAVING'] ) ) {
1713 $having = is_array( $options['HAVING'] )
1714 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1715 : $options['HAVING'];
1716 $sql .= ' HAVING ' . $having;
1723 * Returns an optional ORDER BY
1725 * @param array $options Associative array of options
1727 * @see Database::select()
1730 protected function makeOrderBy( $options ) {
1731 if ( isset( $options['ORDER BY'] ) ) {
1732 $ob = is_array( $options['ORDER BY'] )
1733 ?
implode( ',', $options['ORDER BY'] )
1734 : $options['ORDER BY'];
1736 return ' ORDER BY ' . $ob;
1742 public function select(
1743 $table, $vars, $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1745 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1747 return $this->query( $sql, $fname );
1750 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1751 $options = [], $join_conds = []
1753 if ( is_array( $vars ) ) {
1754 $fields = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1759 $options = (array)$options;
1760 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1761 ?
$options['USE INDEX']
1764 isset( $options['IGNORE INDEX'] ) &&
1765 is_array( $options['IGNORE INDEX'] )
1767 ?
$options['IGNORE INDEX']
1771 $this->selectOptionsIncludeLocking( $options ) &&
1772 $this->selectFieldsOrOptionsAggregate( $vars, $options )
1774 // Some DB types (postgres/oracle) disallow FOR UPDATE with aggregate
1775 // functions. Discourage use of such queries to encourage compatibility.
1777 $this->deprecationLogger
,
1778 __METHOD__
. ": aggregation used with a locking SELECT ($fname)."
1782 if ( is_array( $table ) ) {
1784 $this->tableNamesWithIndexClauseOrJOIN(
1785 $table, $useIndexes, $ignoreIndexes, $join_conds );
1786 } elseif ( $table != '' ) {
1788 $this->tableNamesWithIndexClauseOrJOIN(
1789 [ $table ], $useIndexes, $ignoreIndexes, [] );
1794 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1795 $this->makeSelectOptions( $options );
1797 if ( is_array( $conds ) ) {
1798 $conds = $this->makeList( $conds, self
::LIST_AND
);
1801 if ( $conds === null ||
$conds === false ) {
1802 $this->queryLogger
->warning(
1806 . ' with incorrect parameters: $conds must be a string or an array'
1811 if ( $conds === '' ||
$conds === '*' ) {
1812 $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex $preLimitTail";
1813 } elseif ( is_string( $conds ) ) {
1814 $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex " .
1815 "WHERE $conds $preLimitTail";
1817 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1820 if ( isset( $options['LIMIT'] ) ) {
1821 $sql = $this->limitResult( $sql, $options['LIMIT'],
1822 $options['OFFSET'] ??
false );
1824 $sql = "$sql $postLimitTail";
1826 if ( isset( $options['EXPLAIN'] ) ) {
1827 $sql = 'EXPLAIN ' . $sql;
1833 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1834 $options = [], $join_conds = []
1836 $options = (array)$options;
1837 $options['LIMIT'] = 1;
1839 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1840 if ( $res === false ) {
1841 throw new DBUnexpectedError( $this, "Got false from select()" );
1844 if ( !$this->numRows( $res ) ) {
1848 return $this->fetchObject( $res );
1851 public function estimateRowCount(
1852 $table, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1854 $conds = $this->normalizeConditions( $conds, $fname );
1855 $column = $this->extractSingleFieldFromList( $var );
1856 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1857 $conds[] = "$column IS NOT NULL";
1860 $res = $this->select(
1861 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1863 $row = $res ?
$this->fetchRow( $res ) : [];
1865 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1868 public function selectRowCount(
1869 $tables, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1871 $conds = $this->normalizeConditions( $conds, $fname );
1872 $column = $this->extractSingleFieldFromList( $var );
1873 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1874 $conds[] = "$column IS NOT NULL";
1877 $res = $this->select(
1879 'tmp_count' => $this->buildSelectSubquery(
1888 [ 'rowcount' => 'COUNT(*)' ],
1892 $row = $res ?
$this->fetchRow( $res ) : [];
1894 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1898 * @param string|array $options
1901 private function selectOptionsIncludeLocking( $options ) {
1902 $options = (array)$options;
1903 foreach ( [ 'FOR UPDATE', 'LOCK IN SHARE MODE' ] as $lock ) {
1904 if ( in_array( $lock, $options, true ) ) {
1913 * @param array|string $fields
1914 * @param array|string $options
1917 private function selectFieldsOrOptionsAggregate( $fields, $options ) {
1918 foreach ( (array)$options as $key => $value ) {
1919 if ( is_string( $key ) ) {
1920 if ( preg_match( '/^(?:GROUP BY|HAVING)$/i', $key ) ) {
1923 } elseif ( is_string( $value ) ) {
1924 if ( preg_match( '/^(?:DISTINCT|DISTINCTROW)$/i', $value ) ) {
1930 $regex = '/^(?:COUNT|MIN|MAX|SUM|GROUP_CONCAT|LISTAGG|ARRAY_AGG)\s*\\(/i';
1931 foreach ( (array)$fields as $field ) {
1932 if ( is_string( $field ) && preg_match( $regex, $field ) ) {
1941 * @param array|string $conds
1942 * @param string $fname
1945 final protected function normalizeConditions( $conds, $fname ) {
1946 if ( $conds === null ||
$conds === false ) {
1947 $this->queryLogger
->warning(
1951 . ' with incorrect parameters: $conds must be a string or an array'
1956 if ( !is_array( $conds ) ) {
1957 $conds = ( $conds === '' ) ?
[] : [ $conds ];
1964 * @param array|string $var Field parameter in the style of select()
1965 * @return string|null Column name or null; ignores aliases
1966 * @throws DBUnexpectedError Errors out if multiple columns are given
1968 final protected function extractSingleFieldFromList( $var ) {
1969 if ( is_array( $var ) ) {
1972 } elseif ( count( $var ) == 1 ) {
1973 $column = $var[0] ??
reset( $var );
1975 throw new DBUnexpectedError( $this, __METHOD__
. ': got multiple columns.' );
1984 public function lockForUpdate(
1985 $table, $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1987 if ( !$this->trxLevel
&& !$this->getFlag( self
::DBO_TRX
) ) {
1988 throw new DBUnexpectedError(
1990 __METHOD__
. ': no transaction is active nor is DBO_TRX set'
1994 $options = (array)$options;
1995 $options[] = 'FOR UPDATE';
1997 return $this->selectRowCount( $table, '*', $conds, $fname, $options, $join_conds );
2000 public function fieldExists( $table, $field, $fname = __METHOD__
) {
2001 $info = $this->fieldInfo( $table, $field );
2006 public function indexExists( $table, $index, $fname = __METHOD__
) {
2007 if ( !$this->tableExists( $table ) ) {
2011 $info = $this->indexInfo( $table, $index, $fname );
2012 if ( is_null( $info ) ) {
2015 return $info !== false;
2019 abstract public function tableExists( $table, $fname = __METHOD__
);
2021 public function indexUnique( $table, $index ) {
2022 $indexInfo = $this->indexInfo( $table, $index );
2024 if ( !$indexInfo ) {
2028 return !$indexInfo[0]->Non_unique
;
2032 * Helper for Database::insert().
2034 * @param array $options
2037 protected function makeInsertOptions( $options ) {
2038 return implode( ' ', $options );
2041 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
2042 # No rows to insert, easy just return now
2043 if ( !count( $a ) ) {
2047 $table = $this->tableName( $table );
2049 if ( !is_array( $options ) ) {
2050 $options = [ $options ];
2053 $options = $this->makeInsertOptions( $options );
2055 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
2057 $keys = array_keys( $a[0] );
2060 $keys = array_keys( $a );
2063 $sql = 'INSERT ' . $options .
2064 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
2068 foreach ( $a as $row ) {
2074 $sql .= '(' . $this->makeList( $row ) . ')';
2077 $sql .= '(' . $this->makeList( $a ) . ')';
2080 $this->query( $sql, $fname );
2086 * Make UPDATE options array for Database::makeUpdateOptions
2088 * @param array $options
2091 protected function makeUpdateOptionsArray( $options ) {
2092 if ( !is_array( $options ) ) {
2093 $options = [ $options ];
2098 if ( in_array( 'IGNORE', $options ) ) {
2106 * Make UPDATE options for the Database::update function
2108 * @param array $options The options passed to Database::update
2111 protected function makeUpdateOptions( $options ) {
2112 $opts = $this->makeUpdateOptionsArray( $options );
2114 return implode( ' ', $opts );
2117 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
2118 $table = $this->tableName( $table );
2119 $opts = $this->makeUpdateOptions( $options );
2120 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
2122 if ( $conds !== [] && $conds !== '*' ) {
2123 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
2126 $this->query( $sql, $fname );
2131 public function makeList( $a, $mode = self
::LIST_COMMA
) {
2132 if ( !is_array( $a ) ) {
2133 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
2139 foreach ( $a as $field => $value ) {
2141 if ( $mode == self
::LIST_AND
) {
2143 } elseif ( $mode == self
::LIST_OR
) {
2152 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
2153 $list .= "($value)";
2154 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
2157 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
2159 // Remove null from array to be handled separately if found
2160 $includeNull = false;
2161 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2162 $includeNull = true;
2163 unset( $value[$nullKey] );
2165 if ( count( $value ) == 0 && !$includeNull ) {
2166 throw new InvalidArgumentException(
2167 __METHOD__
. ": empty input for field $field" );
2168 } elseif ( count( $value ) == 0 ) {
2169 // only check if $field is null
2170 $list .= "$field IS NULL";
2172 // IN clause contains at least one valid element
2173 if ( $includeNull ) {
2174 // Group subconditions to ensure correct precedence
2177 if ( count( $value ) == 1 ) {
2178 // Special-case single values, as IN isn't terribly efficient
2179 // Don't necessarily assume the single key is 0; we don't
2180 // enforce linear numeric ordering on other arrays here.
2181 $value = array_values( $value )[0];
2182 $list .= $field . " = " . $this->addQuotes( $value );
2184 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2186 // if null present in array, append IS NULL
2187 if ( $includeNull ) {
2188 $list .= " OR $field IS NULL)";
2191 } elseif ( $value === null ) {
2192 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
2193 $list .= "$field IS ";
2194 } elseif ( $mode == self
::LIST_SET
) {
2195 $list .= "$field = ";
2200 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
2202 $list .= "$field = ";
2204 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
2211 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2214 foreach ( $data as $base => $sub ) {
2215 if ( count( $sub ) ) {
2216 $conds[] = $this->makeList(
2217 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
2223 return $this->makeList( $conds, self
::LIST_OR
);
2225 // Nothing to search for...
2230 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2234 public function bitNot( $field ) {
2238 public function bitAnd( $fieldLeft, $fieldRight ) {
2239 return "($fieldLeft & $fieldRight)";
2242 public function bitOr( $fieldLeft, $fieldRight ) {
2243 return "($fieldLeft | $fieldRight)";
2246 public function buildConcat( $stringList ) {
2247 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2250 public function buildGroupConcatField(
2251 $delim, $table, $field, $conds = '', $join_conds = []
2253 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2255 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
2258 public function buildSubstring( $input, $startPosition, $length = null ) {
2259 $this->assertBuildSubstringParams( $startPosition, $length );
2260 $functionBody = "$input FROM $startPosition";
2261 if ( $length !== null ) {
2262 $functionBody .= " FOR $length";
2264 return 'SUBSTRING(' . $functionBody . ')';
2268 * Check type and bounds for parameters to self::buildSubstring()
2270 * All supported databases have substring functions that behave the same for
2271 * positive $startPosition and non-negative $length, but behaviors differ when
2272 * given 0 or negative $startPosition or negative $length. The simplest
2273 * solution to that is to just forbid those values.
2275 * @param int $startPosition
2276 * @param int|null $length
2279 protected function assertBuildSubstringParams( $startPosition, $length ) {
2280 if ( !is_int( $startPosition ) ||
$startPosition <= 0 ) {
2281 throw new InvalidArgumentException(
2282 '$startPosition must be a positive integer'
2285 if ( !( is_int( $length ) && $length >= 0 ||
$length === null ) ) {
2286 throw new InvalidArgumentException(
2287 '$length must be null or an integer greater than or equal to 0'
2292 public function buildStringCast( $field ) {
2293 // In theory this should work for any standards-compliant
2294 // SQL implementation, although it may not be the best way to do it.
2295 return "CAST( $field AS CHARACTER )";
2298 public function buildIntegerCast( $field ) {
2299 return 'CAST( ' . $field . ' AS INTEGER )';
2302 public function buildSelectSubquery(
2303 $table, $vars, $conds = '', $fname = __METHOD__
,
2304 $options = [], $join_conds = []
2306 return new Subquery(
2307 $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2311 public function databasesAreIndependent() {
2315 final public function selectDB( $db ) {
2316 $this->selectDomain( new DatabaseDomain(
2318 $this->currentDomain
->getSchema(),
2319 $this->currentDomain
->getTablePrefix()
2325 final public function selectDomain( $domain ) {
2326 $this->doSelectDomain( DatabaseDomain
::newFromId( $domain ) );
2329 protected function doSelectDomain( DatabaseDomain
$domain ) {
2330 $this->currentDomain
= $domain;
2333 public function getDBname() {
2334 return $this->currentDomain
->getDatabase();
2337 public function getServer() {
2338 return $this->server
;
2341 public function tableName( $name, $format = 'quoted' ) {
2342 if ( $name instanceof Subquery
) {
2343 throw new DBUnexpectedError(
2345 __METHOD__
. ': got Subquery instance when expecting a string.'
2349 # Skip the entire process when we have a string quoted on both ends.
2350 # Note that we check the end so that we will still quote any use of
2351 # use of `database`.table. But won't break things if someone wants
2352 # to query a database table with a dot in the name.
2353 if ( $this->isQuotedIdentifier( $name ) ) {
2357 # Lets test for any bits of text that should never show up in a table
2358 # name. Basically anything like JOIN or ON which are actually part of
2359 # SQL queries, but may end up inside of the table value to combine
2360 # sql. Such as how the API is doing.
2361 # Note that we use a whitespace test rather than a \b test to avoid
2362 # any remote case where a word like on may be inside of a table name
2363 # surrounded by symbols which may be considered word breaks.
2364 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2365 $this->queryLogger
->warning(
2366 __METHOD__
. ": use of subqueries is not supported this way.",
2367 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
2373 # Split database and table into proper variables.
2374 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2376 # Quote $table and apply the prefix if not quoted.
2377 # $tableName might be empty if this is called from Database::replaceVars()
2378 $tableName = "{$prefix}{$table}";
2379 if ( $format === 'quoted'
2380 && !$this->isQuotedIdentifier( $tableName )
2381 && $tableName !== ''
2383 $tableName = $this->addIdentifierQuotes( $tableName );
2386 # Quote $schema and $database and merge them with the table name if needed
2387 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2388 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2394 * Get the table components needed for a query given the currently selected database
2396 * @param string $name Table name in the form of db.schema.table, db.table, or table
2397 * @return array (DB name or "" for default, schema name, table prefix, table name)
2399 protected function qualifiedTableComponents( $name ) {
2400 # We reverse the explode so that database.table and table both output the correct table.
2401 $dbDetails = explode( '.', $name, 3 );
2402 if ( count( $dbDetails ) == 3 ) {
2403 list( $database, $schema, $table ) = $dbDetails;
2404 # We don't want any prefix added in this case
2406 } elseif ( count( $dbDetails ) == 2 ) {
2407 list( $database, $table ) = $dbDetails;
2408 # We don't want any prefix added in this case
2410 # In dbs that support it, $database may actually be the schema
2411 # but that doesn't affect any of the functionality here
2414 list( $table ) = $dbDetails;
2415 if ( isset( $this->tableAliases
[$table] ) ) {
2416 $database = $this->tableAliases
[$table]['dbname'];
2417 $schema = is_string( $this->tableAliases
[$table]['schema'] )
2418 ?
$this->tableAliases
[$table]['schema']
2419 : $this->relationSchemaQualifier();
2420 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
2421 ?
$this->tableAliases
[$table]['prefix']
2422 : $this->tablePrefix();
2425 $schema = $this->relationSchemaQualifier(); # Default schema
2426 $prefix = $this->tablePrefix(); # Default prefix
2430 return [ $database, $schema, $prefix, $table ];
2434 * @param string|null $namespace Database or schema
2435 * @param string $relation Name of table, view, sequence, etc...
2436 * @param string $format One of (raw, quoted)
2437 * @return string Relation name with quoted and merged $namespace as needed
2439 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2440 if ( strlen( $namespace ) ) {
2441 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2442 $namespace = $this->addIdentifierQuotes( $namespace );
2444 $relation = $namespace . '.' . $relation;
2450 public function tableNames() {
2451 $inArray = func_get_args();
2454 foreach ( $inArray as $name ) {
2455 $retVal[$name] = $this->tableName( $name );
2461 public function tableNamesN() {
2462 $inArray = func_get_args();
2465 foreach ( $inArray as $name ) {
2466 $retVal[] = $this->tableName( $name );
2473 * Get an aliased table name
2475 * This returns strings like "tableName AS newTableName" for aliased tables
2476 * and "(SELECT * from tableA) newTablename" for subqueries (e.g. derived tables)
2478 * @see Database::tableName()
2479 * @param string|Subquery $table Table name or object with a 'sql' field
2480 * @param string|bool $alias Table alias (optional)
2481 * @return string SQL name for aliased table. Will not alias a table to its own name
2483 protected function tableNameWithAlias( $table, $alias = false ) {
2484 if ( is_string( $table ) ) {
2485 $quotedTable = $this->tableName( $table );
2486 } elseif ( $table instanceof Subquery
) {
2487 $quotedTable = (string)$table;
2489 throw new InvalidArgumentException( "Table must be a string or Subquery." );
2492 if ( $alias === false ||
$alias === $table ) {
2493 if ( $table instanceof Subquery
) {
2494 throw new InvalidArgumentException( "Subquery table missing alias." );
2497 return $quotedTable;
2499 return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2504 * Gets an array of aliased table names
2506 * @param array $tables [ [alias] => table ]
2507 * @return string[] See tableNameWithAlias()
2509 protected function tableNamesWithAlias( $tables ) {
2511 foreach ( $tables as $alias => $table ) {
2512 if ( is_numeric( $alias ) ) {
2515 $retval[] = $this->tableNameWithAlias( $table, $alias );
2522 * Get an aliased field name
2523 * e.g. fieldName AS newFieldName
2525 * @param string $name Field name
2526 * @param string|bool $alias Alias (optional)
2527 * @return string SQL name for aliased field. Will not alias a field to its own name
2529 protected function fieldNameWithAlias( $name, $alias = false ) {
2530 if ( !$alias ||
(string)$alias === (string)$name ) {
2533 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2538 * Gets an array of aliased field names
2540 * @param array $fields [ [alias] => field ]
2541 * @return string[] See fieldNameWithAlias()
2543 protected function fieldNamesWithAlias( $fields ) {
2545 foreach ( $fields as $alias => $field ) {
2546 if ( is_numeric( $alias ) ) {
2549 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2556 * Get the aliased table name clause for a FROM clause
2557 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2559 * @param array $tables ( [alias] => table )
2560 * @param array $use_index Same as for select()
2561 * @param array $ignore_index Same as for select()
2562 * @param array $join_conds Same as for select()
2565 protected function tableNamesWithIndexClauseOrJOIN(
2566 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2570 $use_index = (array)$use_index;
2571 $ignore_index = (array)$ignore_index;
2572 $join_conds = (array)$join_conds;
2574 foreach ( $tables as $alias => $table ) {
2575 if ( !is_string( $alias ) ) {
2576 // No alias? Set it equal to the table name
2580 if ( is_array( $table ) ) {
2581 // A parenthesized group
2582 if ( count( $table ) > 1 ) {
2583 $joinedTable = '(' .
2584 $this->tableNamesWithIndexClauseOrJOIN(
2585 $table, $use_index, $ignore_index, $join_conds ) . ')';
2588 $innerTable = reset( $table );
2589 $innerAlias = key( $table );
2590 $joinedTable = $this->tableNameWithAlias(
2592 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2596 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2599 // Is there a JOIN clause for this table?
2600 if ( isset( $join_conds[$alias] ) ) {
2601 list( $joinType, $conds ) = $join_conds[$alias];
2602 $tableClause = $joinType;
2603 $tableClause .= ' ' . $joinedTable;
2604 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2605 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2607 $tableClause .= ' ' . $use;
2610 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2611 $ignore = $this->ignoreIndexClause(
2612 implode( ',', (array)$ignore_index[$alias] ) );
2613 if ( $ignore != '' ) {
2614 $tableClause .= ' ' . $ignore;
2617 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2619 $tableClause .= ' ON (' . $on . ')';
2622 $retJOIN[] = $tableClause;
2623 } elseif ( isset( $use_index[$alias] ) ) {
2624 // Is there an INDEX clause for this table?
2625 $tableClause = $joinedTable;
2626 $tableClause .= ' ' . $this->useIndexClause(
2627 implode( ',', (array)$use_index[$alias] )
2630 $ret[] = $tableClause;
2631 } elseif ( isset( $ignore_index[$alias] ) ) {
2632 // Is there an INDEX clause for this table?
2633 $tableClause = $joinedTable;
2634 $tableClause .= ' ' . $this->ignoreIndexClause(
2635 implode( ',', (array)$ignore_index[$alias] )
2638 $ret[] = $tableClause;
2640 $tableClause = $joinedTable;
2642 $ret[] = $tableClause;
2646 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2647 $implicitJoins = implode( ',', $ret );
2648 $explicitJoins = implode( ' ', $retJOIN );
2650 // Compile our final table clause
2651 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2655 * Allows for index remapping in queries where this is not consistent across DBMS
2657 * @param string $index
2660 protected function indexName( $index ) {
2661 return $this->indexAliases
[$index] ??
$index;
2664 public function addQuotes( $s ) {
2665 if ( $s instanceof Blob
) {
2668 if ( $s === null ) {
2670 } elseif ( is_bool( $s ) ) {
2673 # This will also quote numeric values. This should be harmless,
2674 # and protects against weird problems that occur when they really
2675 # _are_ strings such as article titles and string->number->string
2676 # conversion is not 1:1.
2677 return "'" . $this->strencode( $s ) . "'";
2681 public function addIdentifierQuotes( $s ) {
2682 return '"' . str_replace( '"', '""', $s ) . '"';
2686 * Returns if the given identifier looks quoted or not according to
2687 * the database convention for quoting identifiers .
2689 * @note Do not use this to determine if untrusted input is safe.
2690 * A malicious user can trick this function.
2691 * @param string $name
2694 public function isQuotedIdentifier( $name ) {
2695 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2700 * @param string $escapeChar
2703 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2704 return str_replace( [ $escapeChar, '%', '_' ],
2705 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2709 public function buildLike( $param, ...$params ) {
2710 if ( is_array( $param ) ) {
2713 $params = func_get_args();
2718 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2719 // may escape backslashes, creating problems of double escaping. The `
2720 // character has good cross-DBMS compatibility, avoiding special operators
2721 // in MS SQL like ^ and %
2724 foreach ( $params as $value ) {
2725 if ( $value instanceof LikeMatch
) {
2726 $s .= $value->toString();
2728 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2733 $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2736 public function anyChar() {
2737 return new LikeMatch( '_' );
2740 public function anyString() {
2741 return new LikeMatch( '%' );
2744 public function nextSequenceValue( $seqName ) {
2749 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2750 * is only needed because a) MySQL must be as efficient as possible due to
2751 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2752 * which index to pick. Anyway, other databases might have different
2753 * indexes on a given table. So don't bother overriding this unless you're
2755 * @param string $index
2758 public function useIndexClause( $index ) {
2763 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2764 * is only needed because a) MySQL must be as efficient as possible due to
2765 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2766 * which index to pick. Anyway, other databases might have different
2767 * indexes on a given table. So don't bother overriding this unless you're
2769 * @param string $index
2772 public function ignoreIndexClause( $index ) {
2776 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2777 if ( count( $rows ) == 0 ) {
2781 $uniqueIndexes = (array)$uniqueIndexes;
2783 if ( !is_array( reset( $rows ) ) ) {
2788 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2789 $affectedRowCount = 0;
2790 foreach ( $rows as $row ) {
2791 // Delete rows which collide with this one
2792 $indexWhereClauses = [];
2793 foreach ( $uniqueIndexes as $index ) {
2794 $indexColumns = (array)$index;
2795 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2796 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2797 throw new DBUnexpectedError(
2799 'New record does not provide all values for unique key (' .
2800 implode( ', ', $indexColumns ) . ')'
2802 } elseif ( in_array( null, $indexRowValues, true ) ) {
2803 throw new DBUnexpectedError(
2805 'New record has a null value for unique key (' .
2806 implode( ', ', $indexColumns ) . ')'
2809 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2812 if ( $indexWhereClauses ) {
2813 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2814 $affectedRowCount +
= $this->affectedRows();
2817 // Now insert the row
2818 $this->insert( $table, $row, $fname );
2819 $affectedRowCount +
= $this->affectedRows();
2821 $this->endAtomic( $fname );
2822 $this->affectedRowCount
= $affectedRowCount;
2823 } catch ( Exception
$e ) {
2824 $this->cancelAtomic( $fname );
2830 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2833 * @param string $table Table name
2834 * @param array|string $rows Row(s) to insert
2835 * @param string $fname Caller function name
2837 protected function nativeReplace( $table, $rows, $fname ) {
2838 $table = $this->tableName( $table );
2841 if ( !is_array( reset( $rows ) ) ) {
2845 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2848 foreach ( $rows as $row ) {
2855 $sql .= '(' . $this->makeList( $row ) . ')';
2858 $this->query( $sql, $fname );
2861 public function upsert( $table, array $rows, $uniqueIndexes, array $set,
2864 if ( $rows === [] ) {
2865 return true; // nothing to do
2868 $uniqueIndexes = (array)$uniqueIndexes;
2869 if ( !is_array( reset( $rows ) ) ) {
2873 if ( count( $uniqueIndexes ) ) {
2874 $clauses = []; // list WHERE clauses that each identify a single row
2875 foreach ( $rows as $row ) {
2876 foreach ( $uniqueIndexes as $index ) {
2877 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2878 $rowKey = []; // unique key to this row
2879 foreach ( $index as $column ) {
2880 $rowKey[$column] = $row[$column];
2882 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2885 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2890 $affectedRowCount = 0;
2892 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2893 # Update any existing conflicting row(s)
2894 if ( $where !== false ) {
2895 $this->update( $table, $set, $where, $fname );
2896 $affectedRowCount +
= $this->affectedRows();
2898 # Now insert any non-conflicting row(s)
2899 $this->insert( $table, $rows, $fname, [ 'IGNORE' ] );
2900 $affectedRowCount +
= $this->affectedRows();
2901 $this->endAtomic( $fname );
2902 $this->affectedRowCount
= $affectedRowCount;
2903 } catch ( Exception
$e ) {
2904 $this->cancelAtomic( $fname );
2911 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2915 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2918 $delTable = $this->tableName( $delTable );
2919 $joinTable = $this->tableName( $joinTable );
2920 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2921 if ( $conds != '*' ) {
2922 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2926 $this->query( $sql, $fname );
2929 public function textFieldSize( $table, $field ) {
2930 $table = $this->tableName( $table );
2931 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\"";
2932 $res = $this->query( $sql, __METHOD__
);
2933 $row = $this->fetchObject( $res );
2937 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2946 public function delete( $table, $conds, $fname = __METHOD__
) {
2948 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2951 $table = $this->tableName( $table );
2952 $sql = "DELETE FROM $table";
2954 if ( $conds != '*' ) {
2955 if ( is_array( $conds ) ) {
2956 $conds = $this->makeList( $conds, self
::LIST_AND
);
2958 $sql .= ' WHERE ' . $conds;
2961 $this->query( $sql, $fname );
2966 final public function insertSelect(
2967 $destTable, $srcTable, $varMap, $conds,
2968 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2970 static $hints = [ 'NO_AUTO_COLUMNS' ];
2972 $insertOptions = (array)$insertOptions;
2973 $selectOptions = (array)$selectOptions;
2975 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
2976 // For massive migrations with downtime, we don't want to select everything
2977 // into memory and OOM, so do all this native on the server side if possible.
2978 $this->nativeInsertSelect(
2984 array_diff( $insertOptions, $hints ),
2989 $this->nonNativeInsertSelect(
2995 array_diff( $insertOptions, $hints ),
3005 * @param array $insertOptions INSERT options
3006 * @param array $selectOptions SELECT options
3007 * @return bool Whether an INSERT SELECT with these options will be replication safe
3010 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
3015 * Implementation of insertSelect() based on select() and insert()
3017 * @see IDatabase::insertSelect()
3019 * @param string $destTable
3020 * @param string|array $srcTable
3021 * @param array $varMap
3022 * @param array $conds
3023 * @param string $fname
3024 * @param array $insertOptions
3025 * @param array $selectOptions
3026 * @param array $selectJoinConds
3028 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3029 $fname = __METHOD__
,
3030 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3032 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
3033 // on only the master (without needing row-based-replication). It also makes it easy to
3034 // know how big the INSERT is going to be.
3036 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
3037 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
3039 $selectOptions[] = 'FOR UPDATE';
3040 $res = $this->select(
3041 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
3048 $affectedRowCount = 0;
3049 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
3052 foreach ( $res as $row ) {
3053 $rows[] = (array)$row;
3055 // Avoid inserts that are too huge
3056 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
3057 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
3061 $affectedRowCount +
= $this->affectedRows();
3065 if ( $rows && $ok ) {
3066 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
3068 $affectedRowCount +
= $this->affectedRows();
3072 $this->endAtomic( $fname );
3073 $this->affectedRowCount
= $affectedRowCount;
3075 $this->cancelAtomic( $fname );
3077 } catch ( Exception
$e ) {
3078 $this->cancelAtomic( $fname );
3084 * Native server-side implementation of insertSelect() for situations where
3085 * we don't want to select everything into memory
3087 * @see IDatabase::insertSelect()
3088 * @param string $destTable
3089 * @param string|array $srcTable
3090 * @param array $varMap
3091 * @param array $conds
3092 * @param string $fname
3093 * @param array $insertOptions
3094 * @param array $selectOptions
3095 * @param array $selectJoinConds
3097 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3098 $fname = __METHOD__
,
3099 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3101 $destTable = $this->tableName( $destTable );
3103 if ( !is_array( $insertOptions ) ) {
3104 $insertOptions = [ $insertOptions ];
3107 $insertOptions = $this->makeInsertOptions( $insertOptions );
3109 $selectSql = $this->selectSQLText(
3111 array_values( $varMap ),
3118 $sql = "INSERT $insertOptions" .
3119 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
3122 $this->query( $sql, $fname );
3125 public function limitResult( $sql, $limit, $offset = false ) {
3126 if ( !is_numeric( $limit ) ) {
3127 throw new DBUnexpectedError( $this,
3128 "Invalid non-numeric limit passed to limitResult()\n" );
3130 // This version works in MySQL and SQLite. It will very likely need to be
3131 // overridden for most other RDBMS subclasses.
3132 return "$sql LIMIT "
3133 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3137 public function unionSupportsOrderAndLimit() {
3138 return true; // True for almost every DB supported
3141 public function unionQueries( $sqls, $all ) {
3142 $glue = $all ?
') UNION ALL (' : ') UNION (';
3144 return '(' . implode( $glue, $sqls ) . ')';
3147 public function unionConditionPermutations(
3148 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
3149 $options = [], $join_conds = []
3151 // First, build the Cartesian product of $permute_conds
3153 foreach ( $permute_conds as $field => $values ) {
3155 // Skip empty $values
3158 $values = array_unique( $values ); // For sanity
3160 foreach ( $conds as $cond ) {
3161 foreach ( $values as $value ) {
3162 $cond[$field] = $value;
3163 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
3169 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
3171 // If there's just one condition and no subordering, hand off to
3172 // selectSQLText directly.
3173 if ( count( $conds ) === 1 &&
3174 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
3176 return $this->selectSQLText(
3177 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
3181 // Otherwise, we need to pull out the order and limit to apply after
3182 // the union. Then build the SQL queries for each set of conditions in
3183 // $conds. Then union them together (using UNION ALL, because the
3184 // product *should* already be distinct).
3185 $orderBy = $this->makeOrderBy( $options );
3186 $limit = $options['LIMIT'] ??
null;
3187 $offset = $options['OFFSET'] ??
false;
3188 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
3189 if ( !$this->unionSupportsOrderAndLimit() ) {
3190 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
3192 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
3193 $options['ORDER BY'] = $options['INNER ORDER BY'];
3195 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
3196 // We need to increase the limit by the offset rather than
3197 // using the offset directly, otherwise it'll skip incorrectly
3198 // in the subqueries.
3199 $options['LIMIT'] = $limit +
$offset;
3200 unset( $options['OFFSET'] );
3205 foreach ( $conds as $cond ) {
3206 $sqls[] = $this->selectSQLText(
3207 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
3210 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
3211 if ( $limit !== null ) {
3212 $sql = $this->limitResult( $sql, $limit, $offset );
3218 public function conditional( $cond, $trueVal, $falseVal ) {
3219 if ( is_array( $cond ) ) {
3220 $cond = $this->makeList( $cond, self
::LIST_AND
);
3223 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3226 public function strreplace( $orig, $old, $new ) {
3227 return "REPLACE({$orig}, {$old}, {$new})";
3230 public function getServerUptime() {
3234 public function wasDeadlock() {
3238 public function wasLockTimeout() {
3242 public function wasConnectionLoss() {
3243 return $this->wasConnectionError( $this->lastErrno() );
3246 public function wasReadOnlyError() {
3250 public function wasErrorReissuable() {
3252 $this->wasDeadlock() ||
3253 $this->wasLockTimeout() ||
3254 $this->wasConnectionLoss()
3259 * Do not use this method outside of Database/DBError classes
3261 * @param int|string $errno
3262 * @return bool Whether the given query error was a connection drop
3264 public function wasConnectionError( $errno ) {
3269 * @return bool Whether it is known that the last query error only caused statement rollback
3270 * @note This is for backwards compatibility for callers catching DBError exceptions in
3271 * order to ignore problems like duplicate key errors or foriegn key violations
3274 protected function wasKnownStatementRollbackError() {
3275 return false; // don't know; it could have caused a transaction rollback
3278 public function deadlockLoop() {
3279 $args = func_get_args();
3280 $function = array_shift( $args );
3281 $tries = self
::$DEADLOCK_TRIES;
3283 $this->begin( __METHOD__
);
3286 /** @var Exception $e */
3290 $retVal = $function( ...$args );
3292 } catch ( DBQueryError
$e ) {
3293 if ( $this->wasDeadlock() ) {
3294 // Retry after a randomized delay
3295 usleep( mt_rand( self
::$DEADLOCK_DELAY_MIN, self
::$DEADLOCK_DELAY_MAX ) );
3297 // Throw the error back up
3301 } while ( --$tries > 0 );
3303 if ( $tries <= 0 ) {
3304 // Too many deadlocks; give up
3305 $this->rollback( __METHOD__
);
3308 $this->commit( __METHOD__
);
3314 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3315 # Real waits are implemented in the subclass.
3319 public function getReplicaPos() {
3324 public function getMasterPos() {
3329 public function serverIsReadOnly() {
3333 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
3334 if ( !$this->trxLevel
) {
3335 throw new DBUnexpectedError( $this, "No transaction is active." );
3337 $this->trxEndCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3340 final public function onTransactionCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3341 if ( !$this->trxLevel
&& $this->getTransactionRoundId() ) {
3342 // Start an implicit transaction similar to how query() does
3343 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3344 $this->trxAutomatic
= true;
3347 $this->trxIdleCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3348 if ( !$this->trxLevel
) {
3349 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
3353 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
3354 $this->onTransactionCommitOrIdle( $callback, $fname );
3357 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3358 if ( !$this->trxLevel
&& $this->getTransactionRoundId() ) {
3359 // Start an implicit transaction similar to how query() does
3360 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3361 $this->trxAutomatic
= true;
3364 if ( $this->trxLevel
) {
3365 $this->trxPreCommitCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3367 // No transaction is active nor will start implicitly, so make one for this callback
3368 $this->startAtomic( __METHOD__
, self
::ATOMIC_CANCELABLE
);
3371 $this->endAtomic( __METHOD__
);
3372 } catch ( Exception
$e ) {
3373 $this->cancelAtomic( __METHOD__
);
3380 * @return AtomicSectionIdentifier|null ID of the topmost atomic section level
3382 private function currentAtomicSectionId() {
3383 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3384 $levelInfo = end( $this->trxAtomicLevels
);
3386 return $levelInfo[1];
3393 * @param AtomicSectionIdentifier $old
3394 * @param AtomicSectionIdentifier $new
3396 private function reassignCallbacksForSection(
3397 AtomicSectionIdentifier
$old, AtomicSectionIdentifier
$new
3399 foreach ( $this->trxPreCommitCallbacks
as $key => $info ) {
3400 if ( $info[2] === $old ) {
3401 $this->trxPreCommitCallbacks
[$key][2] = $new;
3404 foreach ( $this->trxIdleCallbacks
as $key => $info ) {
3405 if ( $info[2] === $old ) {
3406 $this->trxIdleCallbacks
[$key][2] = $new;
3409 foreach ( $this->trxEndCallbacks
as $key => $info ) {
3410 if ( $info[2] === $old ) {
3411 $this->trxEndCallbacks
[$key][2] = $new;
3417 * @param AtomicSectionIdentifier[] $sectionIds ID of an actual savepoint
3418 * @throws UnexpectedValueException
3420 private function modifyCallbacksForCancel( array $sectionIds ) {
3421 // Cancel the "on commit" callbacks owned by this savepoint
3422 $this->trxIdleCallbacks
= array_filter(
3423 $this->trxIdleCallbacks
,
3424 function ( $entry ) use ( $sectionIds ) {
3425 return !in_array( $entry[2], $sectionIds, true );
3428 $this->trxPreCommitCallbacks
= array_filter(
3429 $this->trxPreCommitCallbacks
,
3430 function ( $entry ) use ( $sectionIds ) {
3431 return !in_array( $entry[2], $sectionIds, true );
3434 // Make "on resolution" callbacks owned by this savepoint to perceive a rollback
3435 foreach ( $this->trxEndCallbacks
as $key => $entry ) {
3436 if ( in_array( $entry[2], $sectionIds, true ) ) {
3437 $callback = $entry[0];
3438 $this->trxEndCallbacks
[$key][0] = function () use ( $callback ) {
3439 return $callback( self
::TRIGGER_ROLLBACK
, $this );
3445 final public function setTransactionListener( $name, callable
$callback = null ) {
3447 $this->trxRecurringCallbacks
[$name] = $callback;
3449 unset( $this->trxRecurringCallbacks
[$name] );
3454 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
3456 * This method should not be used outside of Database/LoadBalancer
3458 * @param bool $suppress
3461 final public function setTrxEndCallbackSuppression( $suppress ) {
3462 $this->trxEndCallbacksSuppressed
= $suppress;
3466 * Actually consume and run any "on transaction idle/resolution" callbacks.
3468 * This method should not be used outside of Database/LoadBalancer
3470 * @param int $trigger IDatabase::TRIGGER_* constant
3471 * @return int Number of callbacks attempted
3475 public function runOnTransactionIdleCallbacks( $trigger ) {
3476 if ( $this->trxLevel
) { // sanity
3477 throw new DBUnexpectedError( $this, __METHOD__
. ': a transaction is still open.' );
3480 if ( $this->trxEndCallbacksSuppressed
) {
3485 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
3486 /** @var Exception $e */
3487 $e = null; // first exception
3488 do { // callbacks may add callbacks :)
3489 $callbacks = array_merge(
3490 $this->trxIdleCallbacks
,
3491 $this->trxEndCallbacks
// include "transaction resolution" callbacks
3493 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
3494 $this->trxEndCallbacks
= []; // consumed (recursion guard)
3495 foreach ( $callbacks as $callback ) {
3497 list( $phpCallback ) = $callback;
3498 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
3500 // @phan-suppress-next-line PhanParamTooManyCallable
3501 call_user_func( $phpCallback, $trigger, $this );
3502 } catch ( Exception
$ex ) {
3503 call_user_func( $this->errorLogger
, $ex );
3505 // Some callbacks may use startAtomic/endAtomic, so make sure
3506 // their transactions are ended so other callbacks don't fail
3507 if ( $this->trxLevel() ) {
3508 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3512 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
3514 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
3518 } while ( count( $this->trxIdleCallbacks
) );
3520 if ( $e instanceof Exception
) {
3521 throw $e; // re-throw any first exception
3528 * Actually consume and run any "on transaction pre-commit" callbacks.
3530 * This method should not be used outside of Database/LoadBalancer
3533 * @return int Number of callbacks attempted
3536 public function runOnTransactionPreCommitCallbacks() {
3539 $e = null; // first exception
3540 do { // callbacks may add callbacks :)
3541 $callbacks = $this->trxPreCommitCallbacks
;
3542 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
3543 foreach ( $callbacks as $callback ) {
3546 list( $phpCallback ) = $callback;
3547 $phpCallback( $this );
3548 } catch ( Exception
$ex ) {
3549 ( $this->errorLogger
)( $ex );
3553 } while ( count( $this->trxPreCommitCallbacks
) );
3555 if ( $e instanceof Exception
) {
3556 throw $e; // re-throw any first exception
3563 * Actually run any "transaction listener" callbacks.
3565 * This method should not be used outside of Database/LoadBalancer
3567 * @param int $trigger IDatabase::TRIGGER_* constant
3571 public function runTransactionListenerCallbacks( $trigger ) {
3572 if ( $this->trxEndCallbacksSuppressed
) {
3576 /** @var Exception $e */
3577 $e = null; // first exception
3579 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3581 $phpCallback( $trigger, $this );
3582 } catch ( Exception
$ex ) {
3583 ( $this->errorLogger
)( $ex );
3588 if ( $e instanceof Exception
) {
3589 throw $e; // re-throw any first exception
3594 * Create a savepoint
3596 * This is used internally to implement atomic sections. It should not be
3600 * @param string $identifier Identifier for the savepoint
3601 * @param string $fname Calling function name
3603 protected function doSavepoint( $identifier, $fname ) {
3604 $this->query( 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3608 * Release a savepoint
3610 * This is used internally to implement atomic sections. It should not be
3614 * @param string $identifier Identifier for the savepoint
3615 * @param string $fname Calling function name
3617 protected function doReleaseSavepoint( $identifier, $fname ) {
3618 $this->query( 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3622 * Rollback to a savepoint
3624 * This is used internally to implement atomic sections. It should not be
3628 * @param string $identifier Identifier for the savepoint
3629 * @param string $fname Calling function name
3631 protected function doRollbackToSavepoint( $identifier, $fname ) {
3632 $this->query( 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3636 * @param string $fname
3639 private function nextSavepointId( $fname ) {
3640 $savepointId = self
::$SAVEPOINT_PREFIX . ++
$this->trxAtomicCounter
;
3641 if ( strlen( $savepointId ) > 30 ) {
3642 // 30 == Oracle's identifier length limit (pre 12c)
3643 // With a 22 character prefix, that puts the highest number at 99999999.
3644 throw new DBUnexpectedError(
3646 'There have been an excessively large number of atomic sections in a transaction'
3647 . " started by $this->trxFname (at $fname)"
3651 return $savepointId;
3654 final public function startAtomic(
3655 $fname = __METHOD__
, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3657 $savepointId = $cancelable === self
::ATOMIC_CANCELABLE ? self
::$NOT_APPLICABLE : null;
3659 if ( !$this->trxLevel
) {
3660 $this->begin( $fname, self
::TRANSACTION_INTERNAL
); // sets trxAutomatic
3661 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3662 // in all changes being in one transaction to keep requests transactional.
3663 if ( $this->getFlag( self
::DBO_TRX
) ) {
3664 // Since writes could happen in between the topmost atomic sections as part
3665 // of the transaction, those sections will need savepoints.
3666 $savepointId = $this->nextSavepointId( $fname );
3667 $this->doSavepoint( $savepointId, $fname );
3669 $this->trxAutomaticAtomic
= true;
3671 } elseif ( $cancelable === self
::ATOMIC_CANCELABLE
) {
3672 $savepointId = $this->nextSavepointId( $fname );
3673 $this->doSavepoint( $savepointId, $fname );
3676 $sectionId = new AtomicSectionIdentifier
;
3677 $this->trxAtomicLevels
[] = [ $fname, $sectionId, $savepointId ];
3678 $this->queryLogger
->debug( 'startAtomic: entering level ' .
3679 ( count( $this->trxAtomicLevels
) - 1 ) . " ($fname)" );
3684 final public function endAtomic( $fname = __METHOD__
) {
3685 if ( !$this->trxLevel ||
!$this->trxAtomicLevels
) {
3686 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)." );
3689 // Check if the current section matches $fname
3690 $pos = count( $this->trxAtomicLevels
) - 1;
3691 list( $savedFname, $sectionId, $savepointId ) = $this->trxAtomicLevels
[$pos];
3692 $this->queryLogger
->debug( "endAtomic: leaving level $pos ($fname)" );
3694 if ( $savedFname !== $fname ) {
3695 throw new DBUnexpectedError(
3697 "Invalid atomic section ended (got $fname but expected $savedFname)."
3701 // Remove the last section (no need to re-index the array)
3702 array_pop( $this->trxAtomicLevels
);
3704 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3705 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3706 } elseif ( $savepointId !== null && $savepointId !== self
::$NOT_APPLICABLE ) {
3707 $this->doReleaseSavepoint( $savepointId, $fname );
3710 // Hoist callback ownership for callbacks in the section that just ended;
3711 // all callbacks should have an owner that is present in trxAtomicLevels.
3712 $currentSectionId = $this->currentAtomicSectionId();
3713 if ( $currentSectionId ) {
3714 $this->reassignCallbacksForSection( $sectionId, $currentSectionId );
3718 final public function cancelAtomic(
3719 $fname = __METHOD__
, AtomicSectionIdentifier
$sectionId = null
3721 if ( !$this->trxLevel ||
!$this->trxAtomicLevels
) {
3722 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)." );
3725 $excisedFnames = [];
3726 if ( $sectionId !== null ) {
3727 // Find the (last) section with the given $sectionId
3729 foreach ( $this->trxAtomicLevels
as $i => list( $asFname, $asId, $spId ) ) {
3730 if ( $asId === $sectionId ) {
3735 throw new DBUnexpectedError( $this, "Atomic section not found (for $fname)" );
3737 // Remove all descendant sections and re-index the array
3739 $len = count( $this->trxAtomicLevels
);
3740 for ( $i = $pos +
1; $i < $len; ++
$i ) {
3741 $excisedFnames[] = $this->trxAtomicLevels
[$i][0];
3742 $excisedIds[] = $this->trxAtomicLevels
[$i][1];
3744 $this->trxAtomicLevels
= array_slice( $this->trxAtomicLevels
, 0, $pos +
1 );
3745 $this->modifyCallbacksForCancel( $excisedIds );
3748 // Check if the current section matches $fname
3749 $pos = count( $this->trxAtomicLevels
) - 1;
3750 list( $savedFname, $savedSectionId, $savepointId ) = $this->trxAtomicLevels
[$pos];
3752 if ( $excisedFnames ) {
3753 $this->queryLogger
->debug( "cancelAtomic: canceling level $pos ($savedFname) " .
3754 "and descendants " . implode( ', ', $excisedFnames ) );
3756 $this->queryLogger
->debug( "cancelAtomic: canceling level $pos ($savedFname)" );
3759 if ( $savedFname !== $fname ) {
3760 throw new DBUnexpectedError(
3762 "Invalid atomic section ended (got $fname but expected $savedFname)."
3766 // Remove the last section (no need to re-index the array)
3767 array_pop( $this->trxAtomicLevels
);
3768 $this->modifyCallbacksForCancel( [ $savedSectionId ] );
3770 if ( $savepointId !== null ) {
3771 // Rollback the transaction to the state just before this atomic section
3772 if ( $savepointId === self
::$NOT_APPLICABLE ) {
3773 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3775 $this->doRollbackToSavepoint( $savepointId, $fname );
3776 $this->trxStatus
= self
::STATUS_TRX_OK
; // no exception; recovered
3777 $this->trxStatusIgnoredCause
= null;
3779 } elseif ( $this->trxStatus
> self
::STATUS_TRX_ERROR
) {
3780 // Put the transaction into an error state if it's not already in one
3781 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
3782 $this->trxStatusCause
= new DBUnexpectedError(
3784 "Uncancelable atomic section canceled (got $fname)."
3788 $this->affectedRowCount
= 0; // for the sake of consistency
3791 final public function doAtomicSection(
3792 $fname, callable
$callback, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3794 $sectionId = $this->startAtomic( $fname, $cancelable );
3796 $res = $callback( $this, $fname );
3797 } catch ( Exception
$e ) {
3798 $this->cancelAtomic( $fname, $sectionId );
3802 $this->endAtomic( $fname );
3807 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3808 static $modes = [ self
::TRANSACTION_EXPLICIT
, self
::TRANSACTION_INTERNAL
];
3809 if ( !in_array( $mode, $modes, true ) ) {
3810 throw new DBUnexpectedError( $this, "$fname: invalid mode parameter '$mode'." );
3813 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3814 if ( $this->trxLevel
) {
3815 if ( $this->trxAtomicLevels
) {
3816 $levels = $this->flatAtomicSectionList();
3817 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3818 throw new DBUnexpectedError( $this, $msg );
3819 } elseif ( !$this->trxAutomatic
) {
3820 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3821 throw new DBUnexpectedError( $this, $msg );
3823 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3824 throw new DBUnexpectedError( $this, $msg );
3826 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3827 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3828 throw new DBUnexpectedError( $this, $msg );
3831 $this->assertHasConnectionHandle();
3833 $this->doBegin( $fname );
3834 $this->trxStatus
= self
::STATUS_TRX_OK
;
3835 $this->trxStatusIgnoredCause
= null;
3836 $this->trxAtomicCounter
= 0;
3837 $this->trxTimestamp
= microtime( true );
3838 $this->trxFname
= $fname;
3839 $this->trxDoneWrites
= false;
3840 $this->trxAutomaticAtomic
= false;
3841 $this->trxAtomicLevels
= [];
3842 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3843 $this->trxWriteDuration
= 0.0;
3844 $this->trxWriteQueryCount
= 0;
3845 $this->trxWriteAffectedRows
= 0;
3846 $this->trxWriteAdjDuration
= 0.0;
3847 $this->trxWriteAdjQueryCount
= 0;
3848 $this->trxWriteCallers
= [];
3849 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3850 // Get an estimate of the replication lag before any such queries.
3851 $this->trxReplicaLag
= null; // clear cached value first
3852 $this->trxReplicaLag
= $this->getApproximateLagStatus()['lag'];
3853 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3854 // caller will think its OK to muck around with the transaction just because startAtomic()
3855 // has not yet completed (e.g. setting trxAtomicLevels).
3856 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
3860 * Issues the BEGIN command to the database server.
3862 * @see Database::begin()
3863 * @param string $fname
3865 protected function doBegin( $fname ) {
3866 $this->query( 'BEGIN', $fname );
3867 $this->trxLevel
= 1;
3870 final public function commit( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
3871 static $modes = [ self
::FLUSHING_ONE
, self
::FLUSHING_ALL_PEERS
, self
::FLUSHING_INTERNAL
];
3872 if ( !in_array( $flush, $modes, true ) ) {
3873 throw new DBUnexpectedError( $this, "$fname: invalid flush parameter '$flush'." );
3876 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3877 // There are still atomic sections open; this cannot be ignored
3878 $levels = $this->flatAtomicSectionList();
3879 throw new DBUnexpectedError(
3881 "$fname: Got COMMIT while atomic sections $levels are still open."
3885 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3886 if ( !$this->trxLevel
) {
3887 return; // nothing to do
3888 } elseif ( !$this->trxAutomatic
) {
3889 throw new DBUnexpectedError(
3891 "$fname: Flushing an explicit transaction, getting out of sync."
3894 } elseif ( !$this->trxLevel
) {
3895 $this->queryLogger
->error(
3896 "$fname: No transaction to commit, something got out of sync." );
3897 return; // nothing to do
3898 } elseif ( $this->trxAutomatic
) {
3899 throw new DBUnexpectedError(
3901 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)."
3905 $this->assertHasConnectionHandle();
3907 $this->runOnTransactionPreCommitCallbacks();
3909 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3910 $this->doCommit( $fname );
3911 $this->trxStatus
= self
::STATUS_TRX_NONE
;
3913 if ( $this->trxDoneWrites
) {
3914 $this->lastWriteTime
= microtime( true );
3915 $this->trxProfiler
->transactionWritingOut(
3917 $this->getDomainID(),
3920 $this->trxWriteAffectedRows
3924 // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
3925 if ( $flush !== self
::FLUSHING_ALL_PEERS
) {
3926 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3927 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3932 * Issues the COMMIT command to the database server.
3934 * @see Database::commit()
3935 * @param string $fname
3937 protected function doCommit( $fname ) {
3938 if ( $this->trxLevel
) {
3939 $this->query( 'COMMIT', $fname );
3940 $this->trxLevel
= 0;
3944 final public function rollback( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
3945 $trxActive = $this->trxLevel
;
3947 if ( $flush !== self
::FLUSHING_INTERNAL
3948 && $flush !== self
::FLUSHING_ALL_PEERS
3949 && $this->getFlag( self
::DBO_TRX
)
3951 throw new DBUnexpectedError(
3953 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)."
3958 $this->assertHasConnectionHandle();
3960 $this->doRollback( $fname );
3961 $this->trxStatus
= self
::STATUS_TRX_NONE
;
3962 $this->trxAtomicLevels
= [];
3963 // Estimate the RTT via a query now that trxStatus is OK
3964 $writeTime = $this->pingAndCalculateLastTrxApplyTime();
3966 if ( $this->trxDoneWrites
) {
3967 $this->trxProfiler
->transactionWritingOut(
3969 $this->getDomainID(),
3972 $this->trxWriteAffectedRows
3977 // Clear any commit-dependant callbacks. They might even be present
3978 // only due to transaction rounds, with no SQL transaction being active
3979 $this->trxIdleCallbacks
= [];
3980 $this->trxPreCommitCallbacks
= [];
3982 // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
3983 if ( $trxActive && $flush !== self
::FLUSHING_ALL_PEERS
) {
3985 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3986 } catch ( Exception
$e ) {
3987 // already logged; finish and let LoadBalancer move on during mass-rollback
3990 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3991 } catch ( Exception
$e ) {
3992 // already logged; let LoadBalancer move on during mass-rollback
3995 $this->affectedRowCount
= 0; // for the sake of consistency
4000 * Issues the ROLLBACK command to the database server.
4002 * @see Database::rollback()
4003 * @param string $fname
4005 protected function doRollback( $fname ) {
4006 if ( $this->trxLevel
) {
4007 # Disconnects cause rollback anyway, so ignore those errors
4008 $ignoreErrors = true;
4009 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
4010 $this->trxLevel
= 0;
4014 public function flushSnapshot( $fname = __METHOD__
) {
4015 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
4016 // This only flushes transactions to clear snapshots, not to write data
4017 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4018 throw new DBUnexpectedError(
4020 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
4024 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4027 public function explicitTrxActive() {
4028 return $this->trxLevel
&& ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
4031 public function duplicateTableStructure(
4032 $oldName, $newName, $temporary = false, $fname = __METHOD__
4034 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4037 public function listTables( $prefix = null, $fname = __METHOD__
) {
4038 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4041 public function listViews( $prefix = null, $fname = __METHOD__
) {
4042 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4045 public function timestamp( $ts = 0 ) {
4046 $t = new ConvertibleTimestamp( $ts );
4047 // Let errors bubble up to avoid putting garbage in the DB
4048 return $t->getTimestamp( TS_MW
);
4051 public function timestampOrNull( $ts = null ) {
4052 if ( is_null( $ts ) ) {
4055 return $this->timestamp( $ts );
4059 public function affectedRows() {
4060 return ( $this->affectedRowCount
=== null )
4061 ?
$this->fetchAffectedRowCount() // default to driver value
4062 : $this->affectedRowCount
;
4066 * @return int Number of retrieved rows according to the driver
4068 abstract protected function fetchAffectedRowCount();
4071 * Take the result from a query, and wrap it in a ResultWrapper if
4072 * necessary. Boolean values are passed through as is, to indicate success
4073 * of write queries or failure.
4075 * Once upon a time, Database::query() returned a bare MySQL result
4076 * resource, and it was necessary to call this function to convert it to
4077 * a wrapper. Nowadays, raw database objects are never exposed to external
4078 * callers, so this is unnecessary in external code.
4080 * @param bool|IResultWrapper|resource $result
4081 * @return bool|IResultWrapper
4083 protected function resultObject( $result ) {
4086 } elseif ( $result instanceof ResultWrapper
) {
4088 } elseif ( $result === true ) {
4089 // Successful write query
4092 return new ResultWrapper( $this, $result );
4096 public function ping( &$rtt = null ) {
4097 // Avoid hitting the server if it was hit recently
4098 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::$PING_TTL ) {
4099 if ( !func_num_args() ||
$this->lastRoundTripEstimate
> 0 ) {
4100 $rtt = $this->lastRoundTripEstimate
;
4101 return true; // don't care about $rtt
4105 // This will reconnect if possible or return false if not
4106 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
4107 $ok = ( $this->query( self
::$PING_QUERY, __METHOD__
, true ) !== false );
4108 $this->restoreFlags( self
::RESTORE_PRIOR
);
4111 $rtt = $this->lastRoundTripEstimate
;
4118 * Close any existing (dead) database connection and open a new connection
4120 * @param string $fname
4121 * @return bool True if new connection is opened successfully, false if error
4123 protected function replaceLostConnection( $fname ) {
4124 $this->closeConnection();
4125 $this->conn
= false;
4127 $this->handleSessionLossPreconnect();
4136 $this->tablePrefix()
4138 $this->lastPing
= microtime( true );
4141 $this->connLogger
->warning(
4142 $fname . ': lost connection to {dbserver}; reconnected',
4144 'dbserver' => $this->getServer(),
4145 'trace' => ( new RuntimeException() )->getTraceAsString()
4148 } catch ( DBConnectionError
$e ) {
4151 $this->connLogger
->error(
4152 $fname . ': lost connection to {dbserver} permanently',
4153 [ 'dbserver' => $this->getServer() ]
4157 $this->handleSessionLossPostconnect();
4162 public function getSessionLagStatus() {
4163 return $this->getRecordedTransactionLagStatus() ?
: $this->getApproximateLagStatus();
4167 * Get the replica DB lag when the current transaction started
4169 * This is useful when transactions might use snapshot isolation
4170 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
4171 * is this lag plus transaction duration. If they don't, it is still
4172 * safe to be pessimistic. This returns null if there is no transaction.
4174 * This returns null if the lag status for this transaction was not yet recorded.
4176 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
4179 final protected function getRecordedTransactionLagStatus() {
4180 return ( $this->trxLevel
&& $this->trxReplicaLag
!== null )
4181 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
4186 * Get a replica DB lag estimate for this server
4188 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
4191 protected function getApproximateLagStatus() {
4193 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
4194 'since' => microtime( true )
4199 * Merge the result of getSessionLagStatus() for several DBs
4200 * using the most pessimistic values to estimate the lag of
4201 * any data derived from them in combination
4203 * This is information is useful for caching modules
4205 * @see WANObjectCache::set()
4206 * @see WANObjectCache::getWithSetCallback()
4208 * @param IDatabase $db1
4209 * @param IDatabase|null $db2 [optional]
4210 * @return array Map of values:
4211 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
4212 * - since: oldest UNIX timestamp of any of the DB lag estimates
4213 * - pending: whether any of the DBs have uncommitted changes
4217 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
4218 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
4219 foreach ( func_get_args() as $db ) {
4220 /** @var IDatabase $db */
4221 $status = $db->getSessionLagStatus();
4222 if ( $status['lag'] === false ) {
4223 $res['lag'] = false;
4224 } elseif ( $res['lag'] !== false ) {
4225 $res['lag'] = max( $res['lag'], $status['lag'] );
4227 $res['since'] = min( $res['since'], $status['since'] );
4228 $res['pending'] = $res['pending'] ?
: $db->writesPending();
4234 public function getLag() {
4235 if ( $this->getLBInfo( 'master' ) ) {
4236 return 0; // this is the master
4237 } elseif ( $this->getLBInfo( 'is static' ) ) {
4238 return 0; // static dataset
4241 return $this->doGetLag();
4244 protected function doGetLag() {
4248 public function maxListLen() {
4252 public function encodeBlob( $b ) {
4256 public function decodeBlob( $b ) {
4257 if ( $b instanceof Blob
) {
4263 public function setSessionOptions( array $options ) {
4266 public function sourceFile(
4268 callable
$lineCallback = null,
4269 callable
$resultCallback = null,
4271 callable
$inputCallback = null
4273 Wikimedia\
suppressWarnings();
4274 $fp = fopen( $filename, 'r' );
4275 Wikimedia\restoreWarnings
();
4277 if ( $fp === false ) {
4278 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
4282 $fname = __METHOD__
. "( $filename )";
4286 $error = $this->sourceStream(
4287 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
4288 } catch ( Exception
$e ) {
4298 public function setSchemaVars( $vars ) {
4299 $this->schemaVars
= $vars;
4302 public function sourceStream(
4304 callable
$lineCallback = null,
4305 callable
$resultCallback = null,
4306 $fname = __METHOD__
,
4307 callable
$inputCallback = null
4309 $delimiterReset = new ScopedCallback(
4310 function ( $delimiter ) {
4311 $this->delimiter
= $delimiter;
4313 [ $this->delimiter
]
4317 while ( !feof( $fp ) ) {
4318 if ( $lineCallback ) {
4319 call_user_func( $lineCallback );
4322 $line = trim( fgets( $fp ) );
4324 if ( $line == '' ) {
4328 if ( $line[0] == '-' && $line[1] == '-' ) {
4336 $done = $this->streamStatementEnd( $cmd, $line );
4340 if ( $done ||
feof( $fp ) ) {
4341 $cmd = $this->replaceVars( $cmd );
4343 if ( $inputCallback ) {
4344 $callbackResult = $inputCallback( $cmd );
4346 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
4347 $cmd = $callbackResult;
4352 $res = $this->query( $cmd, $fname );
4354 if ( $resultCallback ) {
4355 $resultCallback( $res, $this );
4358 if ( $res === false ) {
4359 $err = $this->lastError();
4361 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4368 ScopedCallback
::consume( $delimiterReset );
4373 * Called by sourceStream() to check if we've reached a statement end
4375 * @param string &$sql SQL assembled so far
4376 * @param string &$newLine New line about to be added to $sql
4377 * @return bool Whether $newLine contains end of the statement
4379 public function streamStatementEnd( &$sql, &$newLine ) {
4380 if ( $this->delimiter
) {
4382 $newLine = preg_replace(
4383 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4384 if ( $newLine != $prev ) {
4393 * Database independent variable replacement. Replaces a set of variables
4394 * in an SQL statement with their contents as given by $this->getSchemaVars().
4396 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4398 * - '{$var}' should be used for text and is passed through the database's
4400 * - `{$var}` should be used for identifiers (e.g. table and database names).
4401 * It is passed through the database's addIdentifierQuotes method which
4402 * can be overridden if the database uses something other than backticks.
4403 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4404 * database's tableName method.
4405 * - / *i* / passes the name that follows through the database's indexName method.
4406 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4407 * its use should be avoided. In 1.24 and older, string encoding was applied.
4409 * @param string $ins SQL statement to replace variables in
4410 * @return string The new SQL statement with variables replaced
4412 protected function replaceVars( $ins ) {
4413 $vars = $this->getSchemaVars();
4414 return preg_replace_callback(
4416 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4417 \'\{\$ (\w+) }\' | # 3. addQuotes
4418 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4419 /\*\$ (\w+) \*/ # 5. leave unencoded
4421 function ( $m ) use ( $vars ) {
4422 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4423 // check for both nonexistent keys *and* the empty string.
4424 if ( isset( $m[1] ) && $m[1] !== '' ) {
4425 if ( $m[1] === 'i' ) {
4426 return $this->indexName( $m[2] );
4428 return $this->tableName( $m[2] );
4430 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4431 return $this->addQuotes( $vars[$m[3]] );
4432 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4433 return $this->addIdentifierQuotes( $vars[$m[4]] );
4434 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4435 return $vars[$m[5]];
4445 * Get schema variables. If none have been set via setSchemaVars(), then
4446 * use some defaults from the current object.
4450 protected function getSchemaVars() {
4451 if ( $this->schemaVars
) {
4452 return $this->schemaVars
;
4454 return $this->getDefaultSchemaVars();
4459 * Get schema variables to use if none have been set via setSchemaVars().
4461 * Override this in derived classes to provide variables for tables.sql
4462 * and SQL patch files.
4466 protected function getDefaultSchemaVars() {
4470 public function lockIsFree( $lockName, $method ) {
4471 // RDBMs methods for checking named locks may or may not count this thread itself.
4472 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
4473 // the behavior choosen by the interface for this method.
4474 return !isset( $this->sessionNamedLocks
[$lockName] );
4477 public function lock( $lockName, $method, $timeout = 5 ) {
4478 $this->sessionNamedLocks
[$lockName] = 1;
4483 public function unlock( $lockName, $method ) {
4484 unset( $this->sessionNamedLocks
[$lockName] );
4489 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
4490 if ( $this->writesOrCallbacksPending() ) {
4491 // This only flushes transactions to clear snapshots, not to write data
4492 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4493 throw new DBUnexpectedError(
4495 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
4499 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
4503 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
4504 if ( $this->trxLevel() ) {
4505 // There is a good chance an exception was thrown, causing any early return
4506 // from the caller. Let any error handler get a chance to issue rollback().
4507 // If there isn't one, let the error bubble up and trigger server-side rollback.
4508 $this->onTransactionResolution(
4509 function () use ( $lockKey, $fname ) {
4510 $this->unlock( $lockKey, $fname );
4515 $this->unlock( $lockKey, $fname );
4519 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4524 public function namedLocksEnqueue() {
4528 public function tableLocksHaveTransactionScope() {
4532 final public function lockTables( array $read, array $write, $method ) {
4533 if ( $this->writesOrCallbacksPending() ) {
4534 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
4537 if ( $this->tableLocksHaveTransactionScope() ) {
4538 $this->startAtomic( $method );
4541 return $this->doLockTables( $read, $write, $method );
4545 * Helper function for lockTables() that handles the actual table locking
4547 * @param array $read Array of tables to lock for read access
4548 * @param array $write Array of tables to lock for write access
4549 * @param string $method Name of caller
4552 protected function doLockTables( array $read, array $write, $method ) {
4556 final public function unlockTables( $method ) {
4557 if ( $this->tableLocksHaveTransactionScope() ) {
4558 $this->endAtomic( $method );
4560 return true; // locks released on COMMIT/ROLLBACK
4563 return $this->doUnlockTables( $method );
4567 * Helper function for unlockTables() that handles the actual table unlocking
4569 * @param string $method Name of caller
4572 protected function doUnlockTables( $method ) {
4578 * @param string $tableName
4579 * @param string $fName
4580 * @return bool|IResultWrapper
4583 public function dropTable( $tableName, $fName = __METHOD__
) {
4584 if ( !$this->tableExists( $tableName, $fName ) ) {
4587 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
4589 return $this->query( $sql, $fName );
4592 public function getInfinity() {
4596 public function encodeExpiry( $expiry ) {
4597 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4598 ?
$this->getInfinity()
4599 : $this->timestamp( $expiry );
4602 public function decodeExpiry( $expiry, $format = TS_MW
) {
4603 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
4607 return ConvertibleTimestamp
::convert( $format, $expiry );
4610 public function setBigSelects( $value = true ) {
4614 public function isReadOnly() {
4615 return ( $this->getReadOnlyReason() !== false );
4619 * @return string|bool Reason this DB is read-only or false if it is not
4621 protected function getReadOnlyReason() {
4622 $reason = $this->getLBInfo( 'readOnlyReason' );
4624 return is_string( $reason ) ?
$reason : false;
4627 public function setTableAliases( array $aliases ) {
4628 $this->tableAliases
= $aliases;
4631 public function setIndexAliases( array $aliases ) {
4632 $this->indexAliases
= $aliases;
4640 protected function hasFlags( $field, $flags ) {
4641 return ( ( $field & $flags ) === $flags );
4645 * Get the underlying binding connection handle
4647 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
4648 * This catches broken callers than catch and ignore disconnection exceptions.
4649 * Unlike checking isOpen(), this is safe to call inside of open().
4652 * @throws DBUnexpectedError
4655 protected function getBindingHandle() {
4656 if ( !$this->conn
) {
4657 throw new DBUnexpectedError(
4659 'DB connection was already closed or the connection dropped.'
4666 public function __toString() {
4667 // spl_object_id is PHP >= 7.2
4668 $id = function_exists( 'spl_object_id' )
4669 ?
spl_object_id( $this )
4670 : spl_object_hash( $this );
4672 $description = $this->getType() . ' object #' . $id;
4673 if ( is_resource( $this->conn
) ) {
4674 $description .= ' (' . (string)$this->conn
. ')'; // "resource id #<ID>"
4675 } elseif ( is_object( $this->conn
) ) {
4676 // spl_object_id is PHP >= 7.2
4677 $handleId = function_exists( 'spl_object_id' )
4678 ?
spl_object_id( $this->conn
)
4679 : spl_object_hash( $this->conn
);
4680 $description .= " (handle id #$handleId)";
4683 return $description;
4687 * Make sure that copies do not share the same client binding handle
4688 * @throws DBConnectionError
4690 public function __clone() {
4691 $this->connLogger
->warning(
4692 "Cloning " . static::class . " is not recommended; forking connection:\n" .
4693 ( new RuntimeException() )->getTraceAsString()
4696 if ( $this->isOpen() ) {
4697 // Open a new connection resource without messing with the old one
4698 $this->conn
= false;
4699 $this->trxEndCallbacks
= []; // don't copy
4700 $this->handleSessionLossPreconnect(); // no trx or locks anymore
4707 $this->tablePrefix()
4709 $this->lastPing
= microtime( true );
4714 * Called by serialize. Throw an exception when DB connection is serialized.
4715 * This causes problems on some database engines because the connection is
4716 * not restored on unserialize.
4718 public function __sleep() {
4719 throw new RuntimeException( 'Database serialization may cause problems, since ' .
4720 'the connection is not restored on wakeup.' );
4724 * Run a few simple sanity checks and close dangling connections
4726 public function __destruct() {
4727 if ( $this->trxLevel
&& $this->trxDoneWrites
) {
4728 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})." );
4731 $danglingWriters = $this->pendingWriteAndCallbackCallers();
4732 if ( $danglingWriters ) {
4733 $fnames = implode( ', ', $danglingWriters );
4734 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
4737 if ( $this->conn
) {
4738 // Avoid connection leaks for sanity. Normally, resources close at script completion.
4739 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4740 Wikimedia\
suppressWarnings();
4741 $this->closeConnection();
4742 Wikimedia\restoreWarnings
();
4743 $this->conn
= false;
4749 * @deprecated since 1.28
4751 class_alias( Database
::class, 'DatabaseBase' );
4754 * @deprecated since 1.29
4756 class_alias( Database
::class, 'Database' );