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
;
33 use Wikimedia\AtEase\AtEase
;
37 use InvalidArgumentException
;
38 use UnexpectedValueException
;
44 * Relational database abstraction object
49 abstract class Database
implements IDatabase
, IMaintainableDatabase
, LoggerAwareInterface
{
50 /** @var string Server that this instance is currently connected to */
52 /** @var string User that this instance is currently connected under the name of */
54 /** @var string Password used to establish the current connection */
56 /** @var array[] Map of (table => (dbname, schema, prefix) map) */
57 protected $tableAliases = [];
58 /** @var string[] Map of (index alias => index) */
59 protected $indexAliases = [];
60 /** @var bool Whether this PHP instance is for a CLI script */
62 /** @var string Agent name for query profiling */
64 /** @var int Bit field of class DBO_* constants */
66 /** @var array LoadBalancer tracking information */
67 protected $lbInfo = [];
68 /** @var array|bool Variables use for schema element placeholders */
69 protected $schemaVars = false;
70 /** @var array Parameters used by initConnection() to establish a connection */
71 protected $connectionParams = [];
72 /** @var array SQL variables values to use for all new connections */
73 protected $connectionVariables = [];
74 /** @var string Current SQL query delimiter */
75 protected $delimiter = ';';
76 /** @var string|bool|null Stashed value of html_errors INI setting */
77 protected $htmlErrors;
78 /** @var int Row batch size to use for emulated INSERT SELECT queries */
79 protected $nonNativeInsertSelectBatchSize = 10000;
81 /** @var BagOStuff APC cache */
83 /** @var LoggerInterface */
84 protected $connLogger;
85 /** @var LoggerInterface */
86 protected $queryLogger;
87 /** @var callable Error logging callback */
88 protected $errorLogger;
89 /** @var callable Deprecation logging callback */
90 protected $deprecationLogger;
91 /** @var callable|null */
93 /** @var TransactionProfiler */
94 protected $trxProfiler;
95 /** @var DatabaseDomain */
96 protected $currentDomain;
97 /** @var object|resource|null Database connection */
100 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
101 private $lazyMasterHandle;
103 /** @var array Map of (name => 1) for locks obtained via lock() */
104 protected $sessionNamedLocks = [];
105 /** @var array Map of (table name => 1) for TEMPORARY tables */
106 protected $sessionTempTables = [];
108 /** @var string ID of the active transaction or the empty string otherwise */
109 protected $trxShortId = '';
110 /** @var int Transaction status */
111 protected $trxStatus = self
::STATUS_TRX_NONE
;
112 /** @var Exception|null The last error that caused the status to become STATUS_TRX_ERROR */
113 protected $trxStatusCause;
114 /** @var array|null Error details of the last statement-only rollback */
115 private $trxStatusIgnoredCause;
116 /** @var float|null UNIX timestamp at the time of BEGIN for the last transaction */
117 private $trxTimestamp = null;
118 /** @var float Replication lag estimate at the time of BEGIN for the last transaction */
119 private $trxReplicaLag = null;
120 /** @var string Name of the function that start the last transaction */
121 private $trxFname = null;
122 /** @var bool Whether possible write queries were done in the last transaction started */
123 private $trxDoneWrites = false;
124 /** @var bool Whether the current transaction was started implicitly due to DBO_TRX */
125 private $trxAutomatic = false;
126 /** @var int Counter for atomic savepoint identifiers (reset with each transaction) */
127 private $trxAtomicCounter = 0;
128 /** @var array List of (name, unique ID, savepoint ID) for each active atomic section level */
129 private $trxAtomicLevels = [];
130 /** @var bool Whether the current transaction was started implicitly by startAtomic() */
131 private $trxAutomaticAtomic = false;
132 /** @var string[] Write query callers of the current transaction */
133 private $trxWriteCallers = [];
134 /** @var float Seconds spent in write queries for the current transaction */
135 private $trxWriteDuration = 0.0;
136 /** @var int Number of write queries for the current transaction */
137 private $trxWriteQueryCount = 0;
138 /** @var int Number of rows affected by write queries for the current transaction */
139 private $trxWriteAffectedRows = 0;
140 /** @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries */
141 private $trxWriteAdjDuration = 0.0;
142 /** @var int Number of write queries counted in trxWriteAdjDuration */
143 private $trxWriteAdjQueryCount = 0;
144 /** @var array[] List of (callable, method name, atomic section id) */
145 private $trxIdleCallbacks = [];
146 /** @var array[] List of (callable, method name, atomic section id) */
147 private $trxPreCommitCallbacks = [];
148 /** @var array[] List of (callable, method name, atomic section id) */
149 private $trxEndCallbacks = [];
150 /** @var array[] List of (callable, method name, atomic section id) */
151 private $trxSectionCancelCallbacks = [];
152 /** @var callable[] Map of (name => callable) */
153 private $trxRecurringCallbacks = [];
154 /** @var bool Whether to suppress triggering of transaction end callbacks */
155 private $trxEndCallbacksSuppressed = false;
157 /** @var int[] Prior flags member variable values */
158 private $priorFlags = [];
160 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
161 protected $affectedRowCount;
163 /** @var float UNIX timestamp */
164 private $lastPing = 0.0;
165 /** @var string The last SQL query attempted */
166 private $lastQuery = '';
167 /** @var float|bool UNIX timestamp of last write query */
168 private $lastWriteTime = false;
169 /** @var string|bool */
170 private $lastPhpError = false;
171 /** @var float Query rount trip time estimate */
172 private $lastRoundTripEstimate = 0.0;
174 /** @var string Lock granularity is on the level of the entire database */
175 const ATTR_DB_LEVEL_LOCKING
= 'db-level-locking';
176 /** @var string The SCHEMA keyword refers to a grouping of tables in a database */
177 const ATTR_SCHEMAS_AS_TABLE_GROUPS
= 'supports-schemas';
179 /** @var int New Database instance will not be connected yet when returned */
180 const NEW_UNCONNECTED
= 0;
181 /** @var int New Database instance will already be connected when returned */
182 const NEW_CONNECTED
= 1;
184 /** @var int Transaction is in a error state requiring a full or savepoint rollback */
185 const STATUS_TRX_ERROR
= 1;
186 /** @var int Transaction is active and in a normal state */
187 const STATUS_TRX_OK
= 2;
188 /** @var int No transaction is active */
189 const STATUS_TRX_NONE
= 3;
191 /** @var string Idiom used when a cancelable atomic section started the transaction */
192 private static $NOT_APPLICABLE = 'n/a';
193 /** @var string Prefix to the atomic section counter used to make savepoint IDs */
194 private static $SAVEPOINT_PREFIX = 'wikimedia_rdbms_atomic';
196 /** @var int Writes to this temporary table do not affect lastDoneWrites() */
197 private static $TEMP_NORMAL = 1;
198 /** @var int Writes to this temporary table effect lastDoneWrites() */
199 private static $TEMP_PSEUDO_PERMANENT = 2;
201 /** @var int Number of times to re-try an operation in case of deadlock */
202 private static $DEADLOCK_TRIES = 4;
203 /** @var int Minimum time to wait before retry, in microseconds */
204 private static $DEADLOCK_DELAY_MIN = 500000;
205 /** @var int Maximum time to wait before retry */
206 private static $DEADLOCK_DELAY_MAX = 1500000;
208 /** @var int How long before it is worth doing a dummy query to test the connection */
209 private static $PING_TTL = 1.0;
210 /** @var string Dummy SQL query */
211 private static $PING_QUERY = 'SELECT 1 AS ping';
213 /** @var float Guess of how many seconds it takes to replicate a small insert */
214 private static $TINY_WRITE_SEC = 0.010;
215 /** @var float Consider a write slow if it took more than this many seconds */
216 private static $SLOW_WRITE_SEC = 0.500;
217 /** @var float Assume an insert of this many rows or less should be fast to replicate */
218 private static $SMALL_WRITE_ROWS = 100;
220 /** @var string[] List of DBO_* flags that can be changed after connection */
221 protected static $MUTABLE_FLAGS = [
227 /** @var int Bit field of all DBO_* flags that can be changed after connection */
228 protected static $DBO_MUTABLE = (
229 self
::DBO_DEBUG | self
::DBO_NOBUFFER | self
::DBO_TRX | self
::DBO_DDLMODE
233 * @note exceptions for missing libraries/drivers should be thrown in initConnection()
234 * @param array $params Parameters passed from Database::factory()
236 protected function __construct( array $params ) {
237 foreach ( [ 'host', 'user', 'password', 'dbname', 'schema', 'tablePrefix' ] as $name ) {
238 $this->connectionParams
[$name] = $params[$name];
241 $this->cliMode
= $params['cliMode'];
242 // Agent name is added to SQL queries in a comment, so make sure it can't break out
243 $this->agent
= str_replace( '/', '-', $params['agent'] );
245 $this->flags
= $params['flags'];
246 if ( $this->flags
& self
::DBO_DEFAULT
) {
247 if ( $this->cliMode
) {
248 $this->flags
&= ~self
::DBO_TRX
;
250 $this->flags |
= self
::DBO_TRX
;
253 // Disregard deprecated DBO_IGNORE flag (T189999)
254 $this->flags
&= ~self
::DBO_IGNORE
;
256 $this->connectionVariables
= $params['variables'];
258 $this->srvCache
= $params['srvCache'] ??
new HashBagOStuff();
260 $this->profiler
= is_callable( $params['profiler'] ) ?
$params['profiler'] : null;
261 $this->trxProfiler
= $params['trxProfiler'];
262 $this->connLogger
= $params['connLogger'];
263 $this->queryLogger
= $params['queryLogger'];
264 $this->errorLogger
= $params['errorLogger'];
265 $this->deprecationLogger
= $params['deprecationLogger'];
267 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
268 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'];
271 // Set initial dummy domain until open() sets the final DB/prefix
272 $this->currentDomain
= new DatabaseDomain(
273 $params['dbname'] != '' ?
$params['dbname'] : null,
274 $params['schema'] != '' ?
$params['schema'] : null,
275 $params['tablePrefix']
280 * Initialize the connection to the database over the wire (or to local files)
282 * @throws LogicException
283 * @throws InvalidArgumentException
284 * @throws DBConnectionError
287 final public function initConnection() {
288 if ( $this->isOpen() ) {
289 throw new LogicException( __METHOD__
. ': already connected' );
291 // Establish the connection
292 $this->doInitConnection();
296 * Actually connect to the database over the wire (or to local files)
298 * @throws DBConnectionError
301 protected function doInitConnection() {
303 $this->connectionParams
['host'],
304 $this->connectionParams
['user'],
305 $this->connectionParams
['password'],
306 $this->connectionParams
['dbname'],
307 $this->connectionParams
['schema'],
308 $this->connectionParams
['tablePrefix']
313 * Open a new connection to the database (closing any existing one)
315 * @param string|null $server Database server host
316 * @param string|null $user Database user name
317 * @param string|null $password Database user password
318 * @param string|null $dbName Database name
319 * @param string|null $schema Database schema name
320 * @param string $tablePrefix Table prefix
321 * @throws DBConnectionError
323 abstract protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix );
326 * Construct a Database subclass instance given a database type and parameters
328 * This also connects to the database immediately upon object construction
330 * @param string $type A possible DB type (sqlite, mysql, postgres,...)
331 * @param array $params Parameter map with keys:
332 * - host : The hostname of the DB server
333 * - user : The name of the database user the client operates under
334 * - password : The password for the database user
335 * - dbname : The name of the database to use where queries do not specify one.
336 * The database must exist or an error might be thrown. Setting this to the empty string
337 * will avoid any such errors and make the handle have no implicit database scope. This is
338 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
339 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
340 * in which user names and such are defined, e.g. users are database-specific in Postgres.
341 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
342 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
343 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
344 * recognized in queries. This can be used in place of schemas for handle site farms.
345 * - flags : Optional bit field of DBO_* constants that define connection, protocol,
346 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
347 * flag in place UNLESS this this database simply acts as a key/value store.
348 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
349 * 'mysqli' driver; the old one 'mysql' has been removed.
350 * - variables: Optional map of session variables to set after connecting. This can be
351 * used to adjust lock timeouts or encoding modes and the like.
352 * - connLogger: Optional PSR-3 logger interface instance.
353 * - queryLogger: Optional PSR-3 logger interface instance.
354 * - profiler : Optional callback that takes a section name argument and returns
355 * a ScopedCallback instance that ends the profile section in its destructor.
356 * These will be called in query(), using a simplified version of the SQL that
357 * also includes the agent as a SQL comment.
358 * - trxProfiler: Optional TransactionProfiler instance.
359 * - errorLogger: Optional callback that takes an Exception and logs it.
360 * - deprecationLogger: Optional callback that takes a string and logs it.
361 * - cliMode: Whether to consider the execution context that of a CLI script.
362 * - agent: Optional name used to identify the end-user in query profiling/logging.
363 * - srvCache: Optional BagOStuff instance to an APC-style cache.
364 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
365 * @param int $connect One of the class constants (NEW_CONNECTED, NEW_UNCONNECTED) [optional]
366 * @return Database|null If the database driver or extension cannot be found
367 * @throws InvalidArgumentException If the database driver or extension cannot be found
370 final public static function factory( $type, $params = [], $connect = self
::NEW_CONNECTED
) {
371 $class = self
::getClass( $type, $params['driver'] ??
null );
373 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
383 'cliMode' => ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' ),
384 'agent' => basename( $_SERVER['SCRIPT_NAME'] ) . '@' . gethostname()
387 $normalizedParams = [
389 'host' => strlen( $params['host'] ) ?
$params['host'] : null,
390 'user' => strlen( $params['user'] ) ?
$params['user'] : null,
391 'password' => is_string( $params['password'] ) ?
$params['password'] : null,
392 'dbname' => strlen( $params['dbname'] ) ?
$params['dbname'] : null,
393 'schema' => strlen( $params['schema'] ) ?
$params['schema'] : null,
394 'tablePrefix' => (string)$params['tablePrefix'],
395 'flags' => (int)$params['flags'],
396 'variables' => $params['variables'],
397 'cliMode' => (bool)$params['cliMode'],
398 'agent' => (string)$params['agent'],
399 // Objects and callbacks
400 'profiler' => $params['profiler'] ??
null,
401 'trxProfiler' => $params['trxProfiler'] ??
new TransactionProfiler(),
402 'connLogger' => $params['connLogger'] ??
new NullLogger(),
403 'queryLogger' => $params['queryLogger'] ??
new NullLogger(),
404 'errorLogger' => $params['errorLogger'] ??
function ( Exception
$e ) {
405 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
407 'deprecationLogger' => $params['deprecationLogger'] ??
function ( $msg ) {
408 trigger_error( $msg, E_USER_DEPRECATED
);
412 /** @var Database $conn */
413 $conn = new $class( $normalizedParams );
414 if ( $connect === self
::NEW_CONNECTED
) {
415 $conn->initConnection();
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 array Map of (Database::ATTR_* constant => value) for all such constants
428 * @throws InvalidArgumentException
431 final public static function attributesFromType( $dbType, $driver = null ) {
433 self
::ATTR_DB_LEVEL_LOCKING
=> false,
434 self
::ATTR_SCHEMAS_AS_TABLE_GROUPS
=> false
437 $class = self
::getClass( $dbType, $driver );
439 return call_user_func( [ $class, 'getAttributes' ] ) +
$defaults;
443 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
444 * @param string|null $driver Optional name of a specific DB client driver
445 * @return string Database subclass name to use
446 * @throws InvalidArgumentException
448 private static function getClass( $dbType, $driver = null ) {
449 // For database types with built-in support, the below maps type to IDatabase
450 // implementations. For types with multipe driver implementations (PHP extensions),
451 // an array can be used, keyed by extension name. In case of an array, the
452 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
453 // we auto-detect the first available driver. For types without built-in support,
454 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
455 static $builtinTypes = [
456 'mssql' => DatabaseMssql
::class,
457 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
458 'sqlite' => DatabaseSqlite
::class,
459 'postgres' => DatabasePostgres
::class,
462 $dbType = strtolower( $dbType );
465 if ( isset( $builtinTypes[$dbType] ) ) {
466 $possibleDrivers = $builtinTypes[$dbType];
467 if ( is_string( $possibleDrivers ) ) {
468 $class = $possibleDrivers;
469 } elseif ( (string)$driver !== '' ) {
470 if ( !isset( $possibleDrivers[$driver] ) ) {
471 throw new InvalidArgumentException( __METHOD__
.
472 " type '$dbType' does not support driver '{$driver}'" );
475 $class = $possibleDrivers[$driver];
477 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
478 if ( extension_loaded( $posDriver ) ) {
479 $class = $possibleClass;
485 $class = 'Database' . ucfirst( $dbType );
488 if ( $class === false ) {
489 throw new InvalidArgumentException( __METHOD__
.
490 " no viable database extension found for type '$dbType'" );
497 * @return array Map of (Database::ATTR_* constant => value
500 protected static function getAttributes() {
505 * Set the PSR-3 logger interface to use for query logging. (The logger
506 * interfaces for connection logging and error logging can be set with the
509 * @param LoggerInterface $logger
511 public function setLogger( LoggerInterface
$logger ) {
512 $this->queryLogger
= $logger;
515 public function getServerInfo() {
516 return $this->getServerVersion();
519 public function bufferResults( $buffer = null ) {
520 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
521 if ( $buffer !== null ) {
523 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
524 : $this->setFlag( self
::DBO_NOBUFFER
);
530 final public function trxLevel() {
531 return ( $this->trxShortId
!= '' ) ?
1 : 0;
534 public function trxTimestamp() {
535 return $this->trxLevel() ?
$this->trxTimestamp
: null;
539 * @return int One of the STATUS_TRX_* class constants
542 public function trxStatus() {
543 return $this->trxStatus
;
546 public function tablePrefix( $prefix = null ) {
547 $old = $this->currentDomain
->getTablePrefix();
548 if ( $prefix !== null ) {
549 $this->currentDomain
= new DatabaseDomain(
550 $this->currentDomain
->getDatabase(),
551 $this->currentDomain
->getSchema(),
559 public function dbSchema( $schema = null ) {
560 if ( strlen( $schema ) && $this->getDBname() === null ) {
561 throw new DBUnexpectedError( $this, "Cannot set schema to '$schema'; no database set" );
564 $old = $this->currentDomain
->getSchema();
565 if ( $schema !== null ) {
566 $this->currentDomain
= new DatabaseDomain(
567 $this->currentDomain
->getDatabase(),
568 // DatabaseDomain uses null for unspecified schemas
569 strlen( $schema ) ?
$schema : null,
570 $this->currentDomain
->getTablePrefix()
578 * @return string Schema to use to qualify relations in queries
580 protected function relationSchemaQualifier() {
581 return $this->dbSchema();
584 public function getLBInfo( $name = null ) {
585 if ( is_null( $name ) ) {
586 return $this->lbInfo
;
589 if ( array_key_exists( $name, $this->lbInfo
) ) {
590 return $this->lbInfo
[$name];
596 public function setLBInfo( $nameOrArray, $value = null ) {
597 if ( is_array( $nameOrArray ) ) {
598 $this->lbInfo
= $nameOrArray;
599 } elseif ( is_string( $nameOrArray ) ) {
600 if ( $value !== null ) {
601 $this->lbInfo
[$nameOrArray] = $value;
603 unset( $this->lbInfo
[$nameOrArray] );
606 throw new InvalidArgumentException( "Got non-string key" );
610 public function setLazyMasterHandle( IDatabase
$conn ) {
611 $this->lazyMasterHandle
= $conn;
615 * @return IDatabase|null
616 * @see setLazyMasterHandle()
619 protected function getLazyMasterHandle() {
620 return $this->lazyMasterHandle
;
623 public function implicitOrderby() {
627 public function lastQuery() {
628 return $this->lastQuery
;
631 public function lastDoneWrites() {
632 return $this->lastWriteTime ?
: false;
635 public function writesPending() {
636 return $this->trxLevel() && $this->trxDoneWrites
;
639 public function writesOrCallbacksPending() {
640 return $this->trxLevel() && (
641 $this->trxDoneWrites ||
642 $this->trxIdleCallbacks ||
643 $this->trxPreCommitCallbacks ||
644 $this->trxEndCallbacks ||
645 $this->trxSectionCancelCallbacks
649 public function preCommitCallbacksPending() {
650 return $this->trxLevel() && $this->trxPreCommitCallbacks
;
654 * @return string|null
656 final protected function getTransactionRoundId() {
657 // If transaction round participation is enabled, see if one is active
658 if ( $this->getFlag( self
::DBO_TRX
) ) {
659 $id = $this->getLBInfo( 'trxRoundId' );
661 return is_string( $id ) ?
$id : null;
667 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
668 if ( !$this->trxLevel() ) {
670 } elseif ( !$this->trxDoneWrites
) {
675 case self
::ESTIMATE_DB_APPLY
:
676 return $this->pingAndCalculateLastTrxApplyTime();
677 default: // everything
678 return $this->trxWriteDuration
;
683 * @return float Time to apply writes to replicas based on trxWrite* fields
685 private function pingAndCalculateLastTrxApplyTime() {
688 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
689 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
690 // For omitted queries, make them count as something at least
691 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
692 $applyTime +
= self
::$TINY_WRITE_SEC * $omitted;
697 public function pendingWriteCallers() {
698 return $this->trxLevel() ?
$this->trxWriteCallers
: [];
701 public function pendingWriteRowsAffected() {
702 return $this->trxWriteAffectedRows
;
706 * List the methods that have write queries or callbacks for the current transaction
708 * This method should not be used outside of Database/LoadBalancer
713 public function pendingWriteAndCallbackCallers() {
714 $fnames = $this->pendingWriteCallers();
716 $this->trxIdleCallbacks
,
717 $this->trxPreCommitCallbacks
,
718 $this->trxEndCallbacks
,
719 $this->trxSectionCancelCallbacks
721 foreach ( $callbacks as $callback ) {
722 $fnames[] = $callback[1];
732 private function flatAtomicSectionList() {
733 return array_reduce( $this->trxAtomicLevels
, function ( $accum, $v ) {
734 return $accum === null ?
$v[0] : "$accum, " . $v[0];
738 public function isOpen() {
739 return (bool)$this->conn
;
742 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
743 if ( $flag & ~
static::$DBO_MUTABLE ) {
744 throw new DBUnexpectedError(
746 "Got $flag (allowed: " . implode( ', ', static::$MUTABLE_FLAGS ) . ')'
750 if ( $remember === self
::REMEMBER_PRIOR
) {
751 array_push( $this->priorFlags
, $this->flags
);
754 $this->flags |
= $flag;
757 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
758 if ( $flag & ~
static::$DBO_MUTABLE ) {
759 throw new DBUnexpectedError(
761 "Got $flag (allowed: " . implode( ', ', static::$MUTABLE_FLAGS ) . ')'
765 if ( $remember === self
::REMEMBER_PRIOR
) {
766 array_push( $this->priorFlags
, $this->flags
);
769 $this->flags
&= ~
$flag;
772 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
773 if ( !$this->priorFlags
) {
777 if ( $state === self
::RESTORE_INITIAL
) {
778 $this->flags
= reset( $this->priorFlags
);
779 $this->priorFlags
= [];
781 $this->flags
= array_pop( $this->priorFlags
);
785 public function getFlag( $flag ) {
786 return ( ( $this->flags
& $flag ) === $flag );
789 public function getDomainID() {
790 return $this->currentDomain
->getId();
794 * Get information about an index into an object
795 * @param string $table Table name
796 * @param string $index Index name
797 * @param string $fname Calling function name
798 * @return mixed Database-specific index description class or false if the index does not exist
800 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
803 * Wrapper for addslashes()
805 * @param string $s String to be slashed.
806 * @return string Slashed string.
808 abstract function strencode( $s );
811 * Set a custom error handler for logging errors during database connection
813 protected function installErrorHandler() {
814 $this->lastPhpError
= false;
815 $this->htmlErrors
= ini_set( 'html_errors', '0' );
816 set_error_handler( [ $this, 'connectionErrorLogger' ] );
820 * Restore the previous error handler and return the last PHP error for this DB
822 * @return bool|string
824 protected function restoreErrorHandler() {
825 restore_error_handler();
826 if ( $this->htmlErrors
!== false ) {
827 ini_set( 'html_errors', $this->htmlErrors
);
830 return $this->getLastPHPError();
834 * @return string|bool Last PHP error for this DB (typically connection errors)
836 protected function getLastPHPError() {
837 if ( $this->lastPhpError
) {
838 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->lastPhpError
);
839 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
848 * Error handler for logging errors during database connection
849 * This method should not be used outside of Database classes
852 * @param string $errstr
854 public function connectionErrorLogger( $errno, $errstr ) {
855 $this->lastPhpError
= $errstr;
859 * Create a log context to pass to PSR-3 logger functions.
861 * @param array $extras Additional data to add to context
864 protected function getLogContext( array $extras = [] ) {
867 'db_server' => $this->server
,
868 'db_name' => $this->getDBname(),
869 'db_user' => $this->user
,
875 final public function close() {
876 $exception = null; // error to throw after disconnecting
878 $wasOpen = (bool)$this->conn
;
879 // This should mostly do nothing if the connection is already closed
881 // Roll back any dangling transaction first
882 if ( $this->trxLevel() ) {
883 if ( $this->trxAtomicLevels
) {
884 // Cannot let incomplete atomic sections be committed
885 $levels = $this->flatAtomicSectionList();
886 $exception = new DBUnexpectedError(
888 __METHOD__
. ": atomic sections $levels are still open"
890 } elseif ( $this->trxAutomatic
) {
891 // Only the connection manager can commit non-empty DBO_TRX transactions
892 // (empty ones we can silently roll back)
893 if ( $this->writesOrCallbacksPending() ) {
894 $exception = new DBUnexpectedError(
897 ": mass commit/rollback of peer transaction required (DBO_TRX set)"
901 // Manual transactions should have been committed or rolled
902 // back, even if empty.
903 $exception = new DBUnexpectedError(
905 __METHOD__
. ": transaction is still open (from {$this->trxFname})"
909 if ( $this->trxEndCallbacksSuppressed
) {
910 $exception = $exception ?
: new DBUnexpectedError(
912 __METHOD__
. ': callbacks are suppressed; cannot properly commit'
916 // Rollback the changes and run any callbacks as needed
917 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
920 // Close the actual connection in the binding handle
921 $closed = $this->closeConnection();
923 $closed = true; // already closed; nothing to do
928 // Throw any unexpected errors after having disconnected
929 if ( $exception instanceof Exception
) {
933 // Note that various subclasses call close() at the start of open(), which itself is
934 // called by replaceLostConnection(). In that case, just because onTransactionResolution()
935 // callbacks are pending does not mean that an exception should be thrown. Rather, they
936 // will be executed after the reconnection step.
938 // Sanity check that no callbacks are dangling
939 $fnames = $this->pendingWriteAndCallbackCallers();
941 throw new RuntimeException(
942 "Transaction callbacks are still pending: " . implode( ', ', $fnames )
951 * Make sure there is an open connection handle (alive or not) as a sanity check
953 * This guards against fatal errors to the binding handle not being defined
954 * in cases where open() was never called or close() was already called
956 * @throws DBUnexpectedError
958 final protected function assertHasConnectionHandle() {
959 if ( !$this->isOpen() ) {
960 throw new DBUnexpectedError( $this, "DB connection was already closed" );
965 * Make sure that this server is not marked as a replica nor read-only as a sanity check
967 * @throws DBReadOnlyRoleError
968 * @throws DBReadOnlyError
970 protected function assertIsWritableMaster() {
971 if ( $this->getLBInfo( 'replica' ) === true ) {
972 throw new DBReadOnlyRoleError(
974 'Write operations are not allowed on replica database connections'
977 $reason = $this->getReadOnlyReason();
978 if ( $reason !== false ) {
979 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
984 * Closes underlying database connection
986 * @return bool Whether connection was closed successfully
988 abstract protected function closeConnection();
991 * Run a query and return a DBMS-dependent wrapper or boolean
993 * This is meant to handle the basic command of actually sending a query to the
994 * server via the driver. No implicit transaction, reconnection, nor retry logic
995 * should happen here. The higher level query() method is designed to handle those
996 * sorts of concerns. This method should not trigger such higher level methods.
998 * The lastError() and lastErrno() methods should meaningfully reflect what error,
999 * if any, occured during the last call to this method. Methods like executeQuery(),
1000 * query(), select(), insert(), update(), delete(), and upsert() implement their calls
1001 * to doQuery() such that an immediately subsequent call to lastError()/lastErrno()
1002 * meaningfully reflects any error that occured during that public query method call.
1004 * For SELECT queries, this returns either:
1005 * - a) A driver-specific value/resource, only on success. This can be iterated
1006 * over by calling fetchObject()/fetchRow() until there are no more rows.
1007 * Alternatively, the result can be passed to resultObject() to obtain an
1008 * IResultWrapper instance which can then be iterated over via "foreach".
1009 * - b) False, on any query failure
1011 * For non-SELECT queries, this returns either:
1012 * - a) A driver-specific value/resource, only on success
1013 * - b) True, only on success (e.g. no meaningful result other than "OK")
1014 * - c) False, on any query failure
1016 * @param string $sql SQL query
1017 * @return mixed|bool An object, resource, or true on success; false on failure
1019 abstract protected function doQuery( $sql );
1022 * Determine whether a query writes to the DB. When in doubt, this returns true.
1026 * - Subsequent web requests should not need to wait for replication from
1027 * the master position seen by this web request, unless this request made
1028 * changes to the master. This is handled by ChronologyProtector by checking
1029 * doneWrites() at the end of the request. doneWrites() returns true if any
1030 * query set lastWriteTime; which query() does based on isWriteQuery().
1032 * - Reject write queries to replica DBs, in query().
1034 * @param string $sql
1037 protected function isWriteQuery( $sql ) {
1038 // BEGIN and COMMIT queries are considered read queries here.
1039 // Database backends and drivers (MySQL, MariaDB, php-mysqli) generally
1040 // treat these as write queries, in that their results have "affected rows"
1041 // as meta data as from writes, instead of "num rows" as from reads.
1042 // But, we treat them as read queries because when reading data (from
1043 // either replica or master) we use transactions to enable repeatable-read
1044 // snapshots, which ensures we get consistent results from the same snapshot
1045 // for all queries within a request. Use cases:
1046 // - Treating these as writes would trigger ChronologyProtector (see method doc).
1047 // - We use this method to reject writes to replicas, but we need to allow
1048 // use of transactions on replicas for read snapshots. This is fine given
1049 // that transactions by themselves don't make changes, only actual writes
1050 // within the transaction matter, which we still detect.
1052 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SAVEPOINT|RELEASE|SET|SHOW|EXPLAIN|USE|\(SELECT)\b/i',
1058 * @param string $sql
1059 * @return string|null
1061 protected function getQueryVerb( $sql ) {
1062 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
1066 * Determine whether a SQL statement is sensitive to isolation level.
1068 * A SQL statement is considered transactable if its result could vary
1069 * depending on the transaction isolation level. Operational commands
1070 * such as 'SET' and 'SHOW' are not considered to be transactable.
1072 * Main purpose: Used by query() to decide whether to begin a transaction
1073 * before the current query (in DBO_TRX mode, on by default).
1075 * @param string $sql
1078 protected function isTransactableQuery( $sql ) {
1080 $this->getQueryVerb( $sql ),
1081 [ 'BEGIN', 'ROLLBACK', 'COMMIT', 'SET', 'SHOW', 'CREATE', 'ALTER', 'USE', 'SHOW' ],
1087 * @param string $sql A SQL query
1088 * @param bool $pseudoPermanent Treat any table from CREATE TEMPORARY as pseudo-permanent
1089 * @return array A n-tuple of:
1090 * - int|null: A self::TEMP_* constant for temp table operations or null otherwise
1091 * - string|null: The name of the new temporary table $sql creates, or null
1092 * - string|null: The name of the temporary table that $sql drops, or null
1094 protected function getTempWrites( $sql, $pseudoPermanent ) {
1095 static $qt = '[`"\']?(\w+)[`"\']?'; // quoted table
1098 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?' . $qt . '/i',
1102 $type = $pseudoPermanent ? self
::$TEMP_PSEUDO_PERMANENT : self
::$TEMP_NORMAL;
1104 return [ $type, $matches[1], null ];
1105 } elseif ( preg_match(
1106 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt . '/i',
1110 return [ $this->sessionTempTables
[$matches[1]] ??
null, null, $matches[1] ];
1111 } elseif ( preg_match(
1112 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt . '/i',
1116 return [ $this->sessionTempTables
[$matches[1]] ??
null, null, null ];
1117 } elseif ( preg_match(
1118 '/^(?:(?:INSERT|REPLACE)\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+' . $qt . '/i',
1122 return [ $this->sessionTempTables
[$matches[1]] ??
null, null, null ];
1125 return [ null, null, null ];
1129 * @param IResultWrapper|bool $ret
1130 * @param int|null $tmpType TEMP_NORMAL or TEMP_PSEUDO_PERMANENT
1131 * @param string|null $tmpNew Name of created temp table
1132 * @param string|null $tmpDel Name of dropped temp table
1134 protected function registerTempWrites( $ret, $tmpType, $tmpNew, $tmpDel ) {
1135 if ( $ret !== false ) {
1136 if ( $tmpNew !== null ) {
1137 $this->sessionTempTables
[$tmpNew] = $tmpType;
1139 if ( $tmpDel !== null ) {
1140 unset( $this->sessionTempTables
[$tmpDel] );
1145 public function query( $sql, $fname = __METHOD__
, $flags = 0 ) {
1146 $flags = (int)$flags; // b/c; this field used to be a bool
1147 // Sanity check that the SQL query is appropriate in the current context and is
1148 // allowed for an outside caller (e.g. does not break transaction/session tracking).
1149 $this->assertQueryIsCurrentlyAllowed( $sql, $fname );
1151 // Send the query to the server and fetch any corresponding errors
1152 list( $ret, $err, $errno, $unignorable ) = $this->executeQuery( $sql, $fname, $flags );
1153 if ( $ret === false ) {
1154 $ignoreErrors = $this->hasFlags( $flags, self
::QUERY_SILENCE_ERRORS
);
1155 // Throw an error unless both the ignore flag was set and a rollback is not needed
1156 $this->reportQueryError( $err, $errno, $sql, $fname, $ignoreErrors && !$unignorable );
1159 return $this->resultObject( $ret );
1163 * Execute a query, retrying it if there is a recoverable connection loss
1165 * This is similar to query() except:
1166 * - It does not prevent all non-ROLLBACK queries if there is a corrupted transaction
1167 * - It does not disallow raw queries that are supposed to use dedicated IDatabase methods
1168 * - It does not throw exceptions for common error cases
1170 * This is meant for internal use with Database subclasses.
1172 * @param string $sql Original SQL query
1173 * @param string $fname Name of the calling function
1174 * @param int $flags Bit field of class QUERY_* constants
1175 * @return array An n-tuple of:
1176 * - mixed|bool: An object, resource, or true on success; false on failure
1177 * - string: The result of calling lastError()
1178 * - int: The result of calling lastErrno()
1179 * - bool: Whether a rollback is needed to allow future non-rollback queries
1180 * @throws DBUnexpectedError
1182 final protected function executeQuery( $sql, $fname, $flags ) {
1183 $this->assertHasConnectionHandle();
1185 $priorTransaction = $this->trxLevel();
1187 if ( $this->isWriteQuery( $sql ) ) {
1188 // In theory, non-persistent writes are allowed in read-only mode, but due to things
1189 // like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1190 $this->assertIsWritableMaster();
1191 // Do not treat temporary table writes as "meaningful writes" since they are only
1192 // visible to one session and are not permanent. Profile them as reads. Integration
1193 // tests can override this behavior via $flags.
1194 $pseudoPermanent = $this->hasFlags( $flags, self
::QUERY_PSEUDO_PERMANENT
);
1195 list( $tmpType, $tmpNew, $tmpDel ) = $this->getTempWrites( $sql, $pseudoPermanent );
1196 $isPermWrite = ( $tmpType !== self
::$TEMP_NORMAL );
1197 // DBConnRef uses QUERY_REPLICA_ROLE to enforce the replica role for raw SQL queries
1198 if ( $isPermWrite && $this->hasFlags( $flags, self
::QUERY_REPLICA_ROLE
) ) {
1199 throw new DBReadOnlyRoleError( $this, "Cannot write; target role is DB_REPLICA" );
1202 // No permanent writes in this query
1203 $isPermWrite = false;
1204 // No temporary tables written to either
1205 list( $tmpType, $tmpNew, $tmpDel ) = [ null, null, null ];
1208 // Add trace comment to the begin of the sql string, right after the operator.
1209 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
1210 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
1212 // Send the query to the server and fetch any corresponding errors.
1213 // This also doubles as a "ping" to see if the connection was dropped.
1214 list( $ret, $err, $errno, $recoverableSR, $recoverableCL, $reconnected ) =
1215 $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1217 // Check if the query failed due to a recoverable connection loss
1218 $allowRetry = !$this->hasFlags( $flags, self
::QUERY_NO_RETRY
);
1219 if ( $ret === false && $recoverableCL && $reconnected && $allowRetry ) {
1220 // Silently resend the query to the server since it is safe and possible
1221 list( $ret, $err, $errno, $recoverableSR, $recoverableCL ) =
1222 $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1225 // Register creation and dropping of temporary tables
1226 $this->registerTempWrites( $ret, $tmpType, $tmpNew, $tmpDel );
1228 $corruptedTrx = false;
1230 if ( $ret === false ) {
1231 if ( $priorTransaction ) {
1232 if ( $recoverableSR ) {
1233 # We're ignoring an error that caused just the current query to be aborted.
1234 # But log the cause so we can log a deprecation notice if a caller actually
1236 $this->trxStatusIgnoredCause
= [ $err, $errno, $fname ];
1237 } elseif ( !$recoverableCL ) {
1238 # Either the query was aborted or all queries after BEGIN where aborted.
1239 # In the first case, the only options going forward are (a) ROLLBACK, or
1240 # (b) ROLLBACK TO SAVEPOINT (if one was set). If the later case, the only
1241 # option is ROLLBACK, since the snapshots would have been released.
1242 $corruptedTrx = true; // cannot recover
1243 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
1244 $this->trxStatusCause
=
1245 $this->getQueryExceptionAndLog( $err, $errno, $sql, $fname );
1246 $this->trxStatusIgnoredCause
= null;
1251 return [ $ret, $err, $errno, $corruptedTrx ];
1255 * Wrapper for doQuery() that handles DBO_TRX, profiling, logging, affected row count
1256 * tracking, and reconnects (without retry) on query failure due to connection loss
1258 * @param string $sql Original SQL query
1259 * @param string $commentedSql SQL query with debugging/trace comment
1260 * @param bool $isPermWrite Whether the query is a (non-temporary table) write
1261 * @param string $fname Name of the calling function
1262 * @param int $flags Bit field of class QUERY_* constants
1263 * @return array An n-tuple of:
1264 * - mixed|bool: An object, resource, or true on success; false on failure
1265 * - string: The result of calling lastError()
1266 * - int: The result of calling lastErrno()
1267 * - bool: Whether a statement rollback error occured
1268 * - bool: Whether a disconnect *both* happened *and* was recoverable
1269 * - bool: Whether a reconnection attempt was *both* made *and* succeeded
1270 * @throws DBUnexpectedError
1272 private function executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags ) {
1273 $priorWritesPending = $this->writesOrCallbacksPending();
1275 if ( ( $flags & self
::QUERY_IGNORE_DBO_TRX
) == 0 ) {
1276 $this->beginIfImplied( $sql, $fname );
1279 // Keep track of whether the transaction has write queries pending
1280 if ( $isPermWrite ) {
1281 $this->lastWriteTime
= microtime( true );
1282 if ( $this->trxLevel() && !$this->trxDoneWrites
) {
1283 $this->trxDoneWrites
= true;
1284 $this->trxProfiler
->transactionWritingIn(
1285 $this->server
, $this->getDomainID(), $this->trxShortId
);
1289 $prefix = !is_null( $this->getLBInfo( 'master' ) ) ?
'query-m: ' : 'query: ';
1290 $generalizedSql = new GeneralizedSql( $sql, $this->trxShortId
, $prefix );
1292 $startTime = microtime( true );
1293 $ps = $this->profiler
1294 ?
( $this->profiler
)( $generalizedSql->stringify() )
1296 $this->affectedRowCount
= null;
1297 $this->lastQuery
= $sql;
1298 $ret = $this->doQuery( $commentedSql );
1299 $lastError = $this->lastError();
1300 $lastErrno = $this->lastErrno();
1302 $this->affectedRowCount
= $this->affectedRows();
1303 unset( $ps ); // profile out (if set)
1304 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1306 $recoverableSR = false; // recoverable statement rollback?
1307 $recoverableCL = false; // recoverable connection loss?
1308 $reconnected = false; // reconnection both attempted and succeeded?
1310 if ( $ret !== false ) {
1311 $this->lastPing
= $startTime;
1312 if ( $isPermWrite && $this->trxLevel() ) {
1313 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1314 $this->trxWriteCallers
[] = $fname;
1316 } elseif ( $this->wasConnectionError( $lastErrno ) ) {
1317 # Check if no meaningful session state was lost
1318 $recoverableCL = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1319 # Update session state tracking and try to restore the connection
1320 $reconnected = $this->replaceLostConnection( __METHOD__
);
1322 # Check if only the last query was rolled back
1323 $recoverableSR = $this->wasKnownStatementRollbackError();
1326 if ( $sql === self
::$PING_QUERY ) {
1327 $this->lastRoundTripEstimate
= $queryRuntime;
1330 $this->trxProfiler
->recordQueryCompletion(
1334 $isPermWrite ?
$this->affectedRows() : $this->numRows( $ret )
1337 // Avoid the overhead of logging calls unless debug mode is enabled
1338 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
1339 $this->queryLogger
->debug(
1340 "{method} [{runtime}s] {db_host}: $sql",
1343 'db_host' => $this->getServer(),
1344 'domain' => $this->getDomainID(),
1345 'runtime' => round( $queryRuntime, 3 )
1350 return [ $ret, $lastError, $lastErrno, $recoverableSR, $recoverableCL, $reconnected ];
1354 * Start an implicit transaction if DBO_TRX is enabled and no transaction is active
1356 * @param string $sql
1357 * @param string $fname
1359 private function beginIfImplied( $sql, $fname ) {
1361 !$this->trxLevel() &&
1362 $this->getFlag( self
::DBO_TRX
) &&
1363 $this->isTransactableQuery( $sql )
1365 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
1366 $this->trxAutomatic
= true;
1371 * Update the estimated run-time of a query, not counting large row lock times
1373 * LoadBalancer can be set to rollback transactions that will create huge replication
1374 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1375 * queries, like inserting a row can take a long time due to row locking. This method
1376 * uses some simple heuristics to discount those cases.
1378 * @param string $sql A SQL write query
1379 * @param float $runtime Total runtime, including RTT
1380 * @param int $affected Affected row count
1382 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1383 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1384 $indicativeOfReplicaRuntime = true;
1385 if ( $runtime > self
::$SLOW_WRITE_SEC ) {
1386 $verb = $this->getQueryVerb( $sql );
1387 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1388 if ( $verb === 'INSERT' ) {
1389 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::$SMALL_WRITE_ROWS;
1390 } elseif ( $verb === 'REPLACE' ) {
1391 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::$SMALL_WRITE_ROWS / 2;
1395 $this->trxWriteDuration +
= $runtime;
1396 $this->trxWriteQueryCount +
= 1;
1397 $this->trxWriteAffectedRows +
= $affected;
1398 if ( $indicativeOfReplicaRuntime ) {
1399 $this->trxWriteAdjDuration +
= $runtime;
1400 $this->trxWriteAdjQueryCount +
= 1;
1405 * Error out if the DB is not in a valid state for a query via query()
1407 * @param string $sql
1408 * @param string $fname
1409 * @throws DBTransactionStateError
1411 private function assertQueryIsCurrentlyAllowed( $sql, $fname ) {
1412 $verb = $this->getQueryVerb( $sql );
1413 if ( $verb === 'USE' ) {
1414 throw new DBUnexpectedError( $this, "Got USE query; use selectDomain() instead" );
1417 if ( $verb === 'ROLLBACK' ) { // transaction/savepoint
1421 if ( $this->trxStatus
< self
::STATUS_TRX_OK
) {
1422 throw new DBTransactionStateError(
1424 "Cannot execute query from $fname while transaction status is ERROR",
1426 $this->trxStatusCause
1428 } elseif ( $this->trxStatus
=== self
::STATUS_TRX_OK
&& $this->trxStatusIgnoredCause
) {
1429 list( $iLastError, $iLastErrno, $iFname ) = $this->trxStatusIgnoredCause
;
1430 call_user_func( $this->deprecationLogger
,
1431 "Caller from $fname ignored an error originally raised from $iFname: " .
1432 "[$iLastErrno] $iLastError"
1434 $this->trxStatusIgnoredCause
= null;
1438 public function assertNoOpenTransactions() {
1439 if ( $this->explicitTrxActive() ) {
1440 throw new DBTransactionError(
1442 "Explicit transaction still active. A caller may have caught an error. "
1443 . "Open transactions: " . $this->flatAtomicSectionList()
1449 * Determine whether it is safe to retry queries after a database connection is lost
1451 * @param string $sql SQL query
1452 * @param bool $priorWritesPending Whether there is a transaction open with
1453 * possible write queries or transaction pre-commit/idle callbacks
1454 * waiting on it to finish.
1455 * @return bool True if it is safe to retry the query, false otherwise
1457 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1458 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1459 # Dropped connections also mean that named locks are automatically released.
1460 # Only allow error suppression in autocommit mode or when the lost transaction
1461 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1462 if ( $this->sessionNamedLocks
) {
1463 return false; // possible critical section violation
1464 } elseif ( $this->sessionTempTables
) {
1465 return false; // tables might be queried latter
1466 } elseif ( $sql === 'COMMIT' ) {
1467 return !$priorWritesPending; // nothing written anyway? (T127428)
1468 } elseif ( $sql === 'ROLLBACK' ) {
1469 return true; // transaction lost...which is also what was requested :)
1470 } elseif ( $this->explicitTrxActive() ) {
1471 return false; // don't drop atomocity and explicit snapshots
1472 } elseif ( $priorWritesPending ) {
1473 return false; // prior writes lost from implicit transaction
1480 * Clean things up after session (and thus transaction) loss before reconnect
1482 private function handleSessionLossPreconnect() {
1483 // Clean up tracking of session-level things...
1484 // https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
1485 // https://www.postgresql.org/docs/9.2/static/sql-createtable.html (ignoring ON COMMIT)
1486 $this->sessionTempTables
= [];
1487 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1488 // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1489 $this->sessionNamedLocks
= [];
1490 // Session loss implies transaction loss
1491 $oldTrxShortId = $this->consumeTrxShortId();
1492 $this->trxAtomicCounter
= 0;
1493 $this->trxIdleCallbacks
= []; // T67263; transaction already lost
1494 $this->trxPreCommitCallbacks
= []; // T67263; transaction already lost
1495 // @note: leave trxRecurringCallbacks in place
1496 if ( $this->trxDoneWrites
) {
1497 $this->trxProfiler
->transactionWritingOut(
1499 $this->getDomainID(),
1501 $this->pendingWriteQueryDuration( self
::ESTIMATE_TOTAL
),
1502 $this->trxWriteAffectedRows
1508 * Clean things up after session (and thus transaction) loss after reconnect
1510 private function handleSessionLossPostconnect() {
1512 // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
1513 // If callback suppression is set then the array will remain unhandled.
1514 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1515 } catch ( Exception
$ex ) {
1516 // Already logged; move on...
1519 // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener()
1520 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1521 } catch ( Exception
$ex ) {
1522 // Already logged; move on...
1527 * Reset the transaction ID and return the old one
1529 * @return string The old transaction ID or the empty string if there wasn't one
1531 private function consumeTrxShortId() {
1532 $old = $this->trxShortId
;
1533 $this->trxShortId
= '';
1539 * Checks whether the cause of the error is detected to be a timeout.
1541 * It returns false by default, and not all engines support detecting this yet.
1542 * If this returns false, it will be treated as a generic query error.
1544 * @param string $error Error text
1545 * @param int $errno Error number
1548 protected function wasQueryTimeout( $error, $errno ) {
1553 * Report a query error. Log the error, and if neither the object ignore
1554 * flag nor the $ignoreErrors flag is set, throw a DBQueryError.
1556 * @param string $error
1558 * @param string $sql
1559 * @param string $fname
1560 * @param bool $ignore
1561 * @throws DBQueryError
1563 public function reportQueryError( $error, $errno, $sql, $fname, $ignore = false ) {
1565 $this->queryLogger
->debug( "SQL ERROR (ignored): $error" );
1567 throw $this->getQueryExceptionAndLog( $error, $errno, $sql, $fname );
1572 * @param string $error
1573 * @param string|int $errno
1574 * @param string $sql
1575 * @param string $fname
1578 private function getQueryExceptionAndLog( $error, $errno, $sql, $fname ) {
1579 $this->queryLogger
->error(
1580 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1581 $this->getLogContext( [
1582 'method' => __METHOD__
,
1585 'sql1line' => mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 ),
1587 'trace' => ( new RuntimeException() )->getTraceAsString()
1591 if ( $this->wasQueryTimeout( $error, $errno ) ) {
1592 $e = new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1593 } elseif ( $this->wasConnectionError( $errno ) ) {
1594 $e = new DBQueryDisconnectedError( $this, $error, $errno, $sql, $fname );
1596 $e = new DBQueryError( $this, $error, $errno, $sql, $fname );
1603 * @param string $error
1604 * @return DBConnectionError
1606 final protected function newExceptionAfterConnectError( $error ) {
1607 // Connection was not fully initialized and is not safe for use
1610 $this->connLogger
->error(
1611 "Error connecting to {db_server} as user {db_user}: {error}",
1612 $this->getLogContext( [
1614 'trace' => ( new RuntimeException() )->getTraceAsString()
1618 return new DBConnectionError( $this, $error );
1621 public function freeResult( $res ) {
1624 public function selectField(
1625 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1627 if ( $var === '*' ) { // sanity
1628 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1631 if ( !is_array( $options ) ) {
1632 $options = [ $options ];
1635 $options['LIMIT'] = 1;
1637 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1638 if ( $res === false ) {
1639 throw new DBUnexpectedError( $this, "Got false from select()" );
1642 $row = $this->fetchRow( $res );
1643 if ( $row === false ) {
1647 return reset( $row );
1650 public function selectFieldValues(
1651 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1653 if ( $var === '*' ) { // sanity
1654 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1655 } elseif ( !is_string( $var ) ) { // sanity
1656 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1659 if ( !is_array( $options ) ) {
1660 $options = [ $options ];
1663 $res = $this->select( $table, [ 'value' => $var ], $cond, $fname, $options, $join_conds );
1664 if ( $res === false ) {
1665 throw new DBUnexpectedError( $this, "Got false from select()" );
1669 foreach ( $res as $row ) {
1670 $values[] = $row->value
;
1677 * Returns an optional USE INDEX clause to go after the table, and a
1678 * string to go at the end of the query.
1680 * @param array $options Associative array of options to be turned into
1681 * an SQL query, valid keys are listed in the function.
1683 * @see Database::select()
1685 protected function makeSelectOptions( $options ) {
1686 $preLimitTail = $postLimitTail = '';
1691 foreach ( $options as $key => $option ) {
1692 if ( is_numeric( $key ) ) {
1693 $noKeyOptions[$option] = true;
1697 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1699 $preLimitTail .= $this->makeOrderBy( $options );
1701 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1702 $postLimitTail .= ' FOR UPDATE';
1705 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1706 $postLimitTail .= ' LOCK IN SHARE MODE';
1709 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1710 $startOpts .= 'DISTINCT';
1713 # Various MySQL extensions
1714 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1715 $startOpts .= ' /*! STRAIGHT_JOIN */';
1718 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1719 $startOpts .= ' HIGH_PRIORITY';
1722 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1723 $startOpts .= ' SQL_BIG_RESULT';
1726 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1727 $startOpts .= ' SQL_BUFFER_RESULT';
1730 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1731 $startOpts .= ' SQL_SMALL_RESULT';
1734 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1735 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1738 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1739 $startOpts .= ' SQL_CACHE';
1742 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1743 $startOpts .= ' SQL_NO_CACHE';
1746 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1747 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1751 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1752 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1757 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1761 * Returns an optional GROUP BY with an optional HAVING
1763 * @param array $options Associative array of options
1765 * @see Database::select()
1768 protected function makeGroupByWithHaving( $options ) {
1770 if ( isset( $options['GROUP BY'] ) ) {
1771 $gb = is_array( $options['GROUP BY'] )
1772 ?
implode( ',', $options['GROUP BY'] )
1773 : $options['GROUP BY'];
1774 $sql .= ' GROUP BY ' . $gb;
1776 if ( isset( $options['HAVING'] ) ) {
1777 $having = is_array( $options['HAVING'] )
1778 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1779 : $options['HAVING'];
1780 $sql .= ' HAVING ' . $having;
1787 * Returns an optional ORDER BY
1789 * @param array $options Associative array of options
1791 * @see Database::select()
1794 protected function makeOrderBy( $options ) {
1795 if ( isset( $options['ORDER BY'] ) ) {
1796 $ob = is_array( $options['ORDER BY'] )
1797 ?
implode( ',', $options['ORDER BY'] )
1798 : $options['ORDER BY'];
1800 return ' ORDER BY ' . $ob;
1806 public function select(
1807 $table, $vars, $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1809 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1811 return $this->query( $sql, $fname );
1814 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1815 $options = [], $join_conds = []
1817 if ( is_array( $vars ) ) {
1818 $fields = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1823 $options = (array)$options;
1824 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1825 ?
$options['USE INDEX']
1828 isset( $options['IGNORE INDEX'] ) &&
1829 is_array( $options['IGNORE INDEX'] )
1831 ?
$options['IGNORE INDEX']
1835 $this->selectOptionsIncludeLocking( $options ) &&
1836 $this->selectFieldsOrOptionsAggregate( $vars, $options )
1838 // Some DB types (postgres/oracle) disallow FOR UPDATE with aggregate
1839 // functions. Discourage use of such queries to encourage compatibility.
1841 $this->deprecationLogger
,
1842 __METHOD__
. ": aggregation used with a locking SELECT ($fname)"
1846 if ( is_array( $table ) ) {
1848 $this->tableNamesWithIndexClauseOrJOIN(
1849 $table, $useIndexes, $ignoreIndexes, $join_conds );
1850 } elseif ( $table != '' ) {
1852 $this->tableNamesWithIndexClauseOrJOIN(
1853 [ $table ], $useIndexes, $ignoreIndexes, [] );
1858 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1859 $this->makeSelectOptions( $options );
1861 if ( is_array( $conds ) ) {
1862 $conds = $this->makeList( $conds, self
::LIST_AND
);
1865 if ( $conds === null ||
$conds === false ) {
1866 $this->queryLogger
->warning(
1870 . ' with incorrect parameters: $conds must be a string or an array'
1875 if ( $conds === '' ||
$conds === '*' ) {
1876 $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex $preLimitTail";
1877 } elseif ( is_string( $conds ) ) {
1878 $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex " .
1879 "WHERE $conds $preLimitTail";
1881 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1884 if ( isset( $options['LIMIT'] ) ) {
1885 $sql = $this->limitResult( $sql, $options['LIMIT'],
1886 $options['OFFSET'] ??
false );
1888 $sql = "$sql $postLimitTail";
1890 if ( isset( $options['EXPLAIN'] ) ) {
1891 $sql = 'EXPLAIN ' . $sql;
1897 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1898 $options = [], $join_conds = []
1900 $options = (array)$options;
1901 $options['LIMIT'] = 1;
1903 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1904 if ( $res === false ) {
1905 throw new DBUnexpectedError( $this, "Got false from select()" );
1908 if ( !$this->numRows( $res ) ) {
1912 return $this->fetchObject( $res );
1915 public function estimateRowCount(
1916 $table, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1918 $conds = $this->normalizeConditions( $conds, $fname );
1919 $column = $this->extractSingleFieldFromList( $var );
1920 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1921 $conds[] = "$column IS NOT NULL";
1924 $res = $this->select(
1925 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1927 $row = $res ?
$this->fetchRow( $res ) : [];
1929 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1932 public function selectRowCount(
1933 $tables, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1935 $conds = $this->normalizeConditions( $conds, $fname );
1936 $column = $this->extractSingleFieldFromList( $var );
1937 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1938 $conds[] = "$column IS NOT NULL";
1941 $res = $this->select(
1943 'tmp_count' => $this->buildSelectSubquery(
1952 [ 'rowcount' => 'COUNT(*)' ],
1956 $row = $res ?
$this->fetchRow( $res ) : [];
1958 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1962 * @param string|array $options
1965 private function selectOptionsIncludeLocking( $options ) {
1966 $options = (array)$options;
1967 foreach ( [ 'FOR UPDATE', 'LOCK IN SHARE MODE' ] as $lock ) {
1968 if ( in_array( $lock, $options, true ) ) {
1977 * @param array|string $fields
1978 * @param array|string $options
1981 private function selectFieldsOrOptionsAggregate( $fields, $options ) {
1982 foreach ( (array)$options as $key => $value ) {
1983 if ( is_string( $key ) ) {
1984 if ( preg_match( '/^(?:GROUP BY|HAVING)$/i', $key ) ) {
1987 } elseif ( is_string( $value ) ) {
1988 if ( preg_match( '/^(?:DISTINCT|DISTINCTROW)$/i', $value ) ) {
1994 $regex = '/^(?:COUNT|MIN|MAX|SUM|GROUP_CONCAT|LISTAGG|ARRAY_AGG)\s*\\(/i';
1995 foreach ( (array)$fields as $field ) {
1996 if ( is_string( $field ) && preg_match( $regex, $field ) ) {
2005 * @param array|string $conds
2006 * @param string $fname
2009 final protected function normalizeConditions( $conds, $fname ) {
2010 if ( $conds === null ||
$conds === false ) {
2011 $this->queryLogger
->warning(
2015 . ' with incorrect parameters: $conds must be a string or an array'
2020 if ( !is_array( $conds ) ) {
2021 $conds = ( $conds === '' ) ?
[] : [ $conds ];
2028 * @param array|string $var Field parameter in the style of select()
2029 * @return string|null Column name or null; ignores aliases
2030 * @throws DBUnexpectedError Errors out if multiple columns are given
2032 final protected function extractSingleFieldFromList( $var ) {
2033 if ( is_array( $var ) ) {
2036 } elseif ( count( $var ) == 1 ) {
2037 $column = $var[0] ??
reset( $var );
2039 throw new DBUnexpectedError( $this, __METHOD__
. ': got multiple columns' );
2048 public function lockForUpdate(
2049 $table, $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
2051 if ( !$this->trxLevel() && !$this->getFlag( self
::DBO_TRX
) ) {
2052 throw new DBUnexpectedError(
2054 __METHOD__
. ': no transaction is active nor is DBO_TRX set'
2058 $options = (array)$options;
2059 $options[] = 'FOR UPDATE';
2061 return $this->selectRowCount( $table, '*', $conds, $fname, $options, $join_conds );
2064 public function fieldExists( $table, $field, $fname = __METHOD__
) {
2065 $info = $this->fieldInfo( $table, $field );
2070 public function indexExists( $table, $index, $fname = __METHOD__
) {
2071 if ( !$this->tableExists( $table ) ) {
2075 $info = $this->indexInfo( $table, $index, $fname );
2076 if ( is_null( $info ) ) {
2079 return $info !== false;
2083 abstract public function tableExists( $table, $fname = __METHOD__
);
2085 public function indexUnique( $table, $index ) {
2086 $indexInfo = $this->indexInfo( $table, $index );
2088 if ( !$indexInfo ) {
2092 return !$indexInfo[0]->Non_unique
;
2096 * Helper for Database::insert().
2098 * @param array $options
2101 protected function makeInsertOptions( $options ) {
2102 return implode( ' ', $options );
2105 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
2106 # No rows to insert, easy just return now
2107 if ( !count( $a ) ) {
2111 $table = $this->tableName( $table );
2113 if ( !is_array( $options ) ) {
2114 $options = [ $options ];
2117 $options = $this->makeInsertOptions( $options );
2119 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
2121 $keys = array_keys( $a[0] );
2124 $keys = array_keys( $a );
2127 $sql = 'INSERT ' . $options .
2128 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
2132 foreach ( $a as $row ) {
2138 $sql .= '(' . $this->makeList( $row ) . ')';
2141 $sql .= '(' . $this->makeList( $a ) . ')';
2144 $this->query( $sql, $fname );
2150 * Make UPDATE options array for Database::makeUpdateOptions
2152 * @param array $options
2155 protected function makeUpdateOptionsArray( $options ) {
2156 if ( !is_array( $options ) ) {
2157 $options = [ $options ];
2162 if ( in_array( 'IGNORE', $options ) ) {
2170 * Make UPDATE options for the Database::update function
2172 * @param array $options The options passed to Database::update
2175 protected function makeUpdateOptions( $options ) {
2176 $opts = $this->makeUpdateOptionsArray( $options );
2178 return implode( ' ', $opts );
2181 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
2182 $table = $this->tableName( $table );
2183 $opts = $this->makeUpdateOptions( $options );
2184 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
2186 if ( $conds !== [] && $conds !== '*' ) {
2187 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
2190 $this->query( $sql, $fname );
2195 public function makeList( $a, $mode = self
::LIST_COMMA
) {
2196 if ( !is_array( $a ) ) {
2197 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
2203 foreach ( $a as $field => $value ) {
2205 if ( $mode == self
::LIST_AND
) {
2207 } elseif ( $mode == self
::LIST_OR
) {
2216 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
2217 $list .= "($value)";
2218 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
2221 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
2223 // Remove null from array to be handled separately if found
2224 $includeNull = false;
2225 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2226 $includeNull = true;
2227 unset( $value[$nullKey] );
2229 if ( count( $value ) == 0 && !$includeNull ) {
2230 throw new InvalidArgumentException(
2231 __METHOD__
. ": empty input for field $field" );
2232 } elseif ( count( $value ) == 0 ) {
2233 // only check if $field is null
2234 $list .= "$field IS NULL";
2236 // IN clause contains at least one valid element
2237 if ( $includeNull ) {
2238 // Group subconditions to ensure correct precedence
2241 if ( count( $value ) == 1 ) {
2242 // Special-case single values, as IN isn't terribly efficient
2243 // Don't necessarily assume the single key is 0; we don't
2244 // enforce linear numeric ordering on other arrays here.
2245 $value = array_values( $value )[0];
2246 $list .= $field . " = " . $this->addQuotes( $value );
2248 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2250 // if null present in array, append IS NULL
2251 if ( $includeNull ) {
2252 $list .= " OR $field IS NULL)";
2255 } elseif ( $value === null ) {
2256 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
2257 $list .= "$field IS ";
2258 } elseif ( $mode == self
::LIST_SET
) {
2259 $list .= "$field = ";
2264 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
2266 $list .= "$field = ";
2268 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
2275 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2278 foreach ( $data as $base => $sub ) {
2279 if ( count( $sub ) ) {
2280 $conds[] = $this->makeList(
2281 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
2287 return $this->makeList( $conds, self
::LIST_OR
);
2289 // Nothing to search for...
2294 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2298 public function bitNot( $field ) {
2302 public function bitAnd( $fieldLeft, $fieldRight ) {
2303 return "($fieldLeft & $fieldRight)";
2306 public function bitOr( $fieldLeft, $fieldRight ) {
2307 return "($fieldLeft | $fieldRight)";
2310 public function buildConcat( $stringList ) {
2311 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2314 public function buildGroupConcatField(
2315 $delim, $table, $field, $conds = '', $join_conds = []
2317 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2319 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
2322 public function buildSubstring( $input, $startPosition, $length = null ) {
2323 $this->assertBuildSubstringParams( $startPosition, $length );
2324 $functionBody = "$input FROM $startPosition";
2325 if ( $length !== null ) {
2326 $functionBody .= " FOR $length";
2328 return 'SUBSTRING(' . $functionBody . ')';
2332 * Check type and bounds for parameters to self::buildSubstring()
2334 * All supported databases have substring functions that behave the same for
2335 * positive $startPosition and non-negative $length, but behaviors differ when
2336 * given 0 or negative $startPosition or negative $length. The simplest
2337 * solution to that is to just forbid those values.
2339 * @param int $startPosition
2340 * @param int|null $length
2343 protected function assertBuildSubstringParams( $startPosition, $length ) {
2344 if ( !is_int( $startPosition ) ||
$startPosition <= 0 ) {
2345 throw new InvalidArgumentException(
2346 '$startPosition must be a positive integer'
2349 if ( !( is_int( $length ) && $length >= 0 ||
$length === null ) ) {
2350 throw new InvalidArgumentException(
2351 '$length must be null or an integer greater than or equal to 0'
2356 public function buildStringCast( $field ) {
2357 // In theory this should work for any standards-compliant
2358 // SQL implementation, although it may not be the best way to do it.
2359 return "CAST( $field AS CHARACTER )";
2362 public function buildIntegerCast( $field ) {
2363 return 'CAST( ' . $field . ' AS INTEGER )';
2366 public function buildSelectSubquery(
2367 $table, $vars, $conds = '', $fname = __METHOD__
,
2368 $options = [], $join_conds = []
2370 return new Subquery(
2371 $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2375 public function databasesAreIndependent() {
2379 final public function selectDB( $db ) {
2380 $this->selectDomain( new DatabaseDomain(
2382 $this->currentDomain
->getSchema(),
2383 $this->currentDomain
->getTablePrefix()
2389 final public function selectDomain( $domain ) {
2390 $this->doSelectDomain( DatabaseDomain
::newFromId( $domain ) );
2394 * @param DatabaseDomain $domain
2395 * @throws DBConnectionError
2399 protected function doSelectDomain( DatabaseDomain
$domain ) {
2400 $this->currentDomain
= $domain;
2403 public function getDBname() {
2404 return $this->currentDomain
->getDatabase();
2407 public function getServer() {
2408 return $this->server
;
2411 public function tableName( $name, $format = 'quoted' ) {
2412 if ( $name instanceof Subquery
) {
2413 throw new DBUnexpectedError(
2415 __METHOD__
. ': got Subquery instance when expecting a string'
2419 # Skip the entire process when we have a string quoted on both ends.
2420 # Note that we check the end so that we will still quote any use of
2421 # use of `database`.table. But won't break things if someone wants
2422 # to query a database table with a dot in the name.
2423 if ( $this->isQuotedIdentifier( $name ) ) {
2427 # Lets test for any bits of text that should never show up in a table
2428 # name. Basically anything like JOIN or ON which are actually part of
2429 # SQL queries, but may end up inside of the table value to combine
2430 # sql. Such as how the API is doing.
2431 # Note that we use a whitespace test rather than a \b test to avoid
2432 # any remote case where a word like on may be inside of a table name
2433 # surrounded by symbols which may be considered word breaks.
2434 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2435 $this->queryLogger
->warning(
2436 __METHOD__
. ": use of subqueries is not supported this way",
2437 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
2443 # Split database and table into proper variables.
2444 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2446 # Quote $table and apply the prefix if not quoted.
2447 # $tableName might be empty if this is called from Database::replaceVars()
2448 $tableName = "{$prefix}{$table}";
2449 if ( $format === 'quoted'
2450 && !$this->isQuotedIdentifier( $tableName )
2451 && $tableName !== ''
2453 $tableName = $this->addIdentifierQuotes( $tableName );
2456 # Quote $schema and $database and merge them with the table name if needed
2457 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2458 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2464 * Get the table components needed for a query given the currently selected database
2466 * @param string $name Table name in the form of db.schema.table, db.table, or table
2467 * @return array (DB name or "" for default, schema name, table prefix, table name)
2469 protected function qualifiedTableComponents( $name ) {
2470 # We reverse the explode so that database.table and table both output the correct table.
2471 $dbDetails = explode( '.', $name, 3 );
2472 if ( count( $dbDetails ) == 3 ) {
2473 list( $database, $schema, $table ) = $dbDetails;
2474 # We don't want any prefix added in this case
2476 } elseif ( count( $dbDetails ) == 2 ) {
2477 list( $database, $table ) = $dbDetails;
2478 # We don't want any prefix added in this case
2480 # In dbs that support it, $database may actually be the schema
2481 # but that doesn't affect any of the functionality here
2484 list( $table ) = $dbDetails;
2485 if ( isset( $this->tableAliases
[$table] ) ) {
2486 $database = $this->tableAliases
[$table]['dbname'];
2487 $schema = is_string( $this->tableAliases
[$table]['schema'] )
2488 ?
$this->tableAliases
[$table]['schema']
2489 : $this->relationSchemaQualifier();
2490 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
2491 ?
$this->tableAliases
[$table]['prefix']
2492 : $this->tablePrefix();
2495 $schema = $this->relationSchemaQualifier(); # Default schema
2496 $prefix = $this->tablePrefix(); # Default prefix
2500 return [ $database, $schema, $prefix, $table ];
2504 * @param string|null $namespace Database or schema
2505 * @param string $relation Name of table, view, sequence, etc...
2506 * @param string $format One of (raw, quoted)
2507 * @return string Relation name with quoted and merged $namespace as needed
2509 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2510 if ( strlen( $namespace ) ) {
2511 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2512 $namespace = $this->addIdentifierQuotes( $namespace );
2514 $relation = $namespace . '.' . $relation;
2520 public function tableNames() {
2521 $inArray = func_get_args();
2524 foreach ( $inArray as $name ) {
2525 $retVal[$name] = $this->tableName( $name );
2531 public function tableNamesN() {
2532 $inArray = func_get_args();
2535 foreach ( $inArray as $name ) {
2536 $retVal[] = $this->tableName( $name );
2543 * Get an aliased table name
2545 * This returns strings like "tableName AS newTableName" for aliased tables
2546 * and "(SELECT * from tableA) newTablename" for subqueries (e.g. derived tables)
2548 * @see Database::tableName()
2549 * @param string|Subquery $table Table name or object with a 'sql' field
2550 * @param string|bool $alias Table alias (optional)
2551 * @return string SQL name for aliased table. Will not alias a table to its own name
2553 protected function tableNameWithAlias( $table, $alias = false ) {
2554 if ( is_string( $table ) ) {
2555 $quotedTable = $this->tableName( $table );
2556 } elseif ( $table instanceof Subquery
) {
2557 $quotedTable = (string)$table;
2559 throw new InvalidArgumentException( "Table must be a string or Subquery" );
2562 if ( $alias === false ||
$alias === $table ) {
2563 if ( $table instanceof Subquery
) {
2564 throw new InvalidArgumentException( "Subquery table missing alias" );
2567 return $quotedTable;
2569 return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2574 * Gets an array of aliased table names
2576 * @param array $tables [ [alias] => table ]
2577 * @return string[] See tableNameWithAlias()
2579 protected function tableNamesWithAlias( $tables ) {
2581 foreach ( $tables as $alias => $table ) {
2582 if ( is_numeric( $alias ) ) {
2585 $retval[] = $this->tableNameWithAlias( $table, $alias );
2592 * Get an aliased field name
2593 * e.g. fieldName AS newFieldName
2595 * @param string $name Field name
2596 * @param string|bool $alias Alias (optional)
2597 * @return string SQL name for aliased field. Will not alias a field to its own name
2599 protected function fieldNameWithAlias( $name, $alias = false ) {
2600 if ( !$alias ||
(string)$alias === (string)$name ) {
2603 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2608 * Gets an array of aliased field names
2610 * @param array $fields [ [alias] => field ]
2611 * @return string[] See fieldNameWithAlias()
2613 protected function fieldNamesWithAlias( $fields ) {
2615 foreach ( $fields as $alias => $field ) {
2616 if ( is_numeric( $alias ) ) {
2619 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2626 * Get the aliased table name clause for a FROM clause
2627 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2629 * @param array $tables ( [alias] => table )
2630 * @param array $use_index Same as for select()
2631 * @param array $ignore_index Same as for select()
2632 * @param array $join_conds Same as for select()
2635 protected function tableNamesWithIndexClauseOrJOIN(
2636 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2640 $use_index = (array)$use_index;
2641 $ignore_index = (array)$ignore_index;
2642 $join_conds = (array)$join_conds;
2644 foreach ( $tables as $alias => $table ) {
2645 if ( !is_string( $alias ) ) {
2646 // No alias? Set it equal to the table name
2650 if ( is_array( $table ) ) {
2651 // A parenthesized group
2652 if ( count( $table ) > 1 ) {
2653 $joinedTable = '(' .
2654 $this->tableNamesWithIndexClauseOrJOIN(
2655 $table, $use_index, $ignore_index, $join_conds ) . ')';
2658 $innerTable = reset( $table );
2659 $innerAlias = key( $table );
2660 $joinedTable = $this->tableNameWithAlias(
2662 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2666 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2669 // Is there a JOIN clause for this table?
2670 if ( isset( $join_conds[$alias] ) ) {
2671 list( $joinType, $conds ) = $join_conds[$alias];
2672 $tableClause = $joinType;
2673 $tableClause .= ' ' . $joinedTable;
2674 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2675 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2677 $tableClause .= ' ' . $use;
2680 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2681 $ignore = $this->ignoreIndexClause(
2682 implode( ',', (array)$ignore_index[$alias] ) );
2683 if ( $ignore != '' ) {
2684 $tableClause .= ' ' . $ignore;
2687 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2689 $tableClause .= ' ON (' . $on . ')';
2692 $retJOIN[] = $tableClause;
2693 } elseif ( isset( $use_index[$alias] ) ) {
2694 // Is there an INDEX clause for this table?
2695 $tableClause = $joinedTable;
2696 $tableClause .= ' ' . $this->useIndexClause(
2697 implode( ',', (array)$use_index[$alias] )
2700 $ret[] = $tableClause;
2701 } elseif ( isset( $ignore_index[$alias] ) ) {
2702 // Is there an INDEX clause for this table?
2703 $tableClause = $joinedTable;
2704 $tableClause .= ' ' . $this->ignoreIndexClause(
2705 implode( ',', (array)$ignore_index[$alias] )
2708 $ret[] = $tableClause;
2710 $tableClause = $joinedTable;
2712 $ret[] = $tableClause;
2716 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2717 $implicitJoins = implode( ',', $ret );
2718 $explicitJoins = implode( ' ', $retJOIN );
2720 // Compile our final table clause
2721 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2725 * Allows for index remapping in queries where this is not consistent across DBMS
2727 * @param string $index
2730 protected function indexName( $index ) {
2731 return $this->indexAliases
[$index] ??
$index;
2734 public function addQuotes( $s ) {
2735 if ( $s instanceof Blob
) {
2738 if ( $s === null ) {
2740 } elseif ( is_bool( $s ) ) {
2743 # This will also quote numeric values. This should be harmless,
2744 # and protects against weird problems that occur when they really
2745 # _are_ strings such as article titles and string->number->string
2746 # conversion is not 1:1.
2747 return "'" . $this->strencode( $s ) . "'";
2751 public function addIdentifierQuotes( $s ) {
2752 return '"' . str_replace( '"', '""', $s ) . '"';
2756 * Returns if the given identifier looks quoted or not according to
2757 * the database convention for quoting identifiers .
2759 * @note Do not use this to determine if untrusted input is safe.
2760 * A malicious user can trick this function.
2761 * @param string $name
2764 public function isQuotedIdentifier( $name ) {
2765 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2770 * @param string $escapeChar
2773 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2774 return str_replace( [ $escapeChar, '%', '_' ],
2775 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2779 public function buildLike( $param, ...$params ) {
2780 if ( is_array( $param ) ) {
2783 $params = func_get_args();
2788 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2789 // may escape backslashes, creating problems of double escaping. The `
2790 // character has good cross-DBMS compatibility, avoiding special operators
2791 // in MS SQL like ^ and %
2794 foreach ( $params as $value ) {
2795 if ( $value instanceof LikeMatch
) {
2796 $s .= $value->toString();
2798 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2803 $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2806 public function anyChar() {
2807 return new LikeMatch( '_' );
2810 public function anyString() {
2811 return new LikeMatch( '%' );
2814 public function nextSequenceValue( $seqName ) {
2819 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2820 * is only needed because a) MySQL must be as efficient as possible due to
2821 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2822 * which index to pick. Anyway, other databases might have different
2823 * indexes on a given table. So don't bother overriding this unless you're
2825 * @param string $index
2828 public function useIndexClause( $index ) {
2833 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2834 * is only needed because a) MySQL must be as efficient as possible due to
2835 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2836 * which index to pick. Anyway, other databases might have different
2837 * indexes on a given table. So don't bother overriding this unless you're
2839 * @param string $index
2842 public function ignoreIndexClause( $index ) {
2846 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2847 if ( count( $rows ) == 0 ) {
2851 $uniqueIndexes = (array)$uniqueIndexes;
2853 if ( !is_array( reset( $rows ) ) ) {
2858 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2859 $affectedRowCount = 0;
2860 foreach ( $rows as $row ) {
2861 // Delete rows which collide with this one
2862 $indexWhereClauses = [];
2863 foreach ( $uniqueIndexes as $index ) {
2864 $indexColumns = (array)$index;
2865 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2866 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2867 throw new DBUnexpectedError(
2869 'New record does not provide all values for unique key (' .
2870 implode( ', ', $indexColumns ) . ')'
2872 } elseif ( in_array( null, $indexRowValues, true ) ) {
2873 throw new DBUnexpectedError(
2875 'New record has a null value for unique key (' .
2876 implode( ', ', $indexColumns ) . ')'
2879 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2882 if ( $indexWhereClauses ) {
2883 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2884 $affectedRowCount +
= $this->affectedRows();
2887 // Now insert the row
2888 $this->insert( $table, $row, $fname );
2889 $affectedRowCount +
= $this->affectedRows();
2891 $this->endAtomic( $fname );
2892 $this->affectedRowCount
= $affectedRowCount;
2893 } catch ( Exception
$e ) {
2894 $this->cancelAtomic( $fname );
2900 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2903 * @param string $table Table name
2904 * @param array|string $rows Row(s) to insert
2905 * @param string $fname Caller function name
2907 protected function nativeReplace( $table, $rows, $fname ) {
2908 $table = $this->tableName( $table );
2911 if ( !is_array( reset( $rows ) ) ) {
2915 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2918 foreach ( $rows as $row ) {
2925 $sql .= '(' . $this->makeList( $row ) . ')';
2928 $this->query( $sql, $fname );
2931 public function upsert( $table, array $rows, $uniqueIndexes, array $set,
2934 if ( $rows === [] ) {
2935 return true; // nothing to do
2938 $uniqueIndexes = (array)$uniqueIndexes;
2939 if ( !is_array( reset( $rows ) ) ) {
2943 if ( count( $uniqueIndexes ) ) {
2944 $clauses = []; // list WHERE clauses that each identify a single row
2945 foreach ( $rows as $row ) {
2946 foreach ( $uniqueIndexes as $index ) {
2947 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2948 $rowKey = []; // unique key to this row
2949 foreach ( $index as $column ) {
2950 $rowKey[$column] = $row[$column];
2952 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2955 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2960 $affectedRowCount = 0;
2962 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2963 # Update any existing conflicting row(s)
2964 if ( $where !== false ) {
2965 $this->update( $table, $set, $where, $fname );
2966 $affectedRowCount +
= $this->affectedRows();
2968 # Now insert any non-conflicting row(s)
2969 $this->insert( $table, $rows, $fname, [ 'IGNORE' ] );
2970 $affectedRowCount +
= $this->affectedRows();
2971 $this->endAtomic( $fname );
2972 $this->affectedRowCount
= $affectedRowCount;
2973 } catch ( Exception
$e ) {
2974 $this->cancelAtomic( $fname );
2981 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2985 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2988 $delTable = $this->tableName( $delTable );
2989 $joinTable = $this->tableName( $joinTable );
2990 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2991 if ( $conds != '*' ) {
2992 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2996 $this->query( $sql, $fname );
2999 public function textFieldSize( $table, $field ) {
3000 $table = $this->tableName( $table );
3001 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\"";
3002 $res = $this->query( $sql, __METHOD__
);
3003 $row = $this->fetchObject( $res );
3007 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
3016 public function delete( $table, $conds, $fname = __METHOD__
) {
3018 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
3021 $table = $this->tableName( $table );
3022 $sql = "DELETE FROM $table";
3024 if ( $conds != '*' ) {
3025 if ( is_array( $conds ) ) {
3026 $conds = $this->makeList( $conds, self
::LIST_AND
);
3028 $sql .= ' WHERE ' . $conds;
3031 $this->query( $sql, $fname );
3036 final public function insertSelect(
3037 $destTable, $srcTable, $varMap, $conds,
3038 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3040 static $hints = [ 'NO_AUTO_COLUMNS' ];
3042 $insertOptions = (array)$insertOptions;
3043 $selectOptions = (array)$selectOptions;
3045 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
3046 // For massive migrations with downtime, we don't want to select everything
3047 // into memory and OOM, so do all this native on the server side if possible.
3048 $this->nativeInsertSelect(
3054 array_diff( $insertOptions, $hints ),
3059 $this->nonNativeInsertSelect(
3065 array_diff( $insertOptions, $hints ),
3075 * @param array $insertOptions INSERT options
3076 * @param array $selectOptions SELECT options
3077 * @return bool Whether an INSERT SELECT with these options will be replication safe
3080 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
3085 * Implementation of insertSelect() based on select() and insert()
3087 * @see IDatabase::insertSelect()
3089 * @param string $destTable
3090 * @param string|array $srcTable
3091 * @param array $varMap
3092 * @param array $conds
3093 * @param string $fname
3094 * @param array $insertOptions
3095 * @param array $selectOptions
3096 * @param array $selectJoinConds
3098 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3099 $fname = __METHOD__
,
3100 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3102 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
3103 // on only the master (without needing row-based-replication). It also makes it easy to
3104 // know how big the INSERT is going to be.
3106 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
3107 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
3109 $selectOptions[] = 'FOR UPDATE';
3110 $res = $this->select(
3111 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
3118 $affectedRowCount = 0;
3119 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
3122 foreach ( $res as $row ) {
3123 $rows[] = (array)$row;
3125 // Avoid inserts that are too huge
3126 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
3127 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
3131 $affectedRowCount +
= $this->affectedRows();
3135 if ( $rows && $ok ) {
3136 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
3138 $affectedRowCount +
= $this->affectedRows();
3142 $this->endAtomic( $fname );
3143 $this->affectedRowCount
= $affectedRowCount;
3145 $this->cancelAtomic( $fname );
3147 } catch ( Exception
$e ) {
3148 $this->cancelAtomic( $fname );
3154 * Native server-side implementation of insertSelect() for situations where
3155 * we don't want to select everything into memory
3157 * @see IDatabase::insertSelect()
3158 * @param string $destTable
3159 * @param string|array $srcTable
3160 * @param array $varMap
3161 * @param array $conds
3162 * @param string $fname
3163 * @param array $insertOptions
3164 * @param array $selectOptions
3165 * @param array $selectJoinConds
3167 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3168 $fname = __METHOD__
,
3169 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3171 $destTable = $this->tableName( $destTable );
3173 if ( !is_array( $insertOptions ) ) {
3174 $insertOptions = [ $insertOptions ];
3177 $insertOptions = $this->makeInsertOptions( $insertOptions );
3179 $selectSql = $this->selectSQLText(
3181 array_values( $varMap ),
3188 $sql = "INSERT $insertOptions" .
3189 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
3192 $this->query( $sql, $fname );
3195 public function limitResult( $sql, $limit, $offset = false ) {
3196 if ( !is_numeric( $limit ) ) {
3197 throw new DBUnexpectedError(
3199 "Invalid non-numeric limit passed to " . __METHOD__
3202 // This version works in MySQL and SQLite. It will very likely need to be
3203 // overridden for most other RDBMS subclasses.
3204 return "$sql LIMIT "
3205 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3209 public function unionSupportsOrderAndLimit() {
3210 return true; // True for almost every DB supported
3213 public function unionQueries( $sqls, $all ) {
3214 $glue = $all ?
') UNION ALL (' : ') UNION (';
3216 return '(' . implode( $glue, $sqls ) . ')';
3219 public function unionConditionPermutations(
3220 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
3221 $options = [], $join_conds = []
3223 // First, build the Cartesian product of $permute_conds
3225 foreach ( $permute_conds as $field => $values ) {
3227 // Skip empty $values
3230 $values = array_unique( $values ); // For sanity
3232 foreach ( $conds as $cond ) {
3233 foreach ( $values as $value ) {
3234 $cond[$field] = $value;
3235 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
3241 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
3243 // If there's just one condition and no subordering, hand off to
3244 // selectSQLText directly.
3245 if ( count( $conds ) === 1 &&
3246 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
3248 return $this->selectSQLText(
3249 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
3253 // Otherwise, we need to pull out the order and limit to apply after
3254 // the union. Then build the SQL queries for each set of conditions in
3255 // $conds. Then union them together (using UNION ALL, because the
3256 // product *should* already be distinct).
3257 $orderBy = $this->makeOrderBy( $options );
3258 $limit = $options['LIMIT'] ??
null;
3259 $offset = $options['OFFSET'] ??
false;
3260 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
3261 if ( !$this->unionSupportsOrderAndLimit() ) {
3262 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
3264 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
3265 $options['ORDER BY'] = $options['INNER ORDER BY'];
3267 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
3268 // We need to increase the limit by the offset rather than
3269 // using the offset directly, otherwise it'll skip incorrectly
3270 // in the subqueries.
3271 $options['LIMIT'] = $limit +
$offset;
3272 unset( $options['OFFSET'] );
3277 foreach ( $conds as $cond ) {
3278 $sqls[] = $this->selectSQLText(
3279 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
3282 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
3283 if ( $limit !== null ) {
3284 $sql = $this->limitResult( $sql, $limit, $offset );
3290 public function conditional( $cond, $trueVal, $falseVal ) {
3291 if ( is_array( $cond ) ) {
3292 $cond = $this->makeList( $cond, self
::LIST_AND
);
3295 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3298 public function strreplace( $orig, $old, $new ) {
3299 return "REPLACE({$orig}, {$old}, {$new})";
3302 public function getServerUptime() {
3306 public function wasDeadlock() {
3310 public function wasLockTimeout() {
3314 public function wasConnectionLoss() {
3315 return $this->wasConnectionError( $this->lastErrno() );
3318 public function wasReadOnlyError() {
3322 public function wasErrorReissuable() {
3324 $this->wasDeadlock() ||
3325 $this->wasLockTimeout() ||
3326 $this->wasConnectionLoss()
3331 * Do not use this method outside of Database/DBError classes
3333 * @param int|string $errno
3334 * @return bool Whether the given query error was a connection drop
3336 public function wasConnectionError( $errno ) {
3341 * @return bool Whether it is known that the last query error only caused statement rollback
3342 * @note This is for backwards compatibility for callers catching DBError exceptions in
3343 * order to ignore problems like duplicate key errors or foriegn key violations
3346 protected function wasKnownStatementRollbackError() {
3347 return false; // don't know; it could have caused a transaction rollback
3350 public function deadlockLoop() {
3351 $args = func_get_args();
3352 $function = array_shift( $args );
3353 $tries = self
::$DEADLOCK_TRIES;
3355 $this->begin( __METHOD__
);
3358 /** @var Exception $e */
3362 $retVal = $function( ...$args );
3364 } catch ( DBQueryError
$e ) {
3365 if ( $this->wasDeadlock() ) {
3366 // Retry after a randomized delay
3367 usleep( mt_rand( self
::$DEADLOCK_DELAY_MIN, self
::$DEADLOCK_DELAY_MAX ) );
3369 // Throw the error back up
3373 } while ( --$tries > 0 );
3375 if ( $tries <= 0 ) {
3376 // Too many deadlocks; give up
3377 $this->rollback( __METHOD__
);
3380 $this->commit( __METHOD__
);
3386 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3387 # Real waits are implemented in the subclass.
3391 public function getReplicaPos() {
3396 public function getMasterPos() {
3401 public function serverIsReadOnly() {
3405 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
3406 if ( !$this->trxLevel() ) {
3407 throw new DBUnexpectedError( $this, "No transaction is active" );
3409 $this->trxEndCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3412 final public function onTransactionCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3413 if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
3414 // Start an implicit transaction similar to how query() does
3415 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3416 $this->trxAutomatic
= true;
3419 $this->trxIdleCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3420 if ( !$this->trxLevel() ) {
3421 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
3425 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
3426 $this->onTransactionCommitOrIdle( $callback, $fname );
3429 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3430 if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
3431 // Start an implicit transaction similar to how query() does
3432 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3433 $this->trxAutomatic
= true;
3436 if ( $this->trxLevel() ) {
3437 $this->trxPreCommitCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3439 // No transaction is active nor will start implicitly, so make one for this callback
3440 $this->startAtomic( __METHOD__
, self
::ATOMIC_CANCELABLE
);
3443 $this->endAtomic( __METHOD__
);
3444 } catch ( Exception
$e ) {
3445 $this->cancelAtomic( __METHOD__
);
3451 final public function onAtomicSectionCancel( callable
$callback, $fname = __METHOD__
) {
3452 if ( !$this->trxLevel() ||
!$this->trxAtomicLevels
) {
3453 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3455 $this->trxSectionCancelCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3459 * @return AtomicSectionIdentifier|null ID of the topmost atomic section level
3461 private function currentAtomicSectionId() {
3462 if ( $this->trxLevel() && $this->trxAtomicLevels
) {
3463 $levelInfo = end( $this->trxAtomicLevels
);
3465 return $levelInfo[1];
3472 * Hoist callback ownership for callbacks in a section to a parent section.
3473 * All callbacks should have an owner that is present in trxAtomicLevels.
3474 * @param AtomicSectionIdentifier $old
3475 * @param AtomicSectionIdentifier $new
3477 private function reassignCallbacksForSection(
3478 AtomicSectionIdentifier
$old, AtomicSectionIdentifier
$new
3480 foreach ( $this->trxPreCommitCallbacks
as $key => $info ) {
3481 if ( $info[2] === $old ) {
3482 $this->trxPreCommitCallbacks
[$key][2] = $new;
3485 foreach ( $this->trxIdleCallbacks
as $key => $info ) {
3486 if ( $info[2] === $old ) {
3487 $this->trxIdleCallbacks
[$key][2] = $new;
3490 foreach ( $this->trxEndCallbacks
as $key => $info ) {
3491 if ( $info[2] === $old ) {
3492 $this->trxEndCallbacks
[$key][2] = $new;
3495 foreach ( $this->trxSectionCancelCallbacks
as $key => $info ) {
3496 if ( $info[2] === $old ) {
3497 $this->trxSectionCancelCallbacks
[$key][2] = $new;
3503 * Update callbacks that were owned by cancelled atomic sections.
3505 * Callbacks for "on commit" should never be run if they're owned by a
3506 * section that won't be committed.
3508 * Callbacks for "on resolution" need to reflect that the section was
3509 * rolled back, even if the transaction as a whole commits successfully.
3511 * Callbacks for "on section cancel" should already have been consumed,
3512 * but errors during the cancellation itself can prevent that while still
3513 * destroying the section. Hoist any such callbacks to the new top section,
3514 * which we assume will itself have to be cancelled or rolled back to
3515 * resolve the error.
3517 * @param AtomicSectionIdentifier[] $sectionIds ID of an actual savepoint
3518 * @param AtomicSectionIdentifier|null $newSectionId New top section ID.
3519 * @throws UnexpectedValueException
3521 private function modifyCallbacksForCancel(
3522 array $sectionIds, AtomicSectionIdentifier
$newSectionId = null
3524 // Cancel the "on commit" callbacks owned by this savepoint
3525 $this->trxIdleCallbacks
= array_filter(
3526 $this->trxIdleCallbacks
,
3527 function ( $entry ) use ( $sectionIds ) {
3528 return !in_array( $entry[2], $sectionIds, true );
3531 $this->trxPreCommitCallbacks
= array_filter(
3532 $this->trxPreCommitCallbacks
,
3533 function ( $entry ) use ( $sectionIds ) {
3534 return !in_array( $entry[2], $sectionIds, true );
3537 // Make "on resolution" callbacks owned by this savepoint to perceive a rollback
3538 foreach ( $this->trxEndCallbacks
as $key => $entry ) {
3539 if ( in_array( $entry[2], $sectionIds, true ) ) {
3540 $callback = $entry[0];
3541 $this->trxEndCallbacks
[$key][0] = function () use ( $callback ) {
3542 // @phan-suppress-next-line PhanInfiniteRecursion No recursion at all here, phan is confused
3543 return $callback( self
::TRIGGER_ROLLBACK
, $this );
3545 // This "on resolution" callback no longer belongs to a section.
3546 $this->trxEndCallbacks
[$key][2] = null;
3549 // Hoist callback ownership for section cancel callbacks to the new top section
3550 foreach ( $this->trxSectionCancelCallbacks
as $key => $entry ) {
3551 if ( in_array( $entry[2], $sectionIds, true ) ) {
3552 $this->trxSectionCancelCallbacks
[$key][2] = $newSectionId;
3557 final public function setTransactionListener( $name, callable
$callback = null ) {
3559 $this->trxRecurringCallbacks
[$name] = $callback;
3561 unset( $this->trxRecurringCallbacks
[$name] );
3566 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
3568 * This method should not be used outside of Database/LoadBalancer
3570 * @param bool $suppress
3573 final public function setTrxEndCallbackSuppression( $suppress ) {
3574 $this->trxEndCallbacksSuppressed
= $suppress;
3578 * Actually consume and run any "on transaction idle/resolution" callbacks.
3580 * This method should not be used outside of Database/LoadBalancer
3582 * @param int $trigger IDatabase::TRIGGER_* constant
3583 * @return int Number of callbacks attempted
3587 public function runOnTransactionIdleCallbacks( $trigger ) {
3588 if ( $this->trxLevel() ) { // sanity
3589 throw new DBUnexpectedError( $this, __METHOD__
. ': a transaction is still open' );
3592 if ( $this->trxEndCallbacksSuppressed
) {
3597 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
3598 /** @var Exception $e */
3599 $e = null; // first exception
3600 do { // callbacks may add callbacks :)
3601 $callbacks = array_merge(
3602 $this->trxIdleCallbacks
,
3603 $this->trxEndCallbacks
// include "transaction resolution" callbacks
3605 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
3606 $this->trxEndCallbacks
= []; // consumed (recursion guard)
3608 // Only run trxSectionCancelCallbacks on rollback, not commit.
3609 // But always consume them.
3610 if ( $trigger === self
::TRIGGER_ROLLBACK
) {
3611 $callbacks = array_merge( $callbacks, $this->trxSectionCancelCallbacks
);
3613 $this->trxSectionCancelCallbacks
= []; // consumed (recursion guard)
3615 foreach ( $callbacks as $callback ) {
3617 list( $phpCallback ) = $callback;
3618 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
3620 // @phan-suppress-next-line PhanParamTooManyCallable
3621 call_user_func( $phpCallback, $trigger, $this );
3622 } catch ( Exception
$ex ) {
3623 call_user_func( $this->errorLogger
, $ex );
3625 // Some callbacks may use startAtomic/endAtomic, so make sure
3626 // their transactions are ended so other callbacks don't fail
3627 if ( $this->trxLevel() ) {
3628 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3632 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
3634 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
3638 } while ( count( $this->trxIdleCallbacks
) );
3640 if ( $e instanceof Exception
) {
3641 throw $e; // re-throw any first exception
3648 * Actually consume and run any "on transaction pre-commit" callbacks.
3650 * This method should not be used outside of Database/LoadBalancer
3653 * @return int Number of callbacks attempted
3656 public function runOnTransactionPreCommitCallbacks() {
3659 $e = null; // first exception
3660 do { // callbacks may add callbacks :)
3661 $callbacks = $this->trxPreCommitCallbacks
;
3662 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
3663 foreach ( $callbacks as $callback ) {
3666 list( $phpCallback ) = $callback;
3667 $phpCallback( $this );
3668 } catch ( Exception
$ex ) {
3669 ( $this->errorLogger
)( $ex );
3673 } while ( count( $this->trxPreCommitCallbacks
) );
3675 if ( $e instanceof Exception
) {
3676 throw $e; // re-throw any first exception
3683 * Actually run any "atomic section cancel" callbacks.
3685 * @param int $trigger IDatabase::TRIGGER_* constant
3686 * @param AtomicSectionIdentifier[]|null $sectionIds Section IDs to cancel,
3687 * null on transaction rollback
3689 private function runOnAtomicSectionCancelCallbacks(
3690 $trigger, array $sectionIds = null
3692 /** @var Exception|Throwable $e */
3693 $e = null; // first exception
3697 $callbacks = $this->trxSectionCancelCallbacks
;
3698 $this->trxSectionCancelCallbacks
= []; // consumed (recursion guard)
3699 foreach ( $callbacks as $entry ) {
3700 if ( $sectionIds === null ||
in_array( $entry[2], $sectionIds, true ) ) {
3702 $entry[0]( $trigger, $this );
3703 } catch ( Exception
$ex ) {
3704 ( $this->errorLogger
)( $ex );
3706 } catch ( Throwable
$ex ) {
3711 $notCancelled[] = $entry;
3714 } while ( count( $this->trxSectionCancelCallbacks
) );
3715 $this->trxSectionCancelCallbacks
= $notCancelled;
3717 if ( $e !== null ) {
3718 throw $e; // re-throw any first Exception/Throwable
3723 * Actually run any "transaction listener" callbacks.
3725 * This method should not be used outside of Database/LoadBalancer
3727 * @param int $trigger IDatabase::TRIGGER_* constant
3731 public function runTransactionListenerCallbacks( $trigger ) {
3732 if ( $this->trxEndCallbacksSuppressed
) {
3736 /** @var Exception $e */
3737 $e = null; // first exception
3739 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3741 $phpCallback( $trigger, $this );
3742 } catch ( Exception
$ex ) {
3743 ( $this->errorLogger
)( $ex );
3748 if ( $e instanceof Exception
) {
3749 throw $e; // re-throw any first exception
3754 * Create a savepoint
3756 * This is used internally to implement atomic sections. It should not be
3760 * @param string $identifier Identifier for the savepoint
3761 * @param string $fname Calling function name
3763 protected function doSavepoint( $identifier, $fname ) {
3764 $this->query( 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3768 * Release a savepoint
3770 * This is used internally to implement atomic sections. It should not be
3774 * @param string $identifier Identifier for the savepoint
3775 * @param string $fname Calling function name
3777 protected function doReleaseSavepoint( $identifier, $fname ) {
3778 $this->query( 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3782 * Rollback to a savepoint
3784 * This is used internally to implement atomic sections. It should not be
3788 * @param string $identifier Identifier for the savepoint
3789 * @param string $fname Calling function name
3791 protected function doRollbackToSavepoint( $identifier, $fname ) {
3792 $this->query( 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3796 * @param string $fname
3799 private function nextSavepointId( $fname ) {
3800 $savepointId = self
::$SAVEPOINT_PREFIX . ++
$this->trxAtomicCounter
;
3801 if ( strlen( $savepointId ) > 30 ) {
3802 // 30 == Oracle's identifier length limit (pre 12c)
3803 // With a 22 character prefix, that puts the highest number at 99999999.
3804 throw new DBUnexpectedError(
3806 'There have been an excessively large number of atomic sections in a transaction'
3807 . " started by $this->trxFname (at $fname)"
3811 return $savepointId;
3814 final public function startAtomic(
3815 $fname = __METHOD__
, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3817 $savepointId = $cancelable === self
::ATOMIC_CANCELABLE ? self
::$NOT_APPLICABLE : null;
3819 if ( !$this->trxLevel() ) {
3820 $this->begin( $fname, self
::TRANSACTION_INTERNAL
); // sets trxAutomatic
3821 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3822 // in all changes being in one transaction to keep requests transactional.
3823 if ( $this->getFlag( self
::DBO_TRX
) ) {
3824 // Since writes could happen in between the topmost atomic sections as part
3825 // of the transaction, those sections will need savepoints.
3826 $savepointId = $this->nextSavepointId( $fname );
3827 $this->doSavepoint( $savepointId, $fname );
3829 $this->trxAutomaticAtomic
= true;
3831 } elseif ( $cancelable === self
::ATOMIC_CANCELABLE
) {
3832 $savepointId = $this->nextSavepointId( $fname );
3833 $this->doSavepoint( $savepointId, $fname );
3836 $sectionId = new AtomicSectionIdentifier
;
3837 $this->trxAtomicLevels
[] = [ $fname, $sectionId, $savepointId ];
3838 $this->queryLogger
->debug( 'startAtomic: entering level ' .
3839 ( count( $this->trxAtomicLevels
) - 1 ) . " ($fname)" );
3844 final public function endAtomic( $fname = __METHOD__
) {
3845 if ( !$this->trxLevel() ||
!$this->trxAtomicLevels
) {
3846 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3849 // Check if the current section matches $fname
3850 $pos = count( $this->trxAtomicLevels
) - 1;
3851 list( $savedFname, $sectionId, $savepointId ) = $this->trxAtomicLevels
[$pos];
3852 $this->queryLogger
->debug( "endAtomic: leaving level $pos ($fname)" );
3854 if ( $savedFname !== $fname ) {
3855 throw new DBUnexpectedError(
3857 "Invalid atomic section ended (got $fname but expected $savedFname)"
3861 // Remove the last section (no need to re-index the array)
3862 array_pop( $this->trxAtomicLevels
);
3864 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3865 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3866 } elseif ( $savepointId !== null && $savepointId !== self
::$NOT_APPLICABLE ) {
3867 $this->doReleaseSavepoint( $savepointId, $fname );
3870 // Hoist callback ownership for callbacks in the section that just ended;
3871 // all callbacks should have an owner that is present in trxAtomicLevels.
3872 $currentSectionId = $this->currentAtomicSectionId();
3873 if ( $currentSectionId ) {
3874 $this->reassignCallbacksForSection( $sectionId, $currentSectionId );
3878 final public function cancelAtomic(
3879 $fname = __METHOD__
, AtomicSectionIdentifier
$sectionId = null
3881 if ( !$this->trxLevel() ||
!$this->trxAtomicLevels
) {
3882 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3886 $newTopSection = $this->currentAtomicSectionId();
3888 $excisedFnames = [];
3889 if ( $sectionId !== null ) {
3890 // Find the (last) section with the given $sectionId
3892 foreach ( $this->trxAtomicLevels
as $i => list( $asFname, $asId, $spId ) ) {
3893 if ( $asId === $sectionId ) {
3898 throw new DBUnexpectedError( $this, "Atomic section not found (for $fname)" );
3900 // Remove all descendant sections and re-index the array
3901 $len = count( $this->trxAtomicLevels
);
3902 for ( $i = $pos +
1; $i < $len; ++
$i ) {
3903 $excisedFnames[] = $this->trxAtomicLevels
[$i][0];
3904 $excisedIds[] = $this->trxAtomicLevels
[$i][1];
3906 $this->trxAtomicLevels
= array_slice( $this->trxAtomicLevels
, 0, $pos +
1 );
3907 $newTopSection = $this->currentAtomicSectionId();
3910 // Check if the current section matches $fname
3911 $pos = count( $this->trxAtomicLevels
) - 1;
3912 list( $savedFname, $savedSectionId, $savepointId ) = $this->trxAtomicLevels
[$pos];
3914 if ( $excisedFnames ) {
3915 $this->queryLogger
->debug( "cancelAtomic: canceling level $pos ($savedFname) " .
3916 "and descendants " . implode( ', ', $excisedFnames ) );
3918 $this->queryLogger
->debug( "cancelAtomic: canceling level $pos ($savedFname)" );
3921 if ( $savedFname !== $fname ) {
3922 throw new DBUnexpectedError(
3924 "Invalid atomic section ended (got $fname but expected $savedFname)"
3928 // Remove the last section (no need to re-index the array)
3929 array_pop( $this->trxAtomicLevels
);
3930 $excisedIds[] = $savedSectionId;
3931 $newTopSection = $this->currentAtomicSectionId();
3933 if ( $savepointId !== null ) {
3934 // Rollback the transaction to the state just before this atomic section
3935 if ( $savepointId === self
::$NOT_APPLICABLE ) {
3936 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3937 // Note: rollback() will run trxSectionCancelCallbacks
3939 $this->doRollbackToSavepoint( $savepointId, $fname );
3940 $this->trxStatus
= self
::STATUS_TRX_OK
; // no exception; recovered
3941 $this->trxStatusIgnoredCause
= null;
3943 // Run trxSectionCancelCallbacks now.
3944 $this->runOnAtomicSectionCancelCallbacks( self
::TRIGGER_CANCEL
, $excisedIds );
3946 } elseif ( $this->trxStatus
> self
::STATUS_TRX_ERROR
) {
3947 // Put the transaction into an error state if it's not already in one
3948 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
3949 $this->trxStatusCause
= new DBUnexpectedError(
3951 "Uncancelable atomic section canceled (got $fname)"
3955 // Fix up callbacks owned by the sections that were just cancelled.
3956 // All callbacks should have an owner that is present in trxAtomicLevels.
3957 $this->modifyCallbacksForCancel( $excisedIds, $newTopSection );
3960 $this->affectedRowCount
= 0; // for the sake of consistency
3963 final public function doAtomicSection(
3964 $fname, callable
$callback, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3966 $sectionId = $this->startAtomic( $fname, $cancelable );
3968 $res = $callback( $this, $fname );
3969 } catch ( Exception
$e ) {
3970 $this->cancelAtomic( $fname, $sectionId );
3974 $this->endAtomic( $fname );
3979 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3980 static $modes = [ self
::TRANSACTION_EXPLICIT
, self
::TRANSACTION_INTERNAL
];
3981 if ( !in_array( $mode, $modes, true ) ) {
3982 throw new DBUnexpectedError( $this, "$fname: invalid mode parameter '$mode'" );
3985 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3986 if ( $this->trxLevel() ) {
3987 if ( $this->trxAtomicLevels
) {
3988 $levels = $this->flatAtomicSectionList();
3989 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open";
3990 throw new DBUnexpectedError( $this, $msg );
3991 } elseif ( !$this->trxAutomatic
) {
3992 $msg = "$fname: Explicit transaction already active (from {$this->trxFname})";
3993 throw new DBUnexpectedError( $this, $msg );
3995 $msg = "$fname: Implicit transaction already active (from {$this->trxFname})";
3996 throw new DBUnexpectedError( $this, $msg );
3998 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3999 $msg = "$fname: Implicit transaction expected (DBO_TRX set)";
4000 throw new DBUnexpectedError( $this, $msg );
4003 $this->assertHasConnectionHandle();
4005 $this->doBegin( $fname );
4006 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
4007 $this->trxStatus
= self
::STATUS_TRX_OK
;
4008 $this->trxStatusIgnoredCause
= null;
4009 $this->trxAtomicCounter
= 0;
4010 $this->trxTimestamp
= microtime( true );
4011 $this->trxFname
= $fname;
4012 $this->trxDoneWrites
= false;
4013 $this->trxAutomaticAtomic
= false;
4014 $this->trxAtomicLevels
= [];
4015 $this->trxWriteDuration
= 0.0;
4016 $this->trxWriteQueryCount
= 0;
4017 $this->trxWriteAffectedRows
= 0;
4018 $this->trxWriteAdjDuration
= 0.0;
4019 $this->trxWriteAdjQueryCount
= 0;
4020 $this->trxWriteCallers
= [];
4021 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
4022 // Get an estimate of the replication lag before any such queries.
4023 $this->trxReplicaLag
= null; // clear cached value first
4024 $this->trxReplicaLag
= $this->getApproximateLagStatus()['lag'];
4025 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
4026 // caller will think its OK to muck around with the transaction just because startAtomic()
4027 // has not yet completed (e.g. setting trxAtomicLevels).
4028 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
4032 * Issues the BEGIN command to the database server.
4034 * @see Database::begin()
4035 * @param string $fname
4038 protected function doBegin( $fname ) {
4039 $this->query( 'BEGIN', $fname );
4042 final public function commit( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
4043 static $modes = [ self
::FLUSHING_ONE
, self
::FLUSHING_ALL_PEERS
, self
::FLUSHING_INTERNAL
];
4044 if ( !in_array( $flush, $modes, true ) ) {
4045 throw new DBUnexpectedError( $this, "$fname: invalid flush parameter '$flush'" );
4048 if ( $this->trxLevel() && $this->trxAtomicLevels
) {
4049 // There are still atomic sections open; this cannot be ignored
4050 $levels = $this->flatAtomicSectionList();
4051 throw new DBUnexpectedError(
4053 "$fname: Got COMMIT while atomic sections $levels are still open"
4057 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
4058 if ( !$this->trxLevel() ) {
4059 return; // nothing to do
4060 } elseif ( !$this->trxAutomatic
) {
4061 throw new DBUnexpectedError(
4063 "$fname: Flushing an explicit transaction, getting out of sync"
4066 } elseif ( !$this->trxLevel() ) {
4067 $this->queryLogger
->error(
4068 "$fname: No transaction to commit, something got out of sync" );
4069 return; // nothing to do
4070 } elseif ( $this->trxAutomatic
) {
4071 throw new DBUnexpectedError(
4073 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)"
4077 $this->assertHasConnectionHandle();
4079 $this->runOnTransactionPreCommitCallbacks();
4081 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
4082 $this->doCommit( $fname );
4083 $oldTrxShortId = $this->consumeTrxShortId();
4084 $this->trxStatus
= self
::STATUS_TRX_NONE
;
4086 if ( $this->trxDoneWrites
) {
4087 $this->lastWriteTime
= microtime( true );
4088 $this->trxProfiler
->transactionWritingOut(
4090 $this->getDomainID(),
4093 $this->trxWriteAffectedRows
4097 // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4098 if ( $flush !== self
::FLUSHING_ALL_PEERS
) {
4099 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
4100 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
4105 * Issues the COMMIT command to the database server.
4107 * @see Database::commit()
4108 * @param string $fname
4111 protected function doCommit( $fname ) {
4112 if ( $this->trxLevel() ) {
4113 $this->query( 'COMMIT', $fname );
4117 final public function rollback( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
4118 $trxActive = $this->trxLevel();
4120 if ( $flush !== self
::FLUSHING_INTERNAL
4121 && $flush !== self
::FLUSHING_ALL_PEERS
4122 && $this->getFlag( self
::DBO_TRX
)
4124 throw new DBUnexpectedError(
4126 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)"
4131 $this->assertHasConnectionHandle();
4133 $this->doRollback( $fname );
4134 $oldTrxShortId = $this->consumeTrxShortId();
4135 $this->trxStatus
= self
::STATUS_TRX_NONE
;
4136 $this->trxAtomicLevels
= [];
4137 // Estimate the RTT via a query now that trxStatus is OK
4138 $writeTime = $this->pingAndCalculateLastTrxApplyTime();
4140 if ( $this->trxDoneWrites
) {
4141 $this->trxProfiler
->transactionWritingOut(
4143 $this->getDomainID(),
4146 $this->trxWriteAffectedRows
4151 // Clear any commit-dependant callbacks. They might even be present
4152 // only due to transaction rounds, with no SQL transaction being active
4153 $this->trxIdleCallbacks
= [];
4154 $this->trxPreCommitCallbacks
= [];
4156 // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4157 if ( $trxActive && $flush !== self
::FLUSHING_ALL_PEERS
) {
4159 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
4160 } catch ( Exception
$e ) {
4161 // already logged; finish and let LoadBalancer move on during mass-rollback
4164 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
4165 } catch ( Exception
$e ) {
4166 // already logged; let LoadBalancer move on during mass-rollback
4169 $this->affectedRowCount
= 0; // for the sake of consistency
4174 * Issues the ROLLBACK command to the database server.
4176 * @see Database::rollback()
4177 * @param string $fname
4180 protected function doRollback( $fname ) {
4181 if ( $this->trxLevel() ) {
4182 # Disconnects cause rollback anyway, so ignore those errors
4183 $ignoreErrors = true;
4184 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
4188 public function flushSnapshot( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
4189 if ( $this->explicitTrxActive() ) {
4190 // Committing this transaction would break callers that assume it is still open
4191 throw new DBUnexpectedError(
4193 "$fname: Cannot flush snapshot; " .
4194 "explicit transaction '{$this->trxFname}' is still open"
4196 } elseif ( $this->writesOrCallbacksPending() ) {
4197 // This only flushes transactions to clear snapshots, not to write data
4198 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4199 throw new DBUnexpectedError(
4201 "$fname: Cannot flush snapshot; " .
4202 "writes from transaction {$this->trxFname} are still pending ($fnames)"
4205 $this->trxLevel() &&
4206 $this->getTransactionRoundId() &&
4207 $flush !== self
::FLUSHING_INTERNAL
&&
4208 $flush !== self
::FLUSHING_ALL_PEERS
4210 $this->queryLogger
->warning(
4211 "$fname: Expected mass snapshot flush of all peer transactions " .
4212 "in the explicit transactions round '{$this->getTransactionRoundId()}'",
4213 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
4217 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4220 public function explicitTrxActive() {
4221 return $this->trxLevel() && ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
4224 public function duplicateTableStructure(
4225 $oldName, $newName, $temporary = false, $fname = __METHOD__
4227 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4230 public function listTables( $prefix = null, $fname = __METHOD__
) {
4231 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4234 public function listViews( $prefix = null, $fname = __METHOD__
) {
4235 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4238 public function timestamp( $ts = 0 ) {
4239 $t = new ConvertibleTimestamp( $ts );
4240 // Let errors bubble up to avoid putting garbage in the DB
4241 return $t->getTimestamp( TS_MW
);
4244 public function timestampOrNull( $ts = null ) {
4245 if ( is_null( $ts ) ) {
4248 return $this->timestamp( $ts );
4252 public function affectedRows() {
4253 return ( $this->affectedRowCount
=== null )
4254 ?
$this->fetchAffectedRowCount() // default to driver value
4255 : $this->affectedRowCount
;
4259 * @return int Number of retrieved rows according to the driver
4261 abstract protected function fetchAffectedRowCount();
4264 * Take a query result and wrap it in an iterable result wrapper if necessary.
4265 * Booleans are passed through as-is to indicate success/failure of write queries.
4267 * Once upon a time, Database::query() returned a bare MySQL result
4268 * resource, and it was necessary to call this function to convert it to
4269 * a wrapper. Nowadays, raw database objects are never exposed to external
4270 * callers, so this is unnecessary in external code.
4272 * @param bool|IResultWrapper|resource $result
4273 * @return bool|IResultWrapper
4275 protected function resultObject( $result ) {
4277 return false; // failed query
4278 } elseif ( $result instanceof IResultWrapper
) {
4280 } elseif ( $result === true ) {
4281 return $result; // succesful write query
4283 return new ResultWrapper( $this, $result );
4287 public function ping( &$rtt = null ) {
4288 // Avoid hitting the server if it was hit recently
4289 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::$PING_TTL ) {
4290 if ( !func_num_args() ||
$this->lastRoundTripEstimate
> 0 ) {
4291 $rtt = $this->lastRoundTripEstimate
;
4292 return true; // don't care about $rtt
4296 // This will reconnect if possible or return false if not
4297 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
4298 $ok = ( $this->query( self
::$PING_QUERY, __METHOD__
, true ) !== false );
4299 $this->restoreFlags( self
::RESTORE_PRIOR
);
4302 $rtt = $this->lastRoundTripEstimate
;
4309 * Close any existing (dead) database connection and open a new connection
4311 * @param string $fname
4312 * @return bool True if new connection is opened successfully, false if error
4314 protected function replaceLostConnection( $fname ) {
4315 $this->closeConnection();
4318 $this->handleSessionLossPreconnect();
4325 $this->currentDomain
->getDatabase(),
4326 $this->currentDomain
->getSchema(),
4327 $this->tablePrefix()
4329 $this->lastPing
= microtime( true );
4332 $this->connLogger
->warning(
4333 $fname . ': lost connection to {dbserver}; reconnected',
4335 'dbserver' => $this->getServer(),
4336 'trace' => ( new RuntimeException() )->getTraceAsString()
4339 } catch ( DBConnectionError
$e ) {
4342 $this->connLogger
->error(
4343 $fname . ': lost connection to {dbserver} permanently',
4344 [ 'dbserver' => $this->getServer() ]
4348 $this->handleSessionLossPostconnect();
4353 public function getSessionLagStatus() {
4354 return $this->getRecordedTransactionLagStatus() ?
: $this->getApproximateLagStatus();
4358 * Get the replica DB lag when the current transaction started
4360 * This is useful when transactions might use snapshot isolation
4361 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
4362 * is this lag plus transaction duration. If they don't, it is still
4363 * safe to be pessimistic. This returns null if there is no transaction.
4365 * This returns null if the lag status for this transaction was not yet recorded.
4367 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
4370 final protected function getRecordedTransactionLagStatus() {
4371 return ( $this->trxLevel() && $this->trxReplicaLag
!== null )
4372 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
4377 * Get a replica DB lag estimate for this server
4379 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
4382 protected function getApproximateLagStatus() {
4384 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
4385 'since' => microtime( true )
4390 * Merge the result of getSessionLagStatus() for several DBs
4391 * using the most pessimistic values to estimate the lag of
4392 * any data derived from them in combination
4394 * This is information is useful for caching modules
4396 * @see WANObjectCache::set()
4397 * @see WANObjectCache::getWithSetCallback()
4399 * @param IDatabase $db1
4400 * @param IDatabase|null $db2 [optional]
4401 * @return array Map of values:
4402 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
4403 * - since: oldest UNIX timestamp of any of the DB lag estimates
4404 * - pending: whether any of the DBs have uncommitted changes
4408 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
4409 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
4410 foreach ( func_get_args() as $db ) {
4411 /** @var IDatabase $db */
4412 $status = $db->getSessionLagStatus();
4413 if ( $status['lag'] === false ) {
4414 $res['lag'] = false;
4415 } elseif ( $res['lag'] !== false ) {
4416 $res['lag'] = max( $res['lag'], $status['lag'] );
4418 $res['since'] = min( $res['since'], $status['since'] );
4419 $res['pending'] = $res['pending'] ?
: $db->writesPending();
4425 public function getLag() {
4426 if ( $this->getLBInfo( 'master' ) ) {
4427 return 0; // this is the master
4428 } elseif ( $this->getLBInfo( 'is static' ) ) {
4429 return 0; // static dataset
4432 return $this->doGetLag();
4435 protected function doGetLag() {
4439 public function maxListLen() {
4443 public function encodeBlob( $b ) {
4447 public function decodeBlob( $b ) {
4448 if ( $b instanceof Blob
) {
4454 public function setSessionOptions( array $options ) {
4457 public function sourceFile(
4459 callable
$lineCallback = null,
4460 callable
$resultCallback = null,
4462 callable
$inputCallback = null
4464 AtEase
::suppressWarnings();
4465 $fp = fopen( $filename, 'r' );
4466 AtEase
::restoreWarnings();
4468 if ( $fp === false ) {
4469 throw new RuntimeException( "Could not open \"{$filename}\"" );
4473 $fname = __METHOD__
. "( $filename )";
4477 $error = $this->sourceStream(
4478 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
4479 } catch ( Exception
$e ) {
4489 public function setSchemaVars( $vars ) {
4490 $this->schemaVars
= $vars;
4493 public function sourceStream(
4495 callable
$lineCallback = null,
4496 callable
$resultCallback = null,
4497 $fname = __METHOD__
,
4498 callable
$inputCallback = null
4500 $delimiterReset = new ScopedCallback(
4501 function ( $delimiter ) {
4502 $this->delimiter
= $delimiter;
4504 [ $this->delimiter
]
4508 while ( !feof( $fp ) ) {
4509 if ( $lineCallback ) {
4510 call_user_func( $lineCallback );
4513 $line = trim( fgets( $fp ) );
4515 if ( $line == '' ) {
4519 if ( $line[0] == '-' && $line[1] == '-' ) {
4527 $done = $this->streamStatementEnd( $cmd, $line );
4531 if ( $done ||
feof( $fp ) ) {
4532 $cmd = $this->replaceVars( $cmd );
4534 if ( $inputCallback ) {
4535 $callbackResult = $inputCallback( $cmd );
4537 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
4538 $cmd = $callbackResult;
4543 $res = $this->query( $cmd, $fname );
4545 if ( $resultCallback ) {
4546 $resultCallback( $res, $this );
4549 if ( $res === false ) {
4550 $err = $this->lastError();
4552 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4559 ScopedCallback
::consume( $delimiterReset );
4564 * Called by sourceStream() to check if we've reached a statement end
4566 * @param string &$sql SQL assembled so far
4567 * @param string &$newLine New line about to be added to $sql
4568 * @return bool Whether $newLine contains end of the statement
4570 public function streamStatementEnd( &$sql, &$newLine ) {
4571 if ( $this->delimiter
) {
4573 $newLine = preg_replace(
4574 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4575 if ( $newLine != $prev ) {
4584 * Database independent variable replacement. Replaces a set of variables
4585 * in an SQL statement with their contents as given by $this->getSchemaVars().
4587 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4589 * - '{$var}' should be used for text and is passed through the database's
4591 * - `{$var}` should be used for identifiers (e.g. table and database names).
4592 * It is passed through the database's addIdentifierQuotes method which
4593 * can be overridden if the database uses something other than backticks.
4594 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4595 * database's tableName method.
4596 * - / *i* / passes the name that follows through the database's indexName method.
4597 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4598 * its use should be avoided. In 1.24 and older, string encoding was applied.
4600 * @param string $ins SQL statement to replace variables in
4601 * @return string The new SQL statement with variables replaced
4603 protected function replaceVars( $ins ) {
4604 $vars = $this->getSchemaVars();
4605 return preg_replace_callback(
4607 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4608 \'\{\$ (\w+) }\' | # 3. addQuotes
4609 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4610 /\*\$ (\w+) \*/ # 5. leave unencoded
4612 function ( $m ) use ( $vars ) {
4613 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4614 // check for both nonexistent keys *and* the empty string.
4615 if ( isset( $m[1] ) && $m[1] !== '' ) {
4616 if ( $m[1] === 'i' ) {
4617 return $this->indexName( $m[2] );
4619 return $this->tableName( $m[2] );
4621 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4622 return $this->addQuotes( $vars[$m[3]] );
4623 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4624 return $this->addIdentifierQuotes( $vars[$m[4]] );
4625 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4626 return $vars[$m[5]];
4636 * Get schema variables. If none have been set via setSchemaVars(), then
4637 * use some defaults from the current object.
4641 protected function getSchemaVars() {
4642 if ( $this->schemaVars
) {
4643 return $this->schemaVars
;
4645 return $this->getDefaultSchemaVars();
4650 * Get schema variables to use if none have been set via setSchemaVars().
4652 * Override this in derived classes to provide variables for tables.sql
4653 * and SQL patch files.
4657 protected function getDefaultSchemaVars() {
4661 public function lockIsFree( $lockName, $method ) {
4662 // RDBMs methods for checking named locks may or may not count this thread itself.
4663 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
4664 // the behavior choosen by the interface for this method.
4665 return !isset( $this->sessionNamedLocks
[$lockName] );
4668 public function lock( $lockName, $method, $timeout = 5 ) {
4669 $this->sessionNamedLocks
[$lockName] = 1;
4674 public function unlock( $lockName, $method ) {
4675 unset( $this->sessionNamedLocks
[$lockName] );
4680 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
4681 if ( $this->writesOrCallbacksPending() ) {
4682 // This only flushes transactions to clear snapshots, not to write data
4683 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4684 throw new DBUnexpectedError(
4686 "$fname: Cannot flush pre-lock snapshot; " .
4687 "writes from transaction {$this->trxFname} are still pending ($fnames)"
4691 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
4695 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
4696 if ( $this->trxLevel() ) {
4697 // There is a good chance an exception was thrown, causing any early return
4698 // from the caller. Let any error handler get a chance to issue rollback().
4699 // If there isn't one, let the error bubble up and trigger server-side rollback.
4700 $this->onTransactionResolution(
4701 function () use ( $lockKey, $fname ) {
4702 $this->unlock( $lockKey, $fname );
4707 $this->unlock( $lockKey, $fname );
4711 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4716 public function namedLocksEnqueue() {
4720 public function tableLocksHaveTransactionScope() {
4724 final public function lockTables( array $read, array $write, $method ) {
4725 if ( $this->writesOrCallbacksPending() ) {
4726 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending" );
4729 if ( $this->tableLocksHaveTransactionScope() ) {
4730 $this->startAtomic( $method );
4733 return $this->doLockTables( $read, $write, $method );
4737 * Helper function for lockTables() that handles the actual table locking
4739 * @param array $read Array of tables to lock for read access
4740 * @param array $write Array of tables to lock for write access
4741 * @param string $method Name of caller
4744 protected function doLockTables( array $read, array $write, $method ) {
4748 final public function unlockTables( $method ) {
4749 if ( $this->tableLocksHaveTransactionScope() ) {
4750 $this->endAtomic( $method );
4752 return true; // locks released on COMMIT/ROLLBACK
4755 return $this->doUnlockTables( $method );
4759 * Helper function for unlockTables() that handles the actual table unlocking
4761 * @param string $method Name of caller
4764 protected function doUnlockTables( $method ) {
4770 * @param string $tableName
4771 * @param string $fName
4772 * @return bool|IResultWrapper
4775 public function dropTable( $tableName, $fName = __METHOD__
) {
4776 if ( !$this->tableExists( $tableName, $fName ) ) {
4779 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
4781 return $this->query( $sql, $fName );
4784 public function getInfinity() {
4788 public function encodeExpiry( $expiry ) {
4789 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4790 ?
$this->getInfinity()
4791 : $this->timestamp( $expiry );
4794 public function decodeExpiry( $expiry, $format = TS_MW
) {
4795 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
4799 return ConvertibleTimestamp
::convert( $format, $expiry );
4802 public function setBigSelects( $value = true ) {
4806 public function isReadOnly() {
4807 return ( $this->getReadOnlyReason() !== false );
4811 * @return string|bool Reason this DB is read-only or false if it is not
4813 protected function getReadOnlyReason() {
4814 $reason = $this->getLBInfo( 'readOnlyReason' );
4815 if ( is_string( $reason ) ) {
4817 } elseif ( $this->getLBInfo( 'replica' ) ) {
4818 return "Server is configured in the role of a read-only replica database.";
4824 public function setTableAliases( array $aliases ) {
4825 $this->tableAliases
= $aliases;
4828 public function setIndexAliases( array $aliases ) {
4829 $this->indexAliases
= $aliases;
4837 protected function hasFlags( $field, $flags ) {
4838 return ( ( $field & $flags ) === $flags );
4842 * Get the underlying binding connection handle
4844 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
4845 * This catches broken callers than catch and ignore disconnection exceptions.
4846 * Unlike checking isOpen(), this is safe to call inside of open().
4849 * @throws DBUnexpectedError
4852 protected function getBindingHandle() {
4853 if ( !$this->conn
) {
4854 throw new DBUnexpectedError(
4856 'DB connection was already closed or the connection dropped'
4863 public function __toString() {
4864 // spl_object_id is PHP >= 7.2
4865 $id = function_exists( 'spl_object_id' )
4866 ?
spl_object_id( $this )
4867 : spl_object_hash( $this );
4869 $description = $this->getType() . ' object #' . $id;
4870 if ( is_resource( $this->conn
) ) {
4871 $description .= ' (' . (string)$this->conn
. ')'; // "resource id #<ID>"
4872 } elseif ( is_object( $this->conn
) ) {
4873 // spl_object_id is PHP >= 7.2
4874 $handleId = function_exists( 'spl_object_id' )
4875 ?
spl_object_id( $this->conn
)
4876 : spl_object_hash( $this->conn
);
4877 $description .= " (handle id #$handleId)";
4880 return $description;
4884 * Make sure that copies do not share the same client binding handle
4885 * @throws DBConnectionError
4887 public function __clone() {
4888 $this->connLogger
->warning(
4889 "Cloning " . static::class . " is not recommended; forking connection",
4890 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
4893 if ( $this->isOpen() ) {
4894 // Open a new connection resource without messing with the old one
4896 $this->trxEndCallbacks
= []; // don't copy
4897 $this->trxSectionCancelCallbacks
= []; // don't copy
4898 $this->handleSessionLossPreconnect(); // no trx or locks anymore
4903 $this->currentDomain
->getDatabase(),
4904 $this->currentDomain
->getSchema(),
4905 $this->tablePrefix()
4907 $this->lastPing
= microtime( true );
4912 * Called by serialize. Throw an exception when DB connection is serialized.
4913 * This causes problems on some database engines because the connection is
4914 * not restored on unserialize.
4916 public function __sleep() {
4917 throw new RuntimeException( 'Database serialization may cause problems, since ' .
4918 'the connection is not restored on wakeup' );
4922 * Run a few simple sanity checks and close dangling connections
4924 public function __destruct() {
4925 if ( $this->trxLevel() && $this->trxDoneWrites
) {
4926 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})" );
4929 $danglingWriters = $this->pendingWriteAndCallbackCallers();
4930 if ( $danglingWriters ) {
4931 $fnames = implode( ', ', $danglingWriters );
4932 trigger_error( "DB transaction writes or callbacks still pending ($fnames)" );
4935 if ( $this->conn
) {
4936 // Avoid connection leaks for sanity. Normally, resources close at script completion.
4937 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4938 AtEase
::suppressWarnings();
4939 $this->closeConnection();
4940 AtEase
::restoreWarnings();
4947 * @deprecated since 1.28
4949 class_alias( Database
::class, 'DatabaseBase' );
4952 * @deprecated since 1.29
4954 class_alias( Database
::class, 'Database' );