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 BagOStuff APC cache */
52 /** @var LoggerInterface */
53 protected $connLogger;
54 /** @var LoggerInterface */
55 protected $queryLogger;
56 /** @var callable Error logging callback */
57 protected $errorLogger;
58 /** @var callable Deprecation logging callback */
59 protected $deprecationLogger;
60 /** @var callable|null */
62 /** @var TransactionProfiler */
63 protected $trxProfiler;
65 /** @var DatabaseDomain */
66 protected $currentDomain;
68 /** @var object|resource|null Database connection */
71 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
72 private $lazyMasterHandle;
74 /** @var string Server that this instance is currently connected to */
76 /** @var string User that this instance is currently connected under the name of */
78 /** @var string Password used to establish the current connection */
80 /** @var bool Whether this PHP instance is for a CLI script */
82 /** @var string Agent name for query profiling */
84 /** @var array Parameters used by initConnection() to establish a connection */
85 protected $connectionParams;
86 /** @var string[]|int[]|float[] SQL variables values to use for all new connections */
87 protected $connectionVariables;
88 /** @var int Row batch size to use for emulated INSERT SELECT queries */
89 protected $nonNativeInsertSelectBatchSize;
91 /** @var int Current bit field of class DBO_* constants */
93 /** @var array Current LoadBalancer tracking information */
94 protected $lbInfo = [];
95 /** @var string Current SQL query delimiter */
96 protected $delimiter = ';';
97 /** @var array[] Current map of (table => (dbname, schema, prefix) map) */
98 protected $tableAliases = [];
99 /** @var string[] Current map of (index alias => index) */
100 protected $indexAliases = [];
101 /** @var array|null Current variables use for schema element placeholders */
102 protected $schemaVars;
104 /** @var string|bool|null Stashed value of html_errors INI setting */
106 /** @var int[] Prior flags member variable values */
107 private $priorFlags = [];
109 /** @var array Map of (name => 1) for locks obtained via lock() */
110 protected $sessionNamedLocks = [];
111 /** @var array Map of (table name => 1) for TEMPORARY tables */
112 protected $sessionTempTables = [];
114 /** @var string ID of the active transaction or the empty string otherwise */
115 private $trxShortId = '';
116 /** @var int Transaction status */
117 private $trxStatus = self
::STATUS_TRX_NONE
;
118 /** @var Exception|null The last error that caused the status to become STATUS_TRX_ERROR */
119 private $trxStatusCause;
120 /** @var array|null Error details of the last statement-only rollback */
121 private $trxStatusIgnoredCause;
122 /** @var float|null UNIX timestamp at the time of BEGIN for the last transaction */
123 private $trxTimestamp = null;
124 /** @var float Replication lag estimate at the time of BEGIN for the last transaction */
125 private $trxReplicaLag = null;
126 /** @var string Name of the function that start the last transaction */
127 private $trxFname = null;
128 /** @var bool Whether possible write queries were done in the last transaction started */
129 private $trxDoneWrites = false;
130 /** @var bool Whether the current transaction was started implicitly due to DBO_TRX */
131 private $trxAutomatic = false;
132 /** @var int Counter for atomic savepoint identifiers (reset with each transaction) */
133 private $trxAtomicCounter = 0;
134 /** @var array List of (name, unique ID, savepoint ID) for each active atomic section level */
135 private $trxAtomicLevels = [];
136 /** @var bool Whether the current transaction was started implicitly by startAtomic() */
137 private $trxAutomaticAtomic = false;
138 /** @var string[] Write query callers of the current transaction */
139 private $trxWriteCallers = [];
140 /** @var float Seconds spent in write queries for the current transaction */
141 private $trxWriteDuration = 0.0;
142 /** @var int Number of write queries for the current transaction */
143 private $trxWriteQueryCount = 0;
144 /** @var int Number of rows affected by write queries for the current transaction */
145 private $trxWriteAffectedRows = 0;
146 /** @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries */
147 private $trxWriteAdjDuration = 0.0;
148 /** @var int Number of write queries counted in trxWriteAdjDuration */
149 private $trxWriteAdjQueryCount = 0;
150 /** @var array[] List of (callable, method name, atomic section id) */
151 private $trxIdleCallbacks = [];
152 /** @var array[] List of (callable, method name, atomic section id) */
153 private $trxPreCommitCallbacks = [];
154 /** @var array[] List of (callable, method name, atomic section id) */
155 private $trxEndCallbacks = [];
156 /** @var array[] List of (callable, method name, atomic section id) */
157 private $trxSectionCancelCallbacks = [];
158 /** @var callable[] Map of (name => callable) */
159 private $trxRecurringCallbacks = [];
160 /** @var bool Whether to suppress triggering of transaction end callbacks */
161 private $trxEndCallbacksSuppressed = false;
163 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
164 protected $affectedRowCount;
166 /** @var float UNIX timestamp */
167 private $lastPing = 0.0;
168 /** @var string The last SQL query attempted */
169 private $lastQuery = '';
170 /** @var float|bool UNIX timestamp of last write query */
171 private $lastWriteTime = false;
172 /** @var string|bool */
173 private $lastPhpError = false;
174 /** @var float Query rount trip time estimate */
175 private $lastRoundTripEstimate = 0.0;
177 /** @var int|null Integer ID of the managing LBFactory instance or null if none */
180 /** @var string Lock granularity is on the level of the entire database */
181 const ATTR_DB_LEVEL_LOCKING
= 'db-level-locking';
182 /** @var string The SCHEMA keyword refers to a grouping of tables in a database */
183 const ATTR_SCHEMAS_AS_TABLE_GROUPS
= 'supports-schemas';
185 /** @var int New Database instance will not be connected yet when returned */
186 const NEW_UNCONNECTED
= 0;
187 /** @var int New Database instance will already be connected when returned */
188 const NEW_CONNECTED
= 1;
190 /** @var int Transaction is in a error state requiring a full or savepoint rollback */
191 const STATUS_TRX_ERROR
= 1;
192 /** @var int Transaction is active and in a normal state */
193 const STATUS_TRX_OK
= 2;
194 /** @var int No transaction is active */
195 const STATUS_TRX_NONE
= 3;
197 /** @var string Idiom used when a cancelable atomic section started the transaction */
198 private static $NOT_APPLICABLE = 'n/a';
199 /** @var string Prefix to the atomic section counter used to make savepoint IDs */
200 private static $SAVEPOINT_PREFIX = 'wikimedia_rdbms_atomic';
202 /** @var int Writes to this temporary table do not affect lastDoneWrites() */
203 private static $TEMP_NORMAL = 1;
204 /** @var int Writes to this temporary table effect lastDoneWrites() */
205 private static $TEMP_PSEUDO_PERMANENT = 2;
207 /** @var int Number of times to re-try an operation in case of deadlock */
208 private static $DEADLOCK_TRIES = 4;
209 /** @var int Minimum time to wait before retry, in microseconds */
210 private static $DEADLOCK_DELAY_MIN = 500000;
211 /** @var int Maximum time to wait before retry */
212 private static $DEADLOCK_DELAY_MAX = 1500000;
214 /** @var int How long before it is worth doing a dummy query to test the connection */
215 private static $PING_TTL = 1.0;
216 /** @var string Dummy SQL query */
217 private static $PING_QUERY = 'SELECT 1 AS ping';
219 /** @var float Guess of how many seconds it takes to replicate a small insert */
220 private static $TINY_WRITE_SEC = 0.010;
221 /** @var float Consider a write slow if it took more than this many seconds */
222 private static $SLOW_WRITE_SEC = 0.500;
223 /** @var float Assume an insert of this many rows or less should be fast to replicate */
224 private static $SMALL_WRITE_ROWS = 100;
226 /** @var string[] List of DBO_* flags that can be changed after connection */
227 protected static $MUTABLE_FLAGS = [
233 /** @var int Bit field of all DBO_* flags that can be changed after connection */
234 protected static $DBO_MUTABLE = (
235 self
::DBO_DEBUG | self
::DBO_NOBUFFER | self
::DBO_TRX | self
::DBO_DDLMODE
239 * @note exceptions for missing libraries/drivers should be thrown in initConnection()
240 * @param array $params Parameters passed from Database::factory()
242 public function __construct( array $params ) {
243 $this->connectionParams
= [];
244 foreach ( [ 'host', 'user', 'password', 'dbname', 'schema', 'tablePrefix' ] as $name ) {
245 $this->connectionParams
[$name] = $params[$name];
247 $this->connectionVariables
= $params['variables'] ??
[];
248 $this->cliMode
= $params['cliMode'];
249 $this->agent
= $params['agent'];
250 $this->flags
= $params['flags'];
251 if ( $this->flags
& self
::DBO_DEFAULT
) {
252 if ( $this->cliMode
) {
253 $this->flags
&= ~self
::DBO_TRX
;
255 $this->flags |
= self
::DBO_TRX
;
258 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'] ??
10000;
260 $this->srvCache
= $params['srvCache'] ??
new HashBagOStuff();
261 $this->profiler
= is_callable( $params['profiler'] ) ?
$params['profiler'] : null;
262 $this->trxProfiler
= $params['trxProfiler'];
263 $this->connLogger
= $params['connLogger'];
264 $this->queryLogger
= $params['queryLogger'];
265 $this->errorLogger
= $params['errorLogger'];
266 $this->deprecationLogger
= $params['deprecationLogger'];
268 // Set initial dummy domain until open() sets the final DB/prefix
269 $this->currentDomain
= new DatabaseDomain(
270 $params['dbname'] != '' ?
$params['dbname'] : null,
271 $params['schema'] != '' ?
$params['schema'] : null,
272 $params['tablePrefix']
275 $this->ownerId
= $params['ownerId'] ??
null;
279 * Initialize the connection to the database over the wire (or to local files)
281 * @throws LogicException
282 * @throws InvalidArgumentException
283 * @throws DBConnectionError
286 final public function initConnection() {
287 if ( $this->isOpen() ) {
288 throw new LogicException( __METHOD__
. ': already connected' );
290 // Establish the connection
291 $this->doInitConnection();
295 * Actually connect to the database over the wire (or to local files)
297 * @throws DBConnectionError
300 protected function doInitConnection() {
302 $this->connectionParams
['host'],
303 $this->connectionParams
['user'],
304 $this->connectionParams
['password'],
305 $this->connectionParams
['dbname'],
306 $this->connectionParams
['schema'],
307 $this->connectionParams
['tablePrefix']
312 * Open a new connection to the database (closing any existing one)
314 * @param string|null $server Database server host
315 * @param string|null $user Database user name
316 * @param string|null $password Database user password
317 * @param string|null $dbName Database name
318 * @param string|null $schema Database schema name
319 * @param string $tablePrefix Table prefix
320 * @throws DBConnectionError
322 abstract protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix );
325 * Construct a Database subclass instance given a database type and parameters
327 * This also connects to the database immediately upon object construction
329 * @param string $type A possible DB type (sqlite, mysql, postgres,...)
330 * @param array $params Parameter map with keys:
331 * - host : The hostname of the DB server
332 * - user : The name of the database user the client operates under
333 * - password : The password for the database user
334 * - dbname : The name of the database to use where queries do not specify one.
335 * The database must exist or an error might be thrown. Setting this to the empty string
336 * will avoid any such errors and make the handle have no implicit database scope. This is
337 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
338 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
339 * in which user names and such are defined, e.g. users are database-specific in Postgres.
340 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
341 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
342 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
343 * recognized in queries. This can be used in place of schemas for handle site farms.
344 * - flags : Optional bit field of DBO_* constants that define connection, protocol,
345 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
346 * flag in place UNLESS this this database simply acts as a key/value store.
347 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
348 * 'mysqli' driver; the old one 'mysql' has been removed.
349 * - variables: Optional map of session variables to set after connecting. This can be
350 * used to adjust lock timeouts or encoding modes and the like.
351 * - connLogger: Optional PSR-3 logger interface instance.
352 * - queryLogger: Optional PSR-3 logger interface instance.
353 * - profiler : Optional callback that takes a section name argument and returns
354 * a ScopedCallback instance that ends the profile section in its destructor.
355 * These will be called in query(), using a simplified version of the SQL that
356 * also includes the agent as a SQL comment.
357 * - trxProfiler: Optional TransactionProfiler instance.
358 * - errorLogger: Optional callback that takes an Exception and logs it.
359 * - deprecationLogger: Optional callback that takes a string and logs it.
360 * - cliMode: Whether to consider the execution context that of a CLI script.
361 * - agent: Optional name used to identify the end-user in query profiling/logging.
362 * - srvCache: Optional BagOStuff instance to an APC-style cache.
363 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT.
364 * - ownerId: Optional integer ID of a LoadBalancer instance that manages this instance.
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(),
388 $normalizedParams = [
390 'host' => strlen( $params['host'] ) ?
$params['host'] : null,
391 'user' => strlen( $params['user'] ) ?
$params['user'] : null,
392 'password' => is_string( $params['password'] ) ?
$params['password'] : null,
393 'dbname' => strlen( $params['dbname'] ) ?
$params['dbname'] : null,
394 'schema' => strlen( $params['schema'] ) ?
$params['schema'] : null,
395 'tablePrefix' => (string)$params['tablePrefix'],
396 'flags' => (int)$params['flags'],
397 'variables' => $params['variables'],
398 'cliMode' => (bool)$params['cliMode'],
399 'agent' => (string)$params['agent'],
400 // Objects and callbacks
401 'srvCache' => $params['srvCache'] ??
new HashBagOStuff(),
402 'profiler' => $params['profiler'] ??
null,
403 'trxProfiler' => $params['trxProfiler'] ??
new TransactionProfiler(),
404 'connLogger' => $params['connLogger'] ??
new NullLogger(),
405 'queryLogger' => $params['queryLogger'] ??
new NullLogger(),
406 'errorLogger' => $params['errorLogger'] ??
function ( Exception
$e ) {
407 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
409 'deprecationLogger' => $params['deprecationLogger'] ??
function ( $msg ) {
410 trigger_error( $msg, E_USER_DEPRECATED
);
414 /** @var Database $conn */
415 $conn = new $class( $normalizedParams );
416 if ( $connect === self
::NEW_CONNECTED
) {
417 $conn->initConnection();
427 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
428 * @param string|null $driver Optional name of a specific DB client driver
429 * @return array Map of (Database::ATTR_* constant => value) for all such constants
430 * @throws InvalidArgumentException
433 final public static function attributesFromType( $dbType, $driver = null ) {
435 self
::ATTR_DB_LEVEL_LOCKING
=> false,
436 self
::ATTR_SCHEMAS_AS_TABLE_GROUPS
=> false
439 $class = self
::getClass( $dbType, $driver );
441 return call_user_func( [ $class, 'getAttributes' ] ) +
$defaults;
445 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
446 * @param string|null $driver Optional name of a specific DB client driver
447 * @return string Database subclass name to use
448 * @throws InvalidArgumentException
450 private static function getClass( $dbType, $driver = null ) {
451 // For database types with built-in support, the below maps type to IDatabase
452 // implementations. For types with multipe driver implementations (PHP extensions),
453 // an array can be used, keyed by extension name. In case of an array, the
454 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
455 // we auto-detect the first available driver. For types without built-in support,
456 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
457 static $builtinTypes = [
458 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
459 'sqlite' => DatabaseSqlite
::class,
460 'postgres' => DatabasePostgres
::class,
463 $dbType = strtolower( $dbType );
466 if ( isset( $builtinTypes[$dbType] ) ) {
467 $possibleDrivers = $builtinTypes[$dbType];
468 if ( is_string( $possibleDrivers ) ) {
469 $class = $possibleDrivers;
470 } elseif ( (string)$driver !== '' ) {
471 if ( !isset( $possibleDrivers[$driver] ) ) {
472 throw new InvalidArgumentException( __METHOD__
.
473 " type '$dbType' does not support driver '{$driver}'" );
476 $class = $possibleDrivers[$driver];
478 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
479 if ( extension_loaded( $posDriver ) ) {
480 $class = $possibleClass;
486 $class = 'Database' . ucfirst( $dbType );
489 if ( $class === false ) {
490 throw new InvalidArgumentException( __METHOD__
.
491 " no viable database extension found for type '$dbType'" );
498 * @return array Map of (Database::ATTR_* constant => value)
501 protected static function getAttributes() {
506 * Set the PSR-3 logger interface to use for query logging. (The logger
507 * interfaces for connection logging and error logging can be set with the
510 * @param LoggerInterface $logger
512 public function setLogger( LoggerInterface
$logger ) {
513 $this->queryLogger
= $logger;
516 public function getServerInfo() {
517 return $this->getServerVersion();
521 * Backwards-compatibility no-op method for disabling query buffering
523 * @param null|bool $buffer Whether to buffer queries (ignored)
524 * @return bool Whether buffering was already enabled (always true)
525 * @deprecated Since 1.34 Use query batching; this no longer does anything
527 public function bufferResults( $buffer = null ) {
531 final public function trxLevel() {
532 return ( $this->trxShortId
!= '' ) ?
1 : 0;
535 public function trxTimestamp() {
536 return $this->trxLevel() ?
$this->trxTimestamp
: null;
540 * @return int One of the STATUS_TRX_* class constants
543 public function trxStatus() {
544 return $this->trxStatus
;
547 public function tablePrefix( $prefix = null ) {
548 $old = $this->currentDomain
->getTablePrefix();
549 if ( $prefix !== null ) {
550 $this->currentDomain
= new DatabaseDomain(
551 $this->currentDomain
->getDatabase(),
552 $this->currentDomain
->getSchema(),
560 public function dbSchema( $schema = null ) {
561 if ( strlen( $schema ) && $this->getDBname() === null ) {
562 throw new DBUnexpectedError( $this, "Cannot set schema to '$schema'; no database set" );
565 $old = $this->currentDomain
->getSchema();
566 if ( $schema !== null ) {
567 $this->currentDomain
= new DatabaseDomain(
568 $this->currentDomain
->getDatabase(),
569 // DatabaseDomain uses null for unspecified schemas
570 strlen( $schema ) ?
$schema : null,
571 $this->currentDomain
->getTablePrefix()
579 * @return string Schema to use to qualify relations in queries
581 protected function relationSchemaQualifier() {
582 return $this->dbSchema();
585 public function getLBInfo( $name = null ) {
586 if ( is_null( $name ) ) {
587 return $this->lbInfo
;
590 if ( array_key_exists( $name, $this->lbInfo
) ) {
591 return $this->lbInfo
[$name];
597 public function setLBInfo( $nameOrArray, $value = null ) {
598 if ( is_array( $nameOrArray ) ) {
599 $this->lbInfo
= $nameOrArray;
600 } elseif ( is_string( $nameOrArray ) ) {
601 if ( $value !== null ) {
602 $this->lbInfo
[$nameOrArray] = $value;
604 unset( $this->lbInfo
[$nameOrArray] );
607 throw new InvalidArgumentException( "Got non-string key" );
611 public function setLazyMasterHandle( IDatabase
$conn ) {
612 $this->lazyMasterHandle
= $conn;
616 * @return IDatabase|null
617 * @see setLazyMasterHandle()
620 protected function getLazyMasterHandle() {
621 return $this->lazyMasterHandle
;
624 public function implicitOrderby() {
628 public function lastQuery() {
629 return $this->lastQuery
;
632 public function lastDoneWrites() {
633 return $this->lastWriteTime ?
: false;
636 public function writesPending() {
637 return $this->trxLevel() && $this->trxDoneWrites
;
640 public function writesOrCallbacksPending() {
641 return $this->trxLevel() && (
642 $this->trxDoneWrites ||
643 $this->trxIdleCallbacks ||
644 $this->trxPreCommitCallbacks ||
645 $this->trxEndCallbacks ||
646 $this->trxSectionCancelCallbacks
650 public function preCommitCallbacksPending() {
651 return $this->trxLevel() && $this->trxPreCommitCallbacks
;
655 * @return string|null
657 final protected function getTransactionRoundId() {
658 // If transaction round participation is enabled, see if one is active
659 if ( $this->getFlag( self
::DBO_TRX
) ) {
660 $id = $this->getLBInfo( 'trxRoundId' );
662 return is_string( $id ) ?
$id : null;
668 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
669 if ( !$this->trxLevel() ) {
671 } elseif ( !$this->trxDoneWrites
) {
676 case self
::ESTIMATE_DB_APPLY
:
677 return $this->pingAndCalculateLastTrxApplyTime();
678 default: // everything
679 return $this->trxWriteDuration
;
684 * @return float Time to apply writes to replicas based on trxWrite* fields
686 private function pingAndCalculateLastTrxApplyTime() {
689 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
690 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
691 // For omitted queries, make them count as something at least
692 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
693 $applyTime +
= self
::$TINY_WRITE_SEC * $omitted;
698 public function pendingWriteCallers() {
699 return $this->trxLevel() ?
$this->trxWriteCallers
: [];
702 public function pendingWriteRowsAffected() {
703 return $this->trxWriteAffectedRows
;
707 * List the methods that have write queries or callbacks for the current transaction
709 * This method should not be used outside of Database/LoadBalancer
714 public function pendingWriteAndCallbackCallers() {
715 $fnames = $this->pendingWriteCallers();
717 $this->trxIdleCallbacks
,
718 $this->trxPreCommitCallbacks
,
719 $this->trxEndCallbacks
,
720 $this->trxSectionCancelCallbacks
722 foreach ( $callbacks as $callback ) {
723 $fnames[] = $callback[1];
733 private function flatAtomicSectionList() {
734 return array_reduce( $this->trxAtomicLevels
, function ( $accum, $v ) {
735 return $accum === null ?
$v[0] : "$accum, " . $v[0];
739 public function isOpen() {
740 return (bool)$this->conn
;
743 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
744 if ( $flag & ~
static::$DBO_MUTABLE ) {
745 throw new DBUnexpectedError(
747 "Got $flag (allowed: " . implode( ', ', static::$MUTABLE_FLAGS ) . ')'
751 if ( $remember === self
::REMEMBER_PRIOR
) {
752 array_push( $this->priorFlags
, $this->flags
);
755 $this->flags |
= $flag;
758 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
759 if ( $flag & ~
static::$DBO_MUTABLE ) {
760 throw new DBUnexpectedError(
762 "Got $flag (allowed: " . implode( ', ', static::$MUTABLE_FLAGS ) . ')'
766 if ( $remember === self
::REMEMBER_PRIOR
) {
767 array_push( $this->priorFlags
, $this->flags
);
770 $this->flags
&= ~
$flag;
773 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
774 if ( !$this->priorFlags
) {
778 if ( $state === self
::RESTORE_INITIAL
) {
779 $this->flags
= reset( $this->priorFlags
);
780 $this->priorFlags
= [];
782 $this->flags
= array_pop( $this->priorFlags
);
786 public function getFlag( $flag ) {
787 return ( ( $this->flags
& $flag ) === $flag );
790 public function getDomainID() {
791 return $this->currentDomain
->getId();
795 * Get information about an index into an object
796 * @param string $table Table name
797 * @param string $index Index name
798 * @param string $fname Calling function name
799 * @return mixed Database-specific index description class or false if the index does not exist
801 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
804 * Wrapper for addslashes()
806 * @param string $s String to be slashed.
807 * @return string Slashed string.
809 abstract function strencode( $s );
812 * Set a custom error handler for logging errors during database connection
814 protected function installErrorHandler() {
815 $this->lastPhpError
= false;
816 $this->htmlErrors
= ini_set( 'html_errors', '0' );
817 set_error_handler( [ $this, 'connectionErrorLogger' ] );
821 * Restore the previous error handler and return the last PHP error for this DB
823 * @return bool|string
825 protected function restoreErrorHandler() {
826 restore_error_handler();
827 if ( $this->htmlErrors
!== false ) {
828 ini_set( 'html_errors', $this->htmlErrors
);
831 return $this->getLastPHPError();
835 * @return string|bool Last PHP error for this DB (typically connection errors)
837 protected function getLastPHPError() {
838 if ( $this->lastPhpError
) {
839 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->lastPhpError
);
840 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
849 * Error handler for logging errors during database connection
850 * This method should not be used outside of Database classes
853 * @param string $errstr
855 public function connectionErrorLogger( $errno, $errstr ) {
856 $this->lastPhpError
= $errstr;
860 * Create a log context to pass to PSR-3 logger functions.
862 * @param array $extras Additional data to add to context
865 protected function getLogContext( array $extras = [] ) {
868 'db_server' => $this->server
,
869 'db_name' => $this->getDBname(),
870 'db_user' => $this->user
,
876 final public function close( $fname = __METHOD__
, $owner = null ) {
877 $error = null; // error to throw after disconnecting
879 $wasOpen = (bool)$this->conn
;
880 // This should mostly do nothing if the connection is already closed
882 // Roll back any dangling transaction first
883 if ( $this->trxLevel() ) {
884 if ( $this->trxAtomicLevels
) {
885 // Cannot let incomplete atomic sections be committed
886 $levels = $this->flatAtomicSectionList();
887 $error = "$fname: atomic sections $levels are still open";
888 } elseif ( $this->trxAutomatic
) {
889 // Only the connection manager can commit non-empty DBO_TRX transactions
890 // (empty ones we can silently roll back)
891 if ( $this->writesOrCallbacksPending() ) {
892 $error = "$fname: " .
893 "expected mass rollback of all peer transactions (DBO_TRX set)";
896 // Manual transactions should have been committed or rolled
897 // back, even if empty.
898 $error = "$fname: transaction is still open (from {$this->trxFname})";
901 if ( $this->trxEndCallbacksSuppressed
&& $error === null ) {
902 $error = "$fname: callbacks are suppressed; cannot properly commit";
905 // Rollback the changes and run any callbacks as needed
906 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
909 // Close the actual connection in the binding handle
910 $closed = $this->closeConnection();
912 $closed = true; // already closed; nothing to do
917 // Log or throw any unexpected errors after having disconnected
918 if ( $error !== null ) {
919 // T217819, T231443: if this is probably just LoadBalancer trying to recover from
920 // errors and shutdown, then log any problems and move on since the request has to
921 // end one way or another. Throwing errors is not very useful at some point.
922 if ( $this->ownerId
!== null && $owner === $this->ownerId
) {
923 $this->queryLogger
->error( $error );
925 throw new DBUnexpectedError( $this, $error );
929 // Note that various subclasses call close() at the start of open(), which itself is
930 // called by replaceLostConnection(). In that case, just because onTransactionResolution()
931 // callbacks are pending does not mean that an exception should be thrown. Rather, they
932 // will be executed after the reconnection step.
934 // Sanity check that no callbacks are dangling
935 $fnames = $this->pendingWriteAndCallbackCallers();
937 throw new RuntimeException(
938 "Transaction callbacks are still pending: " . implode( ', ', $fnames )
947 * Make sure there is an open connection handle (alive or not) as a sanity check
949 * This guards against fatal errors to the binding handle not being defined
950 * in cases where open() was never called or close() was already called
952 * @throws DBUnexpectedError
954 final protected function assertHasConnectionHandle() {
955 if ( !$this->isOpen() ) {
956 throw new DBUnexpectedError( $this, "DB connection was already closed" );
961 * Make sure that this server is not marked as a replica nor read-only as a sanity check
963 * @throws DBReadOnlyRoleError
964 * @throws DBReadOnlyError
966 protected function assertIsWritableMaster() {
967 if ( $this->getLBInfo( 'replica' ) ) {
968 throw new DBReadOnlyRoleError(
970 'Write operations are not allowed on replica database connections'
973 $reason = $this->getReadOnlyReason();
974 if ( $reason !== false ) {
975 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
980 * Closes underlying database connection
982 * @return bool Whether connection was closed successfully
984 abstract protected function closeConnection();
987 * Run a query and return a DBMS-dependent wrapper or boolean
989 * This is meant to handle the basic command of actually sending a query to the
990 * server via the driver. No implicit transaction, reconnection, nor retry logic
991 * should happen here. The higher level query() method is designed to handle those
992 * sorts of concerns. This method should not trigger such higher level methods.
994 * The lastError() and lastErrno() methods should meaningfully reflect what error,
995 * if any, occured during the last call to this method. Methods like executeQuery(),
996 * query(), select(), insert(), update(), delete(), and upsert() implement their calls
997 * to doQuery() such that an immediately subsequent call to lastError()/lastErrno()
998 * meaningfully reflects any error that occured during that public query method call.
1000 * For SELECT queries, this returns either:
1001 * - a) A driver-specific value/resource, only on success. This can be iterated
1002 * over by calling fetchObject()/fetchRow() until there are no more rows.
1003 * Alternatively, the result can be passed to resultObject() to obtain an
1004 * IResultWrapper instance which can then be iterated over via "foreach".
1005 * - b) False, on any query failure
1007 * For non-SELECT queries, this returns either:
1008 * - a) A driver-specific value/resource, only on success
1009 * - b) True, only on success (e.g. no meaningful result other than "OK")
1010 * - c) False, on any query failure
1012 * @param string $sql SQL query
1013 * @return mixed|bool An object, resource, or true on success; false on failure
1015 abstract protected function doQuery( $sql );
1018 * Determine whether a query writes to the DB. When in doubt, this returns true.
1022 * - Subsequent web requests should not need to wait for replication from
1023 * the master position seen by this web request, unless this request made
1024 * changes to the master. This is handled by ChronologyProtector by checking
1025 * doneWrites() at the end of the request. doneWrites() returns true if any
1026 * query set lastWriteTime; which query() does based on isWriteQuery().
1028 * - Reject write queries to replica DBs, in query().
1030 * @param string $sql
1033 protected function isWriteQuery( $sql ) {
1034 // BEGIN and COMMIT queries are considered read queries here.
1035 // Database backends and drivers (MySQL, MariaDB, php-mysqli) generally
1036 // treat these as write queries, in that their results have "affected rows"
1037 // as meta data as from writes, instead of "num rows" as from reads.
1038 // But, we treat them as read queries because when reading data (from
1039 // either replica or master) we use transactions to enable repeatable-read
1040 // snapshots, which ensures we get consistent results from the same snapshot
1041 // for all queries within a request. Use cases:
1042 // - Treating these as writes would trigger ChronologyProtector (see method doc).
1043 // - We use this method to reject writes to replicas, but we need to allow
1044 // use of transactions on replicas for read snapshots. This is fine given
1045 // that transactions by themselves don't make changes, only actual writes
1046 // within the transaction matter, which we still detect.
1048 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SAVEPOINT|RELEASE|SET|SHOW|EXPLAIN|USE|\(SELECT)\b/i',
1054 * @param string $sql
1055 * @return string|null
1057 protected function getQueryVerb( $sql ) {
1058 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
1062 * Determine whether a SQL statement is sensitive to isolation level.
1064 * A SQL statement is considered transactable if its result could vary
1065 * depending on the transaction isolation level. Operational commands
1066 * such as 'SET' and 'SHOW' are not considered to be transactable.
1068 * Main purpose: Used by query() to decide whether to begin a transaction
1069 * before the current query (in DBO_TRX mode, on by default).
1071 * @param string $sql
1074 protected function isTransactableQuery( $sql ) {
1076 $this->getQueryVerb( $sql ),
1077 [ 'BEGIN', 'ROLLBACK', 'COMMIT', 'SET', 'SHOW', 'CREATE', 'ALTER', 'USE', 'SHOW' ],
1083 * @param string $sql A SQL query
1084 * @param bool $pseudoPermanent Treat any table from CREATE TEMPORARY as pseudo-permanent
1085 * @return array A n-tuple of:
1086 * - int|null: A self::TEMP_* constant for temp table operations or null otherwise
1087 * - string|null: The name of the new temporary table $sql creates, or null
1088 * - string|null: The name of the temporary table that $sql drops, or null
1090 protected function getTempWrites( $sql, $pseudoPermanent ) {
1091 static $qt = '[`"\']?(\w+)[`"\']?'; // quoted table
1094 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?' . $qt . '/i',
1098 $type = $pseudoPermanent ? self
::$TEMP_PSEUDO_PERMANENT : self
::$TEMP_NORMAL;
1100 return [ $type, $matches[1], null ];
1101 } elseif ( preg_match(
1102 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt . '/i',
1106 return [ $this->sessionTempTables
[$matches[1]] ??
null, null, $matches[1] ];
1107 } elseif ( preg_match(
1108 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt . '/i',
1112 return [ $this->sessionTempTables
[$matches[1]] ??
null, null, null ];
1113 } elseif ( preg_match(
1114 '/^(?:(?:INSERT|REPLACE)\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+' . $qt . '/i',
1118 return [ $this->sessionTempTables
[$matches[1]] ??
null, null, null ];
1121 return [ null, null, null ];
1125 * @param IResultWrapper|bool $ret
1126 * @param int|null $tmpType TEMP_NORMAL or TEMP_PSEUDO_PERMANENT
1127 * @param string|null $tmpNew Name of created temp table
1128 * @param string|null $tmpDel Name of dropped temp table
1130 protected function registerTempWrites( $ret, $tmpType, $tmpNew, $tmpDel ) {
1131 if ( $ret !== false ) {
1132 if ( $tmpNew !== null ) {
1133 $this->sessionTempTables
[$tmpNew] = $tmpType;
1135 if ( $tmpDel !== null ) {
1136 unset( $this->sessionTempTables
[$tmpDel] );
1141 public function query( $sql, $fname = __METHOD__
, $flags = 0 ) {
1142 $flags = (int)$flags; // b/c; this field used to be a bool
1143 // Sanity check that the SQL query is appropriate in the current context and is
1144 // allowed for an outside caller (e.g. does not break transaction/session tracking).
1145 $this->assertQueryIsCurrentlyAllowed( $sql, $fname );
1147 // Send the query to the server and fetch any corresponding errors
1148 list( $ret, $err, $errno, $unignorable ) = $this->executeQuery( $sql, $fname, $flags );
1149 if ( $ret === false ) {
1150 $ignoreErrors = $this->fieldHasBit( $flags, self
::QUERY_SILENCE_ERRORS
);
1151 // Throw an error unless both the ignore flag was set and a rollback is not needed
1152 $this->reportQueryError( $err, $errno, $sql, $fname, $ignoreErrors && !$unignorable );
1155 return $this->resultObject( $ret );
1159 * Execute a query, retrying it if there is a recoverable connection loss
1161 * This is similar to query() except:
1162 * - It does not prevent all non-ROLLBACK queries if there is a corrupted transaction
1163 * - It does not disallow raw queries that are supposed to use dedicated IDatabase methods
1164 * - It does not throw exceptions for common error cases
1166 * This is meant for internal use with Database subclasses.
1168 * @param string $sql Original SQL query
1169 * @param string $fname Name of the calling function
1170 * @param int $flags Bit field of class QUERY_* constants
1171 * @return array An n-tuple of:
1172 * - mixed|bool: An object, resource, or true on success; false on failure
1173 * - string: The result of calling lastError()
1174 * - int: The result of calling lastErrno()
1175 * - bool: Whether a rollback is needed to allow future non-rollback queries
1176 * @throws DBUnexpectedError
1178 final protected function executeQuery( $sql, $fname, $flags ) {
1179 $this->assertHasConnectionHandle();
1181 $priorTransaction = $this->trxLevel();
1183 if ( $this->isWriteQuery( $sql ) ) {
1184 // In theory, non-persistent writes are allowed in read-only mode, but due to things
1185 // like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1186 $this->assertIsWritableMaster();
1187 // Do not treat temporary table writes as "meaningful writes" since they are only
1188 // visible to one session and are not permanent. Profile them as reads. Integration
1189 // tests can override this behavior via $flags.
1190 $pseudoPermanent = $this->fieldHasBit( $flags, self
::QUERY_PSEUDO_PERMANENT
);
1191 list( $tmpType, $tmpNew, $tmpDel ) = $this->getTempWrites( $sql, $pseudoPermanent );
1192 $isPermWrite = ( $tmpType !== self
::$TEMP_NORMAL );
1193 // DBConnRef uses QUERY_REPLICA_ROLE to enforce the replica role for raw SQL queries
1194 if ( $isPermWrite && $this->fieldHasBit( $flags, self
::QUERY_REPLICA_ROLE
) ) {
1195 throw new DBReadOnlyRoleError( $this, "Cannot write; target role is DB_REPLICA" );
1198 // No permanent writes in this query
1199 $isPermWrite = false;
1200 // No temporary tables written to either
1201 list( $tmpType, $tmpNew, $tmpDel ) = [ null, null, null ];
1204 // Add trace comment to the begin of the sql string, right after the operator.
1205 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598).
1206 $encAgent = str_replace( '/', '-', $this->agent
);
1207 $commentedSql = preg_replace( '/\s|$/', " /* $fname $encAgent */ ", $sql, 1 );
1209 // Send the query to the server and fetch any corresponding errors.
1210 // This also doubles as a "ping" to see if the connection was dropped.
1211 list( $ret, $err, $errno, $recoverableSR, $recoverableCL, $reconnected ) =
1212 $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1214 // Check if the query failed due to a recoverable connection loss
1215 $allowRetry = !$this->fieldHasBit( $flags, self
::QUERY_NO_RETRY
);
1216 if ( $ret === false && $recoverableCL && $reconnected && $allowRetry ) {
1217 // Silently resend the query to the server since it is safe and possible
1218 list( $ret, $err, $errno, $recoverableSR, $recoverableCL ) =
1219 $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1222 // Register creation and dropping of temporary tables
1223 $this->registerTempWrites( $ret, $tmpType, $tmpNew, $tmpDel );
1225 $corruptedTrx = false;
1227 if ( $ret === false ) {
1228 if ( $priorTransaction ) {
1229 if ( $recoverableSR ) {
1230 # We're ignoring an error that caused just the current query to be aborted.
1231 # But log the cause so we can log a deprecation notice if a caller actually
1233 $this->trxStatusIgnoredCause
= [ $err, $errno, $fname ];
1234 } elseif ( !$recoverableCL ) {
1235 # Either the query was aborted or all queries after BEGIN where aborted.
1236 # In the first case, the only options going forward are (a) ROLLBACK, or
1237 # (b) ROLLBACK TO SAVEPOINT (if one was set). If the later case, the only
1238 # option is ROLLBACK, since the snapshots would have been released.
1239 $corruptedTrx = true; // cannot recover
1240 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
1241 $this->trxStatusCause
=
1242 $this->getQueryExceptionAndLog( $err, $errno, $sql, $fname );
1243 $this->trxStatusIgnoredCause
= null;
1248 return [ $ret, $err, $errno, $corruptedTrx ];
1252 * Wrapper for doQuery() that handles DBO_TRX, profiling, logging, affected row count
1253 * tracking, and reconnects (without retry) on query failure due to connection loss
1255 * @param string $sql Original SQL query
1256 * @param string $commentedSql SQL query with debugging/trace comment
1257 * @param bool $isPermWrite Whether the query is a (non-temporary table) write
1258 * @param string $fname Name of the calling function
1259 * @param int $flags Bit field of class QUERY_* constants
1260 * @return array An n-tuple of:
1261 * - mixed|bool: An object, resource, or true on success; false on failure
1262 * - string: The result of calling lastError()
1263 * - int: The result of calling lastErrno()
1264 * - bool: Whether a statement rollback error occured
1265 * - bool: Whether a disconnect *both* happened *and* was recoverable
1266 * - bool: Whether a reconnection attempt was *both* made *and* succeeded
1267 * @throws DBUnexpectedError
1269 private function executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags ) {
1270 $priorWritesPending = $this->writesOrCallbacksPending();
1272 if ( ( $flags & self
::QUERY_IGNORE_DBO_TRX
) == 0 ) {
1273 $this->beginIfImplied( $sql, $fname );
1276 // Keep track of whether the transaction has write queries pending
1277 if ( $isPermWrite ) {
1278 $this->lastWriteTime
= microtime( true );
1279 if ( $this->trxLevel() && !$this->trxDoneWrites
) {
1280 $this->trxDoneWrites
= true;
1281 $this->trxProfiler
->transactionWritingIn(
1282 $this->server
, $this->getDomainID(), $this->trxShortId
);
1286 $prefix = $this->getLBInfo( 'master' ) ?
'query-m: ' : 'query: ';
1287 $generalizedSql = new GeneralizedSql( $sql, $this->trxShortId
, $prefix );
1289 $startTime = microtime( true );
1290 $ps = $this->profiler
1291 ?
( $this->profiler
)( $generalizedSql->stringify() )
1293 $this->affectedRowCount
= null;
1294 $this->lastQuery
= $sql;
1295 $ret = $this->doQuery( $commentedSql );
1296 $lastError = $this->lastError();
1297 $lastErrno = $this->lastErrno();
1299 $this->affectedRowCount
= $this->affectedRows();
1300 unset( $ps ); // profile out (if set)
1301 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1303 $recoverableSR = false; // recoverable statement rollback?
1304 $recoverableCL = false; // recoverable connection loss?
1305 $reconnected = false; // reconnection both attempted and succeeded?
1307 if ( $ret !== false ) {
1308 $this->lastPing
= $startTime;
1309 if ( $isPermWrite && $this->trxLevel() ) {
1310 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1311 $this->trxWriteCallers
[] = $fname;
1313 } elseif ( $this->wasConnectionError( $lastErrno ) ) {
1314 # Check if no meaningful session state was lost
1315 $recoverableCL = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1316 # Update session state tracking and try to restore the connection
1317 $reconnected = $this->replaceLostConnection( __METHOD__
);
1319 # Check if only the last query was rolled back
1320 $recoverableSR = $this->wasKnownStatementRollbackError();
1323 if ( $sql === self
::$PING_QUERY ) {
1324 $this->lastRoundTripEstimate
= $queryRuntime;
1327 $this->trxProfiler
->recordQueryCompletion(
1331 $isPermWrite ?
$this->affectedRows() : $this->numRows( $ret )
1334 // Avoid the overhead of logging calls unless debug mode is enabled
1335 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
1336 $this->queryLogger
->debug(
1337 "{method} [{runtime}s] {db_host}: {sql}",
1340 'db_host' => $this->getServer(),
1342 'domain' => $this->getDomainID(),
1343 'runtime' => round( $queryRuntime, 3 )
1348 return [ $ret, $lastError, $lastErrno, $recoverableSR, $recoverableCL, $reconnected ];
1352 * Start an implicit transaction if DBO_TRX is enabled and no transaction is active
1354 * @param string $sql
1355 * @param string $fname
1357 private function beginIfImplied( $sql, $fname ) {
1359 !$this->trxLevel() &&
1360 $this->getFlag( self
::DBO_TRX
) &&
1361 $this->isTransactableQuery( $sql )
1363 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
1364 $this->trxAutomatic
= true;
1369 * Update the estimated run-time of a query, not counting large row lock times
1371 * LoadBalancer can be set to rollback transactions that will create huge replication
1372 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1373 * queries, like inserting a row can take a long time due to row locking. This method
1374 * uses some simple heuristics to discount those cases.
1376 * @param string $sql A SQL write query
1377 * @param float $runtime Total runtime, including RTT
1378 * @param int $affected Affected row count
1380 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1381 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1382 $indicativeOfReplicaRuntime = true;
1383 if ( $runtime > self
::$SLOW_WRITE_SEC ) {
1384 $verb = $this->getQueryVerb( $sql );
1385 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1386 if ( $verb === 'INSERT' ) {
1387 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::$SMALL_WRITE_ROWS;
1388 } elseif ( $verb === 'REPLACE' ) {
1389 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::$SMALL_WRITE_ROWS / 2;
1393 $this->trxWriteDuration +
= $runtime;
1394 $this->trxWriteQueryCount +
= 1;
1395 $this->trxWriteAffectedRows +
= $affected;
1396 if ( $indicativeOfReplicaRuntime ) {
1397 $this->trxWriteAdjDuration +
= $runtime;
1398 $this->trxWriteAdjQueryCount +
= 1;
1403 * Error out if the DB is not in a valid state for a query via query()
1405 * @param string $sql
1406 * @param string $fname
1407 * @throws DBTransactionStateError
1409 private function assertQueryIsCurrentlyAllowed( $sql, $fname ) {
1410 $verb = $this->getQueryVerb( $sql );
1411 if ( $verb === 'USE' ) {
1412 throw new DBUnexpectedError( $this, "Got USE query; use selectDomain() instead" );
1415 if ( $verb === 'ROLLBACK' ) { // transaction/savepoint
1419 if ( $this->trxStatus
< self
::STATUS_TRX_OK
) {
1420 throw new DBTransactionStateError(
1422 "Cannot execute query from $fname while transaction status is ERROR",
1424 $this->trxStatusCause
1426 } elseif ( $this->trxStatus
=== self
::STATUS_TRX_OK
&& $this->trxStatusIgnoredCause
) {
1427 list( $iLastError, $iLastErrno, $iFname ) = $this->trxStatusIgnoredCause
;
1428 call_user_func( $this->deprecationLogger
,
1429 "Caller from $fname ignored an error originally raised from $iFname: " .
1430 "[$iLastErrno] $iLastError"
1432 $this->trxStatusIgnoredCause
= null;
1436 public function assertNoOpenTransactions() {
1437 if ( $this->explicitTrxActive() ) {
1438 throw new DBTransactionError(
1440 "Explicit transaction still active. A caller may have caught an error. "
1441 . "Open transactions: " . $this->flatAtomicSectionList()
1447 * Determine whether it is safe to retry queries after a database connection is lost
1449 * @param string $sql SQL query
1450 * @param bool $priorWritesPending Whether there is a transaction open with
1451 * possible write queries or transaction pre-commit/idle callbacks
1452 * waiting on it to finish.
1453 * @return bool True if it is safe to retry the query, false otherwise
1455 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1456 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1457 # Dropped connections also mean that named locks are automatically released.
1458 # Only allow error suppression in autocommit mode or when the lost transaction
1459 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1460 if ( $this->sessionNamedLocks
) {
1461 return false; // possible critical section violation
1462 } elseif ( $this->sessionTempTables
) {
1463 return false; // tables might be queried latter
1464 } elseif ( $sql === 'COMMIT' ) {
1465 return !$priorWritesPending; // nothing written anyway? (T127428)
1466 } elseif ( $sql === 'ROLLBACK' ) {
1467 return true; // transaction lost...which is also what was requested :)
1468 } elseif ( $this->explicitTrxActive() ) {
1469 return false; // don't drop atomocity and explicit snapshots
1470 } elseif ( $priorWritesPending ) {
1471 return false; // prior writes lost from implicit transaction
1478 * Clean things up after session (and thus transaction) loss before reconnect
1480 private function handleSessionLossPreconnect() {
1481 // Clean up tracking of session-level things...
1482 // https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
1483 // https://www.postgresql.org/docs/9.2/static/sql-createtable.html (ignoring ON COMMIT)
1484 $this->sessionTempTables
= [];
1485 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1486 // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1487 $this->sessionNamedLocks
= [];
1488 // Session loss implies transaction loss
1489 $oldTrxShortId = $this->consumeTrxShortId();
1490 $this->trxAtomicCounter
= 0;
1491 $this->trxIdleCallbacks
= []; // T67263; transaction already lost
1492 $this->trxPreCommitCallbacks
= []; // T67263; transaction already lost
1493 // Clear additional subclass fields
1494 $this->doHandleSessionLossPreconnect();
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 * Reset any additional subclass trx* and session* fields
1510 protected function doHandleSessionLossPreconnect() {
1515 * Clean things up after session (and thus transaction) loss after reconnect
1517 private function handleSessionLossPostconnect() {
1519 // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
1520 // If callback suppression is set then the array will remain unhandled.
1521 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1522 } catch ( Exception
$ex ) {
1523 // Already logged; move on...
1526 // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener()
1527 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1528 } catch ( Exception
$ex ) {
1529 // Already logged; move on...
1534 * Reset the transaction ID and return the old one
1536 * @return string The old transaction ID or the empty string if there wasn't one
1538 private function consumeTrxShortId() {
1539 $old = $this->trxShortId
;
1540 $this->trxShortId
= '';
1546 * Checks whether the cause of the error is detected to be a timeout.
1548 * It returns false by default, and not all engines support detecting this yet.
1549 * If this returns false, it will be treated as a generic query error.
1551 * @param string $error Error text
1552 * @param int $errno Error number
1555 protected function wasQueryTimeout( $error, $errno ) {
1560 * Report a query error. Log the error, and if neither the object ignore
1561 * flag nor the $ignoreErrors flag is set, throw a DBQueryError.
1563 * @param string $error
1565 * @param string $sql
1566 * @param string $fname
1567 * @param bool $ignore
1568 * @throws DBQueryError
1570 public function reportQueryError( $error, $errno, $sql, $fname, $ignore = false ) {
1572 $this->queryLogger
->debug( "SQL ERROR (ignored): $error" );
1574 throw $this->getQueryExceptionAndLog( $error, $errno, $sql, $fname );
1579 * @param string $error
1580 * @param string|int $errno
1581 * @param string $sql
1582 * @param string $fname
1585 private function getQueryExceptionAndLog( $error, $errno, $sql, $fname ) {
1586 $this->queryLogger
->error(
1587 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1588 $this->getLogContext( [
1589 'method' => __METHOD__
,
1592 'sql1line' => mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 ),
1594 'exception' => new RuntimeException()
1598 if ( $this->wasQueryTimeout( $error, $errno ) ) {
1599 $e = new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1600 } elseif ( $this->wasConnectionError( $errno ) ) {
1601 $e = new DBQueryDisconnectedError( $this, $error, $errno, $sql, $fname );
1603 $e = new DBQueryError( $this, $error, $errno, $sql, $fname );
1610 * @param string $error
1611 * @return DBConnectionError
1613 final protected function newExceptionAfterConnectError( $error ) {
1614 // Connection was not fully initialized and is not safe for use
1617 $this->connLogger
->error(
1618 "Error connecting to {db_server} as user {db_user}: {error}",
1619 $this->getLogContext( [
1621 'exception' => new RuntimeException()
1625 return new DBConnectionError( $this, $error );
1628 public function freeResult( $res ) {
1631 public function selectField(
1632 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1634 if ( $var === '*' ) { // sanity
1635 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1638 if ( !is_array( $options ) ) {
1639 $options = [ $options ];
1642 $options['LIMIT'] = 1;
1644 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1645 if ( $res === false ) {
1646 throw new DBUnexpectedError( $this, "Got false from select()" );
1649 $row = $this->fetchRow( $res );
1650 if ( $row === false ) {
1654 return reset( $row );
1657 public function selectFieldValues(
1658 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1660 if ( $var === '*' ) { // sanity
1661 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1662 } elseif ( !is_string( $var ) ) { // sanity
1663 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1666 if ( !is_array( $options ) ) {
1667 $options = [ $options ];
1670 $res = $this->select( $table, [ 'value' => $var ], $cond, $fname, $options, $join_conds );
1671 if ( $res === false ) {
1672 throw new DBUnexpectedError( $this, "Got false from select()" );
1676 foreach ( $res as $row ) {
1677 $values[] = $row->value
;
1684 * Returns an optional USE INDEX clause to go after the table, and a
1685 * string to go at the end of the query.
1687 * @see Database::select()
1689 * @param array $options Associative array of options to be turned into
1690 * an SQL query, valid keys are listed in the function.
1693 protected function makeSelectOptions( array $options ) {
1694 $preLimitTail = $postLimitTail = '';
1699 foreach ( $options as $key => $option ) {
1700 if ( is_numeric( $key ) ) {
1701 $noKeyOptions[$option] = true;
1705 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1707 $preLimitTail .= $this->makeOrderBy( $options );
1709 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1710 $postLimitTail .= ' FOR UPDATE';
1713 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1714 $postLimitTail .= ' LOCK IN SHARE MODE';
1717 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1718 $startOpts .= 'DISTINCT';
1721 # Various MySQL extensions
1722 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1723 $startOpts .= ' /*! STRAIGHT_JOIN */';
1726 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1727 $startOpts .= ' SQL_BIG_RESULT';
1730 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1731 $startOpts .= ' SQL_BUFFER_RESULT';
1734 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1735 $startOpts .= ' SQL_SMALL_RESULT';
1738 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1739 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1742 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1743 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1747 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1748 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1753 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1757 * Returns an optional GROUP BY with an optional HAVING
1759 * @param array $options Associative array of options
1761 * @see Database::select()
1764 protected function makeGroupByWithHaving( $options ) {
1766 if ( isset( $options['GROUP BY'] ) ) {
1767 $gb = is_array( $options['GROUP BY'] )
1768 ?
implode( ',', $options['GROUP BY'] )
1769 : $options['GROUP BY'];
1770 $sql .= ' GROUP BY ' . $gb;
1772 if ( isset( $options['HAVING'] ) ) {
1773 $having = is_array( $options['HAVING'] )
1774 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1775 : $options['HAVING'];
1776 $sql .= ' HAVING ' . $having;
1783 * Returns an optional ORDER BY
1785 * @param array $options Associative array of options
1787 * @see Database::select()
1790 protected function makeOrderBy( $options ) {
1791 if ( isset( $options['ORDER BY'] ) ) {
1792 $ob = is_array( $options['ORDER BY'] )
1793 ?
implode( ',', $options['ORDER BY'] )
1794 : $options['ORDER BY'];
1796 return ' ORDER BY ' . $ob;
1802 public function select(
1803 $table, $vars, $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1805 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1807 return $this->query( $sql, $fname );
1810 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1811 $options = [], $join_conds = []
1813 if ( is_array( $vars ) ) {
1814 $fields = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1819 $options = (array)$options;
1820 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1821 ?
$options['USE INDEX']
1824 isset( $options['IGNORE INDEX'] ) &&
1825 is_array( $options['IGNORE INDEX'] )
1827 ?
$options['IGNORE INDEX']
1831 $this->selectOptionsIncludeLocking( $options ) &&
1832 $this->selectFieldsOrOptionsAggregate( $vars, $options )
1834 // Some DB types (e.g. postgres) disallow FOR UPDATE with aggregate
1835 // functions. Discourage use of such queries to encourage compatibility.
1837 $this->deprecationLogger
,
1838 __METHOD__
. ": aggregation used with a locking SELECT ($fname)"
1842 if ( is_array( $table ) ) {
1844 $this->tableNamesWithIndexClauseOrJOIN(
1845 $table, $useIndexes, $ignoreIndexes, $join_conds );
1846 } elseif ( $table != '' ) {
1848 $this->tableNamesWithIndexClauseOrJOIN(
1849 [ $table ], $useIndexes, $ignoreIndexes, [] );
1854 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1855 $this->makeSelectOptions( $options );
1857 if ( is_array( $conds ) ) {
1858 $conds = $this->makeList( $conds, self
::LIST_AND
);
1861 if ( $conds === null ||
$conds === false ) {
1862 $this->queryLogger
->warning(
1866 . ' with incorrect parameters: $conds must be a string or an array'
1871 if ( $conds === '' ||
$conds === '*' ) {
1872 $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex $preLimitTail";
1873 } elseif ( is_string( $conds ) ) {
1874 $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex " .
1875 "WHERE $conds $preLimitTail";
1877 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1880 if ( isset( $options['LIMIT'] ) ) {
1881 $sql = $this->limitResult( $sql, $options['LIMIT'],
1882 $options['OFFSET'] ??
false );
1884 $sql = "$sql $postLimitTail";
1886 if ( isset( $options['EXPLAIN'] ) ) {
1887 $sql = 'EXPLAIN ' . $sql;
1893 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1894 $options = [], $join_conds = []
1896 $options = (array)$options;
1897 $options['LIMIT'] = 1;
1899 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1900 if ( $res === false ) {
1901 throw new DBUnexpectedError( $this, "Got false from select()" );
1904 if ( !$this->numRows( $res ) ) {
1908 return $this->fetchObject( $res );
1911 public function estimateRowCount(
1912 $table, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1914 $conds = $this->normalizeConditions( $conds, $fname );
1915 $column = $this->extractSingleFieldFromList( $var );
1916 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1917 $conds[] = "$column IS NOT NULL";
1920 $res = $this->select(
1921 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1923 $row = $res ?
$this->fetchRow( $res ) : [];
1925 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1928 public function selectRowCount(
1929 $tables, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1931 $conds = $this->normalizeConditions( $conds, $fname );
1932 $column = $this->extractSingleFieldFromList( $var );
1933 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1934 $conds[] = "$column IS NOT NULL";
1937 $res = $this->select(
1939 'tmp_count' => $this->buildSelectSubquery(
1948 [ 'rowcount' => 'COUNT(*)' ],
1952 $row = $res ?
$this->fetchRow( $res ) : [];
1954 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1958 * @param string|array $options
1961 private function selectOptionsIncludeLocking( $options ) {
1962 $options = (array)$options;
1963 foreach ( [ 'FOR UPDATE', 'LOCK IN SHARE MODE' ] as $lock ) {
1964 if ( in_array( $lock, $options, true ) ) {
1973 * @param array|string $fields
1974 * @param array|string $options
1977 private function selectFieldsOrOptionsAggregate( $fields, $options ) {
1978 foreach ( (array)$options as $key => $value ) {
1979 if ( is_string( $key ) ) {
1980 if ( preg_match( '/^(?:GROUP BY|HAVING)$/i', $key ) ) {
1983 } elseif ( is_string( $value ) ) {
1984 if ( preg_match( '/^(?:DISTINCT|DISTINCTROW)$/i', $value ) ) {
1990 $regex = '/^(?:COUNT|MIN|MAX|SUM|GROUP_CONCAT|LISTAGG|ARRAY_AGG)\s*\\(/i';
1991 foreach ( (array)$fields as $field ) {
1992 if ( is_string( $field ) && preg_match( $regex, $field ) ) {
2001 * @param array|string $conds
2002 * @param string $fname
2005 final protected function normalizeConditions( $conds, $fname ) {
2006 if ( $conds === null ||
$conds === false ) {
2007 $this->queryLogger
->warning(
2011 . ' with incorrect parameters: $conds must be a string or an array'
2016 if ( !is_array( $conds ) ) {
2017 $conds = ( $conds === '' ) ?
[] : [ $conds ];
2024 * @param array|string $var Field parameter in the style of select()
2025 * @return string|null Column name or null; ignores aliases
2026 * @throws DBUnexpectedError Errors out if multiple columns are given
2028 final protected function extractSingleFieldFromList( $var ) {
2029 if ( is_array( $var ) ) {
2032 } elseif ( count( $var ) == 1 ) {
2033 $column = $var[0] ??
reset( $var );
2035 throw new DBUnexpectedError( $this, __METHOD__
. ': got multiple columns' );
2044 public function lockForUpdate(
2045 $table, $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
2047 if ( !$this->trxLevel() && !$this->getFlag( self
::DBO_TRX
) ) {
2048 throw new DBUnexpectedError(
2050 __METHOD__
. ': no transaction is active nor is DBO_TRX set'
2054 $options = (array)$options;
2055 $options[] = 'FOR UPDATE';
2057 return $this->selectRowCount( $table, '*', $conds, $fname, $options, $join_conds );
2060 public function fieldExists( $table, $field, $fname = __METHOD__
) {
2061 $info = $this->fieldInfo( $table, $field );
2066 public function indexExists( $table, $index, $fname = __METHOD__
) {
2067 if ( !$this->tableExists( $table ) ) {
2071 $info = $this->indexInfo( $table, $index, $fname );
2072 if ( is_null( $info ) ) {
2075 return $info !== false;
2079 abstract public function tableExists( $table, $fname = __METHOD__
);
2081 public function indexUnique( $table, $index ) {
2082 $indexInfo = $this->indexInfo( $table, $index );
2084 if ( !$indexInfo ) {
2088 return !$indexInfo[0]->Non_unique
;
2092 * Helper for Database::insert().
2094 * @param array $options
2097 protected function makeInsertOptions( $options ) {
2098 return implode( ' ', $options );
2101 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
2102 # No rows to insert, easy just return now
2103 if ( !count( $a ) ) {
2107 $table = $this->tableName( $table );
2109 if ( !is_array( $options ) ) {
2110 $options = [ $options ];
2113 $options = $this->makeInsertOptions( $options );
2115 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
2117 $keys = array_keys( $a[0] );
2120 $keys = array_keys( $a );
2123 $sql = 'INSERT ' . $options .
2124 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
2128 foreach ( $a as $row ) {
2134 $sql .= '(' . $this->makeList( $row ) . ')';
2137 $sql .= '(' . $this->makeList( $a ) . ')';
2140 $this->query( $sql, $fname );
2146 * Make UPDATE options array for Database::makeUpdateOptions
2148 * @param array $options
2151 protected function makeUpdateOptionsArray( $options ) {
2152 if ( !is_array( $options ) ) {
2153 $options = [ $options ];
2158 if ( in_array( 'IGNORE', $options ) ) {
2166 * Make UPDATE options for the Database::update function
2168 * @param array $options The options passed to Database::update
2171 protected function makeUpdateOptions( $options ) {
2172 $opts = $this->makeUpdateOptionsArray( $options );
2174 return implode( ' ', $opts );
2177 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
2178 $table = $this->tableName( $table );
2179 $opts = $this->makeUpdateOptions( $options );
2180 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
2182 if ( $conds !== [] && $conds !== '*' ) {
2183 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
2186 $this->query( $sql, $fname );
2191 public function makeList( $a, $mode = self
::LIST_COMMA
) {
2192 if ( !is_array( $a ) ) {
2193 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
2199 foreach ( $a as $field => $value ) {
2201 if ( $mode == self
::LIST_AND
) {
2203 } elseif ( $mode == self
::LIST_OR
) {
2212 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
2213 $list .= "($value)";
2214 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
2217 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
2219 // Remove null from array to be handled separately if found
2220 $includeNull = false;
2221 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2222 $includeNull = true;
2223 unset( $value[$nullKey] );
2225 if ( count( $value ) == 0 && !$includeNull ) {
2226 throw new InvalidArgumentException(
2227 __METHOD__
. ": empty input for field $field" );
2228 } elseif ( count( $value ) == 0 ) {
2229 // only check if $field is null
2230 $list .= "$field IS NULL";
2232 // IN clause contains at least one valid element
2233 if ( $includeNull ) {
2234 // Group subconditions to ensure correct precedence
2237 if ( count( $value ) == 1 ) {
2238 // Special-case single values, as IN isn't terribly efficient
2239 // Don't necessarily assume the single key is 0; we don't
2240 // enforce linear numeric ordering on other arrays here.
2241 $value = array_values( $value )[0];
2242 $list .= $field . " = " . $this->addQuotes( $value );
2244 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2246 // if null present in array, append IS NULL
2247 if ( $includeNull ) {
2248 $list .= " OR $field IS NULL)";
2251 } elseif ( $value === null ) {
2252 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
2253 $list .= "$field IS ";
2254 } elseif ( $mode == self
::LIST_SET
) {
2255 $list .= "$field = ";
2260 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
2262 $list .= "$field = ";
2264 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
2271 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2274 foreach ( $data as $base => $sub ) {
2275 if ( count( $sub ) ) {
2276 $conds[] = $this->makeList(
2277 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
2283 return $this->makeList( $conds, self
::LIST_OR
);
2285 // Nothing to search for...
2290 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2294 public function bitNot( $field ) {
2298 public function bitAnd( $fieldLeft, $fieldRight ) {
2299 return "($fieldLeft & $fieldRight)";
2302 public function bitOr( $fieldLeft, $fieldRight ) {
2303 return "($fieldLeft | $fieldRight)";
2306 public function buildConcat( $stringList ) {
2307 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2310 public function buildGroupConcatField(
2311 $delim, $table, $field, $conds = '', $join_conds = []
2313 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2315 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
2318 public function buildSubstring( $input, $startPosition, $length = null ) {
2319 $this->assertBuildSubstringParams( $startPosition, $length );
2320 $functionBody = "$input FROM $startPosition";
2321 if ( $length !== null ) {
2322 $functionBody .= " FOR $length";
2324 return 'SUBSTRING(' . $functionBody . ')';
2328 * Check type and bounds for parameters to self::buildSubstring()
2330 * All supported databases have substring functions that behave the same for
2331 * positive $startPosition and non-negative $length, but behaviors differ when
2332 * given 0 or negative $startPosition or negative $length. The simplest
2333 * solution to that is to just forbid those values.
2335 * @param int $startPosition
2336 * @param int|null $length
2339 protected function assertBuildSubstringParams( $startPosition, $length ) {
2340 if ( !is_int( $startPosition ) ||
$startPosition <= 0 ) {
2341 throw new InvalidArgumentException(
2342 '$startPosition must be a positive integer'
2345 if ( !( is_int( $length ) && $length >= 0 ||
$length === null ) ) {
2346 throw new InvalidArgumentException(
2347 '$length must be null or an integer greater than or equal to 0'
2352 public function buildStringCast( $field ) {
2353 // In theory this should work for any standards-compliant
2354 // SQL implementation, although it may not be the best way to do it.
2355 return "CAST( $field AS CHARACTER )";
2358 public function buildIntegerCast( $field ) {
2359 return 'CAST( ' . $field . ' AS INTEGER )';
2362 public function buildSelectSubquery(
2363 $table, $vars, $conds = '', $fname = __METHOD__
,
2364 $options = [], $join_conds = []
2366 return new Subquery(
2367 $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2371 public function databasesAreIndependent() {
2375 final public function selectDB( $db ) {
2376 $this->selectDomain( new DatabaseDomain(
2378 $this->currentDomain
->getSchema(),
2379 $this->currentDomain
->getTablePrefix()
2385 final public function selectDomain( $domain ) {
2386 $this->doSelectDomain( DatabaseDomain
::newFromId( $domain ) );
2390 * @param DatabaseDomain $domain
2391 * @throws DBConnectionError
2395 protected function doSelectDomain( DatabaseDomain
$domain ) {
2396 $this->currentDomain
= $domain;
2399 public function getDBname() {
2400 return $this->currentDomain
->getDatabase();
2403 public function getServer() {
2404 return $this->server
;
2407 public function tableName( $name, $format = 'quoted' ) {
2408 if ( $name instanceof Subquery
) {
2409 throw new DBUnexpectedError(
2411 __METHOD__
. ': got Subquery instance when expecting a string'
2415 # Skip the entire process when we have a string quoted on both ends.
2416 # Note that we check the end so that we will still quote any use of
2417 # use of `database`.table. But won't break things if someone wants
2418 # to query a database table with a dot in the name.
2419 if ( $this->isQuotedIdentifier( $name ) ) {
2423 # Lets test for any bits of text that should never show up in a table
2424 # name. Basically anything like JOIN or ON which are actually part of
2425 # SQL queries, but may end up inside of the table value to combine
2426 # sql. Such as how the API is doing.
2427 # Note that we use a whitespace test rather than a \b test to avoid
2428 # any remote case where a word like on may be inside of a table name
2429 # surrounded by symbols which may be considered word breaks.
2430 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2431 $this->queryLogger
->warning(
2432 __METHOD__
. ": use of subqueries is not supported this way",
2433 [ 'exception' => new RuntimeException() ]
2439 # Split database and table into proper variables.
2440 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2442 # Quote $table and apply the prefix if not quoted.
2443 # $tableName might be empty if this is called from Database::replaceVars()
2444 $tableName = "{$prefix}{$table}";
2445 if ( $format === 'quoted'
2446 && !$this->isQuotedIdentifier( $tableName )
2447 && $tableName !== ''
2449 $tableName = $this->addIdentifierQuotes( $tableName );
2452 # Quote $schema and $database and merge them with the table name if needed
2453 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2454 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2460 * Get the table components needed for a query given the currently selected database
2462 * @param string $name Table name in the form of db.schema.table, db.table, or table
2463 * @return array (DB name or "" for default, schema name, table prefix, table name)
2465 protected function qualifiedTableComponents( $name ) {
2466 # We reverse the explode so that database.table and table both output the correct table.
2467 $dbDetails = explode( '.', $name, 3 );
2468 if ( count( $dbDetails ) == 3 ) {
2469 list( $database, $schema, $table ) = $dbDetails;
2470 # We don't want any prefix added in this case
2472 } elseif ( count( $dbDetails ) == 2 ) {
2473 list( $database, $table ) = $dbDetails;
2474 # We don't want any prefix added in this case
2476 # In dbs that support it, $database may actually be the schema
2477 # but that doesn't affect any of the functionality here
2480 list( $table ) = $dbDetails;
2481 if ( isset( $this->tableAliases
[$table] ) ) {
2482 $database = $this->tableAliases
[$table]['dbname'];
2483 $schema = is_string( $this->tableAliases
[$table]['schema'] )
2484 ?
$this->tableAliases
[$table]['schema']
2485 : $this->relationSchemaQualifier();
2486 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
2487 ?
$this->tableAliases
[$table]['prefix']
2488 : $this->tablePrefix();
2491 $schema = $this->relationSchemaQualifier(); # Default schema
2492 $prefix = $this->tablePrefix(); # Default prefix
2496 return [ $database, $schema, $prefix, $table ];
2500 * @param string|null $namespace Database or schema
2501 * @param string $relation Name of table, view, sequence, etc...
2502 * @param string $format One of (raw, quoted)
2503 * @return string Relation name with quoted and merged $namespace as needed
2505 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2506 if ( strlen( $namespace ) ) {
2507 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2508 $namespace = $this->addIdentifierQuotes( $namespace );
2510 $relation = $namespace . '.' . $relation;
2516 public function tableNames() {
2517 $inArray = func_get_args();
2520 foreach ( $inArray as $name ) {
2521 $retVal[$name] = $this->tableName( $name );
2527 public function tableNamesN() {
2528 $inArray = func_get_args();
2531 foreach ( $inArray as $name ) {
2532 $retVal[] = $this->tableName( $name );
2539 * Get an aliased table name
2541 * This returns strings like "tableName AS newTableName" for aliased tables
2542 * and "(SELECT * from tableA) newTablename" for subqueries (e.g. derived tables)
2544 * @see Database::tableName()
2545 * @param string|Subquery $table Table name or object with a 'sql' field
2546 * @param string|bool $alias Table alias (optional)
2547 * @return string SQL name for aliased table. Will not alias a table to its own name
2549 protected function tableNameWithAlias( $table, $alias = false ) {
2550 if ( is_string( $table ) ) {
2551 $quotedTable = $this->tableName( $table );
2552 } elseif ( $table instanceof Subquery
) {
2553 $quotedTable = (string)$table;
2555 throw new InvalidArgumentException( "Table must be a string or Subquery" );
2558 if ( $alias === false ||
$alias === $table ) {
2559 if ( $table instanceof Subquery
) {
2560 throw new InvalidArgumentException( "Subquery table missing alias" );
2563 return $quotedTable;
2565 return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2570 * Gets an array of aliased table names
2572 * @param array $tables [ [alias] => table ]
2573 * @return string[] See tableNameWithAlias()
2575 protected function tableNamesWithAlias( $tables ) {
2577 foreach ( $tables as $alias => $table ) {
2578 if ( is_numeric( $alias ) ) {
2581 $retval[] = $this->tableNameWithAlias( $table, $alias );
2588 * Get an aliased field name
2589 * e.g. fieldName AS newFieldName
2591 * @param string $name Field name
2592 * @param string|bool $alias Alias (optional)
2593 * @return string SQL name for aliased field. Will not alias a field to its own name
2595 protected function fieldNameWithAlias( $name, $alias = false ) {
2596 if ( !$alias ||
(string)$alias === (string)$name ) {
2599 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2604 * Gets an array of aliased field names
2606 * @param array $fields [ [alias] => field ]
2607 * @return string[] See fieldNameWithAlias()
2609 protected function fieldNamesWithAlias( $fields ) {
2611 foreach ( $fields as $alias => $field ) {
2612 if ( is_numeric( $alias ) ) {
2615 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2622 * Get the aliased table name clause for a FROM clause
2623 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2625 * @param array $tables ( [alias] => table )
2626 * @param array $use_index Same as for select()
2627 * @param array $ignore_index Same as for select()
2628 * @param array $join_conds Same as for select()
2631 protected function tableNamesWithIndexClauseOrJOIN(
2632 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2636 $use_index = (array)$use_index;
2637 $ignore_index = (array)$ignore_index;
2638 $join_conds = (array)$join_conds;
2640 foreach ( $tables as $alias => $table ) {
2641 if ( !is_string( $alias ) ) {
2642 // No alias? Set it equal to the table name
2646 if ( is_array( $table ) ) {
2647 // A parenthesized group
2648 if ( count( $table ) > 1 ) {
2649 $joinedTable = '(' .
2650 $this->tableNamesWithIndexClauseOrJOIN(
2651 $table, $use_index, $ignore_index, $join_conds ) . ')';
2654 $innerTable = reset( $table );
2655 $innerAlias = key( $table );
2656 $joinedTable = $this->tableNameWithAlias(
2658 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2662 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2665 // Is there a JOIN clause for this table?
2666 if ( isset( $join_conds[$alias] ) ) {
2667 list( $joinType, $conds ) = $join_conds[$alias];
2668 $tableClause = $joinType;
2669 $tableClause .= ' ' . $joinedTable;
2670 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2671 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2673 $tableClause .= ' ' . $use;
2676 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2677 $ignore = $this->ignoreIndexClause(
2678 implode( ',', (array)$ignore_index[$alias] ) );
2679 if ( $ignore != '' ) {
2680 $tableClause .= ' ' . $ignore;
2683 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2685 $tableClause .= ' ON (' . $on . ')';
2688 $retJOIN[] = $tableClause;
2689 } elseif ( isset( $use_index[$alias] ) ) {
2690 // Is there an INDEX clause for this table?
2691 $tableClause = $joinedTable;
2692 $tableClause .= ' ' . $this->useIndexClause(
2693 implode( ',', (array)$use_index[$alias] )
2696 $ret[] = $tableClause;
2697 } elseif ( isset( $ignore_index[$alias] ) ) {
2698 // Is there an INDEX clause for this table?
2699 $tableClause = $joinedTable;
2700 $tableClause .= ' ' . $this->ignoreIndexClause(
2701 implode( ',', (array)$ignore_index[$alias] )
2704 $ret[] = $tableClause;
2706 $tableClause = $joinedTable;
2708 $ret[] = $tableClause;
2712 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2713 $implicitJoins = implode( ',', $ret );
2714 $explicitJoins = implode( ' ', $retJOIN );
2716 // Compile our final table clause
2717 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2721 * Allows for index remapping in queries where this is not consistent across DBMS
2723 * @param string $index
2726 protected function indexName( $index ) {
2727 return $this->indexAliases
[$index] ??
$index;
2730 public function addQuotes( $s ) {
2731 if ( $s instanceof Blob
) {
2734 if ( $s === null ) {
2736 } elseif ( is_bool( $s ) ) {
2739 # This will also quote numeric values. This should be harmless,
2740 # and protects against weird problems that occur when they really
2741 # _are_ strings such as article titles and string->number->string
2742 # conversion is not 1:1.
2743 return "'" . $this->strencode( $s ) . "'";
2747 public function addIdentifierQuotes( $s ) {
2748 return '"' . str_replace( '"', '""', $s ) . '"';
2752 * Returns if the given identifier looks quoted or not according to
2753 * the database convention for quoting identifiers .
2755 * @note Do not use this to determine if untrusted input is safe.
2756 * A malicious user can trick this function.
2757 * @param string $name
2760 public function isQuotedIdentifier( $name ) {
2761 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2766 * @param string $escapeChar
2769 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2770 return str_replace( [ $escapeChar, '%', '_' ],
2771 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2775 public function buildLike( $param, ...$params ) {
2776 if ( is_array( $param ) ) {
2779 $params = func_get_args();
2784 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2785 // may escape backslashes, creating problems of double escaping. The `
2786 // character has good cross-DBMS compatibility, avoiding special operators
2787 // in MS SQL like ^ and %
2790 foreach ( $params as $value ) {
2791 if ( $value instanceof LikeMatch
) {
2792 $s .= $value->toString();
2794 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2799 $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2802 public function anyChar() {
2803 return new LikeMatch( '_' );
2806 public function anyString() {
2807 return new LikeMatch( '%' );
2810 public function nextSequenceValue( $seqName ) {
2815 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2816 * is only needed because a) MySQL must be as efficient as possible due to
2817 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2818 * which index to pick. Anyway, other databases might have different
2819 * indexes on a given table. So don't bother overriding this unless you're
2821 * @param string $index
2824 public function useIndexClause( $index ) {
2829 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2830 * is only needed because a) MySQL must be as efficient as possible due to
2831 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2832 * which index to pick. Anyway, other databases might have different
2833 * indexes on a given table. So don't bother overriding this unless you're
2835 * @param string $index
2838 public function ignoreIndexClause( $index ) {
2842 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2843 if ( count( $rows ) == 0 ) {
2847 $uniqueIndexes = (array)$uniqueIndexes;
2849 if ( !is_array( reset( $rows ) ) ) {
2854 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2855 $affectedRowCount = 0;
2856 foreach ( $rows as $row ) {
2857 // Delete rows which collide with this one
2858 $indexWhereClauses = [];
2859 foreach ( $uniqueIndexes as $index ) {
2860 $indexColumns = (array)$index;
2861 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2862 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2863 throw new DBUnexpectedError(
2865 'New record does not provide all values for unique key (' .
2866 implode( ', ', $indexColumns ) . ')'
2868 } elseif ( in_array( null, $indexRowValues, true ) ) {
2869 throw new DBUnexpectedError(
2871 'New record has a null value for unique key (' .
2872 implode( ', ', $indexColumns ) . ')'
2875 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2878 if ( $indexWhereClauses ) {
2879 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2880 $affectedRowCount +
= $this->affectedRows();
2883 // Now insert the row
2884 $this->insert( $table, $row, $fname );
2885 $affectedRowCount +
= $this->affectedRows();
2887 $this->endAtomic( $fname );
2888 $this->affectedRowCount
= $affectedRowCount;
2889 } catch ( Exception
$e ) {
2890 $this->cancelAtomic( $fname );
2896 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2899 * @param string $table Table name
2900 * @param array|string $rows Row(s) to insert
2901 * @param string $fname Caller function name
2903 protected function nativeReplace( $table, $rows, $fname ) {
2904 $table = $this->tableName( $table );
2907 if ( !is_array( reset( $rows ) ) ) {
2911 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2914 foreach ( $rows as $row ) {
2921 $sql .= '(' . $this->makeList( $row ) . ')';
2924 $this->query( $sql, $fname );
2927 public function upsert( $table, array $rows, $uniqueIndexes, array $set,
2930 if ( $rows === [] ) {
2931 return true; // nothing to do
2934 $uniqueIndexes = (array)$uniqueIndexes;
2935 if ( !is_array( reset( $rows ) ) ) {
2939 if ( count( $uniqueIndexes ) ) {
2940 $clauses = []; // list WHERE clauses that each identify a single row
2941 foreach ( $rows as $row ) {
2942 foreach ( $uniqueIndexes as $index ) {
2943 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2944 $rowKey = []; // unique key to this row
2945 foreach ( $index as $column ) {
2946 $rowKey[$column] = $row[$column];
2948 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2951 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2956 $affectedRowCount = 0;
2958 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2959 # Update any existing conflicting row(s)
2960 if ( $where !== false ) {
2961 $this->update( $table, $set, $where, $fname );
2962 $affectedRowCount +
= $this->affectedRows();
2964 # Now insert any non-conflicting row(s)
2965 $this->insert( $table, $rows, $fname, [ 'IGNORE' ] );
2966 $affectedRowCount +
= $this->affectedRows();
2967 $this->endAtomic( $fname );
2968 $this->affectedRowCount
= $affectedRowCount;
2969 } catch ( Exception
$e ) {
2970 $this->cancelAtomic( $fname );
2977 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2981 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2984 $delTable = $this->tableName( $delTable );
2985 $joinTable = $this->tableName( $joinTable );
2986 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2987 if ( $conds != '*' ) {
2988 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2992 $this->query( $sql, $fname );
2995 public function textFieldSize( $table, $field ) {
2996 $table = $this->tableName( $table );
2997 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\"";
2998 $res = $this->query( $sql, __METHOD__
);
2999 $row = $this->fetchObject( $res );
3003 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
3012 public function delete( $table, $conds, $fname = __METHOD__
) {
3014 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
3017 $table = $this->tableName( $table );
3018 $sql = "DELETE FROM $table";
3020 if ( $conds != '*' ) {
3021 if ( is_array( $conds ) ) {
3022 $conds = $this->makeList( $conds, self
::LIST_AND
);
3024 $sql .= ' WHERE ' . $conds;
3027 $this->query( $sql, $fname );
3032 final public function insertSelect(
3033 $destTable, $srcTable, $varMap, $conds,
3034 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3036 static $hints = [ 'NO_AUTO_COLUMNS' ];
3038 $insertOptions = (array)$insertOptions;
3039 $selectOptions = (array)$selectOptions;
3041 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
3042 // For massive migrations with downtime, we don't want to select everything
3043 // into memory and OOM, so do all this native on the server side if possible.
3044 $this->nativeInsertSelect(
3050 array_diff( $insertOptions, $hints ),
3055 $this->nonNativeInsertSelect(
3061 array_diff( $insertOptions, $hints ),
3071 * @param array $insertOptions INSERT options
3072 * @param array $selectOptions SELECT options
3073 * @return bool Whether an INSERT SELECT with these options will be replication safe
3076 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
3081 * Implementation of insertSelect() based on select() and insert()
3083 * @see IDatabase::insertSelect()
3085 * @param string $destTable
3086 * @param string|array $srcTable
3087 * @param array $varMap
3088 * @param array $conds
3089 * @param string $fname
3090 * @param array $insertOptions
3091 * @param array $selectOptions
3092 * @param array $selectJoinConds
3094 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3095 $fname = __METHOD__
,
3096 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3098 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
3099 // on only the master (without needing row-based-replication). It also makes it easy to
3100 // know how big the INSERT is going to be.
3102 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
3103 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
3105 $selectOptions[] = 'FOR UPDATE';
3106 $res = $this->select(
3107 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
3114 $affectedRowCount = 0;
3115 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
3118 foreach ( $res as $row ) {
3119 $rows[] = (array)$row;
3121 // Avoid inserts that are too huge
3122 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
3123 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
3127 $affectedRowCount +
= $this->affectedRows();
3131 if ( $rows && $ok ) {
3132 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
3134 $affectedRowCount +
= $this->affectedRows();
3138 $this->endAtomic( $fname );
3139 $this->affectedRowCount
= $affectedRowCount;
3141 $this->cancelAtomic( $fname );
3143 } catch ( Exception
$e ) {
3144 $this->cancelAtomic( $fname );
3150 * Native server-side implementation of insertSelect() for situations where
3151 * we don't want to select everything into memory
3153 * @see IDatabase::insertSelect()
3154 * @param string $destTable
3155 * @param string|array $srcTable
3156 * @param array $varMap
3157 * @param array $conds
3158 * @param string $fname
3159 * @param array $insertOptions
3160 * @param array $selectOptions
3161 * @param array $selectJoinConds
3163 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3164 $fname = __METHOD__
,
3165 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3167 $destTable = $this->tableName( $destTable );
3169 if ( !is_array( $insertOptions ) ) {
3170 $insertOptions = [ $insertOptions ];
3173 $insertOptions = $this->makeInsertOptions( $insertOptions );
3175 $selectSql = $this->selectSQLText(
3177 array_values( $varMap ),
3184 $sql = "INSERT $insertOptions" .
3185 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
3188 $this->query( $sql, $fname );
3191 public function limitResult( $sql, $limit, $offset = false ) {
3192 if ( !is_numeric( $limit ) ) {
3193 throw new DBUnexpectedError(
3195 "Invalid non-numeric limit passed to " . __METHOD__
3198 // This version works in MySQL and SQLite. It will very likely need to be
3199 // overridden for most other RDBMS subclasses.
3200 return "$sql LIMIT "
3201 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3205 public function unionSupportsOrderAndLimit() {
3206 return true; // True for almost every DB supported
3209 public function unionQueries( $sqls, $all ) {
3210 $glue = $all ?
') UNION ALL (' : ') UNION (';
3212 return '(' . implode( $glue, $sqls ) . ')';
3215 public function unionConditionPermutations(
3216 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
3217 $options = [], $join_conds = []
3219 // First, build the Cartesian product of $permute_conds
3221 foreach ( $permute_conds as $field => $values ) {
3223 // Skip empty $values
3226 $values = array_unique( $values ); // For sanity
3228 foreach ( $conds as $cond ) {
3229 foreach ( $values as $value ) {
3230 $cond[$field] = $value;
3231 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
3237 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
3239 // If there's just one condition and no subordering, hand off to
3240 // selectSQLText directly.
3241 if ( count( $conds ) === 1 &&
3242 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
3244 return $this->selectSQLText(
3245 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
3249 // Otherwise, we need to pull out the order and limit to apply after
3250 // the union. Then build the SQL queries for each set of conditions in
3251 // $conds. Then union them together (using UNION ALL, because the
3252 // product *should* already be distinct).
3253 $orderBy = $this->makeOrderBy( $options );
3254 $limit = $options['LIMIT'] ??
null;
3255 $offset = $options['OFFSET'] ??
false;
3256 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
3257 if ( !$this->unionSupportsOrderAndLimit() ) {
3258 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
3260 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
3261 $options['ORDER BY'] = $options['INNER ORDER BY'];
3263 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
3264 // We need to increase the limit by the offset rather than
3265 // using the offset directly, otherwise it'll skip incorrectly
3266 // in the subqueries.
3267 $options['LIMIT'] = $limit +
$offset;
3268 unset( $options['OFFSET'] );
3273 foreach ( $conds as $cond ) {
3274 $sqls[] = $this->selectSQLText(
3275 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
3278 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
3279 if ( $limit !== null ) {
3280 $sql = $this->limitResult( $sql, $limit, $offset );
3286 public function conditional( $cond, $trueVal, $falseVal ) {
3287 if ( is_array( $cond ) ) {
3288 $cond = $this->makeList( $cond, self
::LIST_AND
);
3291 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3294 public function strreplace( $orig, $old, $new ) {
3295 return "REPLACE({$orig}, {$old}, {$new})";
3298 public function getServerUptime() {
3302 public function wasDeadlock() {
3306 public function wasLockTimeout() {
3310 public function wasConnectionLoss() {
3311 return $this->wasConnectionError( $this->lastErrno() );
3314 public function wasReadOnlyError() {
3318 public function wasErrorReissuable() {
3320 $this->wasDeadlock() ||
3321 $this->wasLockTimeout() ||
3322 $this->wasConnectionLoss()
3327 * Do not use this method outside of Database/DBError classes
3329 * @param int|string $errno
3330 * @return bool Whether the given query error was a connection drop
3332 public function wasConnectionError( $errno ) {
3337 * @return bool Whether it is known that the last query error only caused statement rollback
3338 * @note This is for backwards compatibility for callers catching DBError exceptions in
3339 * order to ignore problems like duplicate key errors or foriegn key violations
3342 protected function wasKnownStatementRollbackError() {
3343 return false; // don't know; it could have caused a transaction rollback
3346 public function deadlockLoop() {
3347 $args = func_get_args();
3348 $function = array_shift( $args );
3349 $tries = self
::$DEADLOCK_TRIES;
3351 $this->begin( __METHOD__
);
3354 /** @var Exception $e */
3358 $retVal = $function( ...$args );
3360 } catch ( DBQueryError
$e ) {
3361 if ( $this->wasDeadlock() ) {
3362 // Retry after a randomized delay
3363 usleep( mt_rand( self
::$DEADLOCK_DELAY_MIN, self
::$DEADLOCK_DELAY_MAX ) );
3365 // Throw the error back up
3369 } while ( --$tries > 0 );
3371 if ( $tries <= 0 ) {
3372 // Too many deadlocks; give up
3373 $this->rollback( __METHOD__
);
3376 $this->commit( __METHOD__
);
3382 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3383 # Real waits are implemented in the subclass.
3387 public function getReplicaPos() {
3392 public function getMasterPos() {
3397 public function serverIsReadOnly() {
3401 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
3402 if ( !$this->trxLevel() ) {
3403 throw new DBUnexpectedError( $this, "No transaction is active" );
3405 $this->trxEndCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3408 final public function onTransactionCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3409 if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
3410 // Start an implicit transaction similar to how query() does
3411 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3412 $this->trxAutomatic
= true;
3415 $this->trxIdleCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3416 if ( !$this->trxLevel() ) {
3417 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
3421 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
3422 $this->onTransactionCommitOrIdle( $callback, $fname );
3425 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3426 if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
3427 // Start an implicit transaction similar to how query() does
3428 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3429 $this->trxAutomatic
= true;
3432 if ( $this->trxLevel() ) {
3433 $this->trxPreCommitCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3435 // No transaction is active nor will start implicitly, so make one for this callback
3436 $this->startAtomic( __METHOD__
, self
::ATOMIC_CANCELABLE
);
3439 $this->endAtomic( __METHOD__
);
3440 } catch ( Exception
$e ) {
3441 $this->cancelAtomic( __METHOD__
);
3447 final public function onAtomicSectionCancel( callable
$callback, $fname = __METHOD__
) {
3448 if ( !$this->trxLevel() ||
!$this->trxAtomicLevels
) {
3449 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3451 $this->trxSectionCancelCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3455 * @return AtomicSectionIdentifier|null ID of the topmost atomic section level
3457 private function currentAtomicSectionId() {
3458 if ( $this->trxLevel() && $this->trxAtomicLevels
) {
3459 $levelInfo = end( $this->trxAtomicLevels
);
3461 return $levelInfo[1];
3468 * Hoist callback ownership for callbacks in a section to a parent section.
3469 * All callbacks should have an owner that is present in trxAtomicLevels.
3470 * @param AtomicSectionIdentifier $old
3471 * @param AtomicSectionIdentifier $new
3473 private function reassignCallbacksForSection(
3474 AtomicSectionIdentifier
$old, AtomicSectionIdentifier
$new
3476 foreach ( $this->trxPreCommitCallbacks
as $key => $info ) {
3477 if ( $info[2] === $old ) {
3478 $this->trxPreCommitCallbacks
[$key][2] = $new;
3481 foreach ( $this->trxIdleCallbacks
as $key => $info ) {
3482 if ( $info[2] === $old ) {
3483 $this->trxIdleCallbacks
[$key][2] = $new;
3486 foreach ( $this->trxEndCallbacks
as $key => $info ) {
3487 if ( $info[2] === $old ) {
3488 $this->trxEndCallbacks
[$key][2] = $new;
3491 foreach ( $this->trxSectionCancelCallbacks
as $key => $info ) {
3492 if ( $info[2] === $old ) {
3493 $this->trxSectionCancelCallbacks
[$key][2] = $new;
3499 * Update callbacks that were owned by cancelled atomic sections.
3501 * Callbacks for "on commit" should never be run if they're owned by a
3502 * section that won't be committed.
3504 * Callbacks for "on resolution" need to reflect that the section was
3505 * rolled back, even if the transaction as a whole commits successfully.
3507 * Callbacks for "on section cancel" should already have been consumed,
3508 * but errors during the cancellation itself can prevent that while still
3509 * destroying the section. Hoist any such callbacks to the new top section,
3510 * which we assume will itself have to be cancelled or rolled back to
3511 * resolve the error.
3513 * @param AtomicSectionIdentifier[] $sectionIds ID of an actual savepoint
3514 * @param AtomicSectionIdentifier|null $newSectionId New top section ID.
3515 * @throws UnexpectedValueException
3517 private function modifyCallbacksForCancel(
3518 array $sectionIds, AtomicSectionIdentifier
$newSectionId = null
3520 // Cancel the "on commit" callbacks owned by this savepoint
3521 $this->trxIdleCallbacks
= array_filter(
3522 $this->trxIdleCallbacks
,
3523 function ( $entry ) use ( $sectionIds ) {
3524 return !in_array( $entry[2], $sectionIds, true );
3527 $this->trxPreCommitCallbacks
= array_filter(
3528 $this->trxPreCommitCallbacks
,
3529 function ( $entry ) use ( $sectionIds ) {
3530 return !in_array( $entry[2], $sectionIds, true );
3533 // Make "on resolution" callbacks owned by this savepoint to perceive a rollback
3534 foreach ( $this->trxEndCallbacks
as $key => $entry ) {
3535 if ( in_array( $entry[2], $sectionIds, true ) ) {
3536 $callback = $entry[0];
3537 $this->trxEndCallbacks
[$key][0] = function () use ( $callback ) {
3538 // @phan-suppress-next-line PhanInfiniteRecursion, PhanUndeclaredInvokeInCallable
3539 return $callback( self
::TRIGGER_ROLLBACK
, $this );
3541 // This "on resolution" callback no longer belongs to a section.
3542 $this->trxEndCallbacks
[$key][2] = null;
3545 // Hoist callback ownership for section cancel callbacks to the new top section
3546 foreach ( $this->trxSectionCancelCallbacks
as $key => $entry ) {
3547 if ( in_array( $entry[2], $sectionIds, true ) ) {
3548 $this->trxSectionCancelCallbacks
[$key][2] = $newSectionId;
3553 final public function setTransactionListener( $name, callable
$callback = null ) {
3555 $this->trxRecurringCallbacks
[$name] = $callback;
3557 unset( $this->trxRecurringCallbacks
[$name] );
3562 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
3564 * This method should not be used outside of Database/LoadBalancer
3566 * @param bool $suppress
3569 final public function setTrxEndCallbackSuppression( $suppress ) {
3570 $this->trxEndCallbacksSuppressed
= $suppress;
3574 * Actually consume and run any "on transaction idle/resolution" callbacks.
3576 * This method should not be used outside of Database/LoadBalancer
3578 * @param int $trigger IDatabase::TRIGGER_* constant
3579 * @return int Number of callbacks attempted
3583 public function runOnTransactionIdleCallbacks( $trigger ) {
3584 if ( $this->trxLevel() ) { // sanity
3585 throw new DBUnexpectedError( $this, __METHOD__
. ': a transaction is still open' );
3588 if ( $this->trxEndCallbacksSuppressed
) {
3593 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
3594 /** @var Exception $e */
3595 $e = null; // first exception
3596 do { // callbacks may add callbacks :)
3597 $callbacks = array_merge(
3598 $this->trxIdleCallbacks
,
3599 $this->trxEndCallbacks
// include "transaction resolution" callbacks
3601 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
3602 $this->trxEndCallbacks
= []; // consumed (recursion guard)
3604 // Only run trxSectionCancelCallbacks on rollback, not commit.
3605 // But always consume them.
3606 if ( $trigger === self
::TRIGGER_ROLLBACK
) {
3607 $callbacks = array_merge( $callbacks, $this->trxSectionCancelCallbacks
);
3609 $this->trxSectionCancelCallbacks
= []; // consumed (recursion guard)
3611 foreach ( $callbacks as $callback ) {
3613 list( $phpCallback ) = $callback;
3614 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
3616 // @phan-suppress-next-line PhanParamTooManyCallable
3617 call_user_func( $phpCallback, $trigger, $this );
3618 } catch ( Exception
$ex ) {
3619 call_user_func( $this->errorLogger
, $ex );
3621 // Some callbacks may use startAtomic/endAtomic, so make sure
3622 // their transactions are ended so other callbacks don't fail
3623 if ( $this->trxLevel() ) {
3624 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3628 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
3630 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
3634 } while ( count( $this->trxIdleCallbacks
) );
3636 if ( $e instanceof Exception
) {
3637 throw $e; // re-throw any first exception
3644 * Actually consume and run any "on transaction pre-commit" callbacks.
3646 * This method should not be used outside of Database/LoadBalancer
3649 * @return int Number of callbacks attempted
3652 public function runOnTransactionPreCommitCallbacks() {
3655 $e = null; // first exception
3656 do { // callbacks may add callbacks :)
3657 $callbacks = $this->trxPreCommitCallbacks
;
3658 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
3659 foreach ( $callbacks as $callback ) {
3662 list( $phpCallback ) = $callback;
3663 // @phan-suppress-next-line PhanUndeclaredInvokeInCallable
3664 $phpCallback( $this );
3665 } catch ( Exception
$ex ) {
3666 ( $this->errorLogger
)( $ex );
3670 } while ( count( $this->trxPreCommitCallbacks
) );
3672 if ( $e instanceof Exception
) {
3673 throw $e; // re-throw any first exception
3680 * Actually run any "atomic section cancel" callbacks.
3682 * @param int $trigger IDatabase::TRIGGER_* constant
3683 * @param AtomicSectionIdentifier[]|null $sectionIds Section IDs to cancel,
3684 * null on transaction rollback
3686 private function runOnAtomicSectionCancelCallbacks(
3687 $trigger, array $sectionIds = null
3689 /** @var Exception|Throwable $e */
3690 $e = null; // first exception
3694 $callbacks = $this->trxSectionCancelCallbacks
;
3695 $this->trxSectionCancelCallbacks
= []; // consumed (recursion guard)
3696 foreach ( $callbacks as $entry ) {
3697 if ( $sectionIds === null ||
in_array( $entry[2], $sectionIds, true ) ) {
3699 // @phan-suppress-next-line PhanUndeclaredInvokeInCallable
3700 $entry[0]( $trigger, $this );
3701 } catch ( Exception
$ex ) {
3702 ( $this->errorLogger
)( $ex );
3704 } catch ( Throwable
$ex ) {
3709 $notCancelled[] = $entry;
3712 } while ( count( $this->trxSectionCancelCallbacks
) );
3713 $this->trxSectionCancelCallbacks
= $notCancelled;
3715 if ( $e !== null ) {
3716 throw $e; // re-throw any first Exception/Throwable
3721 * Actually run any "transaction listener" callbacks.
3723 * This method should not be used outside of Database/LoadBalancer
3725 * @param int $trigger IDatabase::TRIGGER_* constant
3729 public function runTransactionListenerCallbacks( $trigger ) {
3730 if ( $this->trxEndCallbacksSuppressed
) {
3734 /** @var Exception $e */
3735 $e = null; // first exception
3737 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3739 $phpCallback( $trigger, $this );
3740 } catch ( Exception
$ex ) {
3741 ( $this->errorLogger
)( $ex );
3746 if ( $e instanceof Exception
) {
3747 throw $e; // re-throw any first exception
3752 * Create a savepoint
3754 * This is used internally to implement atomic sections. It should not be
3758 * @param string $identifier Identifier for the savepoint
3759 * @param string $fname Calling function name
3761 protected function doSavepoint( $identifier, $fname ) {
3762 $this->query( 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3766 * Release a savepoint
3768 * This is used internally to implement atomic sections. It should not be
3772 * @param string $identifier Identifier for the savepoint
3773 * @param string $fname Calling function name
3775 protected function doReleaseSavepoint( $identifier, $fname ) {
3776 $this->query( 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3780 * Rollback to a savepoint
3782 * This is used internally to implement atomic sections. It should not be
3786 * @param string $identifier Identifier for the savepoint
3787 * @param string $fname Calling function name
3789 protected function doRollbackToSavepoint( $identifier, $fname ) {
3790 $this->query( 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3794 * @param string $fname
3797 private function nextSavepointId( $fname ) {
3798 $savepointId = self
::$SAVEPOINT_PREFIX . ++
$this->trxAtomicCounter
;
3799 if ( strlen( $savepointId ) > 30 ) {
3800 // 30 == Oracle's identifier length limit (pre 12c)
3801 // With a 22 character prefix, that puts the highest number at 99999999.
3802 throw new DBUnexpectedError(
3804 'There have been an excessively large number of atomic sections in a transaction'
3805 . " started by $this->trxFname (at $fname)"
3809 return $savepointId;
3812 final public function startAtomic(
3813 $fname = __METHOD__
, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3815 $savepointId = $cancelable === self
::ATOMIC_CANCELABLE ? self
::$NOT_APPLICABLE : null;
3817 if ( !$this->trxLevel() ) {
3818 $this->begin( $fname, self
::TRANSACTION_INTERNAL
); // sets trxAutomatic
3819 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3820 // in all changes being in one transaction to keep requests transactional.
3821 if ( $this->getFlag( self
::DBO_TRX
) ) {
3822 // Since writes could happen in between the topmost atomic sections as part
3823 // of the transaction, those sections will need savepoints.
3824 $savepointId = $this->nextSavepointId( $fname );
3825 $this->doSavepoint( $savepointId, $fname );
3827 $this->trxAutomaticAtomic
= true;
3829 } elseif ( $cancelable === self
::ATOMIC_CANCELABLE
) {
3830 $savepointId = $this->nextSavepointId( $fname );
3831 $this->doSavepoint( $savepointId, $fname );
3834 $sectionId = new AtomicSectionIdentifier
;
3835 $this->trxAtomicLevels
[] = [ $fname, $sectionId, $savepointId ];
3836 $this->queryLogger
->debug( 'startAtomic: entering level ' .
3837 ( count( $this->trxAtomicLevels
) - 1 ) . " ($fname)" );
3842 final public function endAtomic( $fname = __METHOD__
) {
3843 if ( !$this->trxLevel() ||
!$this->trxAtomicLevels
) {
3844 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3847 // Check if the current section matches $fname
3848 $pos = count( $this->trxAtomicLevels
) - 1;
3849 list( $savedFname, $sectionId, $savepointId ) = $this->trxAtomicLevels
[$pos];
3850 $this->queryLogger
->debug( "endAtomic: leaving level $pos ($fname)" );
3852 if ( $savedFname !== $fname ) {
3853 throw new DBUnexpectedError(
3855 "Invalid atomic section ended (got $fname but expected $savedFname)"
3859 // Remove the last section (no need to re-index the array)
3860 array_pop( $this->trxAtomicLevels
);
3862 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3863 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3864 } elseif ( $savepointId !== null && $savepointId !== self
::$NOT_APPLICABLE ) {
3865 $this->doReleaseSavepoint( $savepointId, $fname );
3868 // Hoist callback ownership for callbacks in the section that just ended;
3869 // all callbacks should have an owner that is present in trxAtomicLevels.
3870 $currentSectionId = $this->currentAtomicSectionId();
3871 if ( $currentSectionId ) {
3872 $this->reassignCallbacksForSection( $sectionId, $currentSectionId );
3876 final public function cancelAtomic(
3877 $fname = __METHOD__
, AtomicSectionIdentifier
$sectionId = null
3879 if ( !$this->trxLevel() ||
!$this->trxAtomicLevels
) {
3880 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3884 $newTopSection = $this->currentAtomicSectionId();
3886 $excisedFnames = [];
3887 if ( $sectionId !== null ) {
3888 // Find the (last) section with the given $sectionId
3890 foreach ( $this->trxAtomicLevels
as $i => list( $asFname, $asId, $spId ) ) {
3891 if ( $asId === $sectionId ) {
3896 throw new DBUnexpectedError( $this, "Atomic section not found (for $fname)" );
3898 // Remove all descendant sections and re-index the array
3899 $len = count( $this->trxAtomicLevels
);
3900 for ( $i = $pos +
1; $i < $len; ++
$i ) {
3901 $excisedFnames[] = $this->trxAtomicLevels
[$i][0];
3902 $excisedIds[] = $this->trxAtomicLevels
[$i][1];
3904 $this->trxAtomicLevels
= array_slice( $this->trxAtomicLevels
, 0, $pos +
1 );
3905 $newTopSection = $this->currentAtomicSectionId();
3908 // Check if the current section matches $fname
3909 $pos = count( $this->trxAtomicLevels
) - 1;
3910 list( $savedFname, $savedSectionId, $savepointId ) = $this->trxAtomicLevels
[$pos];
3912 if ( $excisedFnames ) {
3913 $this->queryLogger
->debug( "cancelAtomic: canceling level $pos ($savedFname) " .
3914 "and descendants " . implode( ', ', $excisedFnames ) );
3916 $this->queryLogger
->debug( "cancelAtomic: canceling level $pos ($savedFname)" );
3919 if ( $savedFname !== $fname ) {
3920 throw new DBUnexpectedError(
3922 "Invalid atomic section ended (got $fname but expected $savedFname)"
3926 // Remove the last section (no need to re-index the array)
3927 array_pop( $this->trxAtomicLevels
);
3928 $excisedIds[] = $savedSectionId;
3929 $newTopSection = $this->currentAtomicSectionId();
3931 if ( $savepointId !== null ) {
3932 // Rollback the transaction to the state just before this atomic section
3933 if ( $savepointId === self
::$NOT_APPLICABLE ) {
3934 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3935 // Note: rollback() will run trxSectionCancelCallbacks
3937 $this->doRollbackToSavepoint( $savepointId, $fname );
3938 $this->trxStatus
= self
::STATUS_TRX_OK
; // no exception; recovered
3939 $this->trxStatusIgnoredCause
= null;
3941 // Run trxSectionCancelCallbacks now.
3942 $this->runOnAtomicSectionCancelCallbacks( self
::TRIGGER_CANCEL
, $excisedIds );
3944 } elseif ( $this->trxStatus
> self
::STATUS_TRX_ERROR
) {
3945 // Put the transaction into an error state if it's not already in one
3946 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
3947 $this->trxStatusCause
= new DBUnexpectedError(
3949 "Uncancelable atomic section canceled (got $fname)"
3953 // Fix up callbacks owned by the sections that were just cancelled.
3954 // All callbacks should have an owner that is present in trxAtomicLevels.
3955 $this->modifyCallbacksForCancel( $excisedIds, $newTopSection );
3958 $this->affectedRowCount
= 0; // for the sake of consistency
3961 final public function doAtomicSection(
3962 $fname, callable
$callback, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3964 $sectionId = $this->startAtomic( $fname, $cancelable );
3966 $res = $callback( $this, $fname );
3967 } catch ( Exception
$e ) {
3968 $this->cancelAtomic( $fname, $sectionId );
3972 $this->endAtomic( $fname );
3977 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3978 static $modes = [ self
::TRANSACTION_EXPLICIT
, self
::TRANSACTION_INTERNAL
];
3979 if ( !in_array( $mode, $modes, true ) ) {
3980 throw new DBUnexpectedError( $this, "$fname: invalid mode parameter '$mode'" );
3983 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3984 if ( $this->trxLevel() ) {
3985 if ( $this->trxAtomicLevels
) {
3986 $levels = $this->flatAtomicSectionList();
3987 $msg = "$fname: got explicit BEGIN while atomic section(s) $levels are open";
3988 throw new DBUnexpectedError( $this, $msg );
3989 } elseif ( !$this->trxAutomatic
) {
3990 $msg = "$fname: explicit transaction already active (from {$this->trxFname})";
3991 throw new DBUnexpectedError( $this, $msg );
3993 $msg = "$fname: implicit transaction already active (from {$this->trxFname})";
3994 throw new DBUnexpectedError( $this, $msg );
3996 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3997 $msg = "$fname: implicit transaction expected (DBO_TRX set)";
3998 throw new DBUnexpectedError( $this, $msg );
4001 $this->assertHasConnectionHandle();
4003 $this->doBegin( $fname );
4004 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
4005 $this->trxStatus
= self
::STATUS_TRX_OK
;
4006 $this->trxStatusIgnoredCause
= null;
4007 $this->trxAtomicCounter
= 0;
4008 $this->trxTimestamp
= microtime( true );
4009 $this->trxFname
= $fname;
4010 $this->trxDoneWrites
= false;
4011 $this->trxAutomaticAtomic
= false;
4012 $this->trxAtomicLevels
= [];
4013 $this->trxWriteDuration
= 0.0;
4014 $this->trxWriteQueryCount
= 0;
4015 $this->trxWriteAffectedRows
= 0;
4016 $this->trxWriteAdjDuration
= 0.0;
4017 $this->trxWriteAdjQueryCount
= 0;
4018 $this->trxWriteCallers
= [];
4019 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
4020 // Get an estimate of the replication lag before any such queries.
4021 $this->trxReplicaLag
= null; // clear cached value first
4022 $this->trxReplicaLag
= $this->getApproximateLagStatus()['lag'];
4023 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
4024 // caller will think its OK to muck around with the transaction just because startAtomic()
4025 // has not yet completed (e.g. setting trxAtomicLevels).
4026 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
4030 * Issues the BEGIN command to the database server.
4032 * @see Database::begin()
4033 * @param string $fname
4036 protected function doBegin( $fname ) {
4037 $this->query( 'BEGIN', $fname );
4040 final public function commit( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
4041 static $modes = [ self
::FLUSHING_ONE
, self
::FLUSHING_ALL_PEERS
, self
::FLUSHING_INTERNAL
];
4042 if ( !in_array( $flush, $modes, true ) ) {
4043 throw new DBUnexpectedError( $this, "$fname: invalid flush parameter '$flush'" );
4046 if ( $this->trxLevel() && $this->trxAtomicLevels
) {
4047 // There are still atomic sections open; this cannot be ignored
4048 $levels = $this->flatAtomicSectionList();
4049 throw new DBUnexpectedError(
4051 "$fname: got COMMIT while atomic sections $levels are still open"
4055 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
4056 if ( !$this->trxLevel() ) {
4057 return; // nothing to do
4058 } elseif ( !$this->trxAutomatic
) {
4059 throw new DBUnexpectedError(
4061 "$fname: flushing an explicit transaction, getting out of sync"
4064 } elseif ( !$this->trxLevel() ) {
4065 $this->queryLogger
->error(
4066 "$fname: no transaction to commit, something got out of sync" );
4067 return; // nothing to do
4068 } elseif ( $this->trxAutomatic
) {
4069 throw new DBUnexpectedError(
4071 "$fname: expected mass commit of all peer transactions (DBO_TRX set)"
4075 $this->assertHasConnectionHandle();
4077 $this->runOnTransactionPreCommitCallbacks();
4079 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
4080 $this->doCommit( $fname );
4081 $oldTrxShortId = $this->consumeTrxShortId();
4082 $this->trxStatus
= self
::STATUS_TRX_NONE
;
4084 if ( $this->trxDoneWrites
) {
4085 $this->lastWriteTime
= microtime( true );
4086 $this->trxProfiler
->transactionWritingOut(
4088 $this->getDomainID(),
4091 $this->trxWriteAffectedRows
4095 // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4096 if ( $flush !== self
::FLUSHING_ALL_PEERS
) {
4097 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
4098 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
4103 * Issues the COMMIT command to the database server.
4105 * @see Database::commit()
4106 * @param string $fname
4109 protected function doCommit( $fname ) {
4110 if ( $this->trxLevel() ) {
4111 $this->query( 'COMMIT', $fname );
4115 final public function rollback( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
4116 $trxActive = $this->trxLevel();
4118 if ( $flush !== self
::FLUSHING_INTERNAL
4119 && $flush !== self
::FLUSHING_ALL_PEERS
4120 && $this->getFlag( self
::DBO_TRX
)
4122 throw new DBUnexpectedError(
4124 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)"
4129 $this->assertHasConnectionHandle();
4131 $this->doRollback( $fname );
4132 $oldTrxShortId = $this->consumeTrxShortId();
4133 $this->trxStatus
= self
::STATUS_TRX_NONE
;
4134 $this->trxAtomicLevels
= [];
4135 // Estimate the RTT via a query now that trxStatus is OK
4136 $writeTime = $this->pingAndCalculateLastTrxApplyTime();
4138 if ( $this->trxDoneWrites
) {
4139 $this->trxProfiler
->transactionWritingOut(
4141 $this->getDomainID(),
4144 $this->trxWriteAffectedRows
4149 // Clear any commit-dependant callbacks. They might even be present
4150 // only due to transaction rounds, with no SQL transaction being active
4151 $this->trxIdleCallbacks
= [];
4152 $this->trxPreCommitCallbacks
= [];
4154 // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4155 if ( $trxActive && $flush !== self
::FLUSHING_ALL_PEERS
) {
4157 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
4158 } catch ( Exception
$e ) {
4159 // already logged; finish and let LoadBalancer move on during mass-rollback
4162 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
4163 } catch ( Exception
$e ) {
4164 // already logged; let LoadBalancer move on during mass-rollback
4167 $this->affectedRowCount
= 0; // for the sake of consistency
4172 * Issues the ROLLBACK command to the database server.
4174 * @see Database::rollback()
4175 * @param string $fname
4178 protected function doRollback( $fname ) {
4179 if ( $this->trxLevel() ) {
4180 # Disconnects cause rollback anyway, so ignore those errors
4181 $ignoreErrors = true;
4182 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
4186 public function flushSnapshot( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
4187 if ( $this->explicitTrxActive() ) {
4188 // Committing this transaction would break callers that assume it is still open
4189 throw new DBUnexpectedError(
4191 "$fname: Cannot flush snapshot; " .
4192 "explicit transaction '{$this->trxFname}' is still open"
4194 } elseif ( $this->writesOrCallbacksPending() ) {
4195 // This only flushes transactions to clear snapshots, not to write data
4196 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4197 throw new DBUnexpectedError(
4199 "$fname: Cannot flush snapshot; " .
4200 "writes from transaction {$this->trxFname} are still pending ($fnames)"
4203 $this->trxLevel() &&
4204 $this->getTransactionRoundId() &&
4205 $flush !== self
::FLUSHING_INTERNAL
&&
4206 $flush !== self
::FLUSHING_ALL_PEERS
4208 $this->queryLogger
->warning(
4209 "$fname: Expected mass snapshot flush of all peer transactions " .
4210 "in the explicit transactions round '{$this->getTransactionRoundId()}'",
4211 [ 'exception' => new RuntimeException() ]
4215 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4218 public function explicitTrxActive() {
4219 return $this->trxLevel() && ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
4222 public function duplicateTableStructure(
4223 $oldName, $newName, $temporary = false, $fname = __METHOD__
4225 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4228 public function listTables( $prefix = null, $fname = __METHOD__
) {
4229 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4232 public function listViews( $prefix = null, $fname = __METHOD__
) {
4233 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4236 public function timestamp( $ts = 0 ) {
4237 $t = new ConvertibleTimestamp( $ts );
4238 // Let errors bubble up to avoid putting garbage in the DB
4239 return $t->getTimestamp( TS_MW
);
4242 public function timestampOrNull( $ts = null ) {
4243 if ( is_null( $ts ) ) {
4246 return $this->timestamp( $ts );
4250 public function affectedRows() {
4251 return ( $this->affectedRowCount
=== null )
4252 ?
$this->fetchAffectedRowCount() // default to driver value
4253 : $this->affectedRowCount
;
4257 * @return int Number of retrieved rows according to the driver
4259 abstract protected function fetchAffectedRowCount();
4262 * Take a query result and wrap it in an iterable result wrapper if necessary.
4263 * Booleans are passed through as-is to indicate success/failure of write queries.
4265 * Once upon a time, Database::query() returned a bare MySQL result
4266 * resource, and it was necessary to call this function to convert it to
4267 * a wrapper. Nowadays, raw database objects are never exposed to external
4268 * callers, so this is unnecessary in external code.
4270 * @param bool|IResultWrapper|resource $result
4271 * @return bool|IResultWrapper
4273 protected function resultObject( $result ) {
4275 return false; // failed query
4276 } elseif ( $result instanceof IResultWrapper
) {
4278 } elseif ( $result === true ) {
4279 return $result; // succesful write query
4281 return new ResultWrapper( $this, $result );
4285 public function ping( &$rtt = null ) {
4286 // Avoid hitting the server if it was hit recently
4287 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::$PING_TTL ) {
4288 if ( !func_num_args() ||
$this->lastRoundTripEstimate
> 0 ) {
4289 $rtt = $this->lastRoundTripEstimate
;
4290 return true; // don't care about $rtt
4294 // This will reconnect if possible or return false if not
4295 $flags = self
::QUERY_IGNORE_DBO_TRX | self
::QUERY_SILENCE_ERRORS
;
4296 $ok = ( $this->query( self
::$PING_QUERY, __METHOD__
, $flags ) !== false );
4298 $rtt = $this->lastRoundTripEstimate
;
4305 * Close any existing (dead) database connection and open a new connection
4307 * @param string $fname
4308 * @return bool True if new connection is opened successfully, false if error
4310 protected function replaceLostConnection( $fname ) {
4311 $this->closeConnection();
4314 $this->handleSessionLossPreconnect();
4321 $this->currentDomain
->getDatabase(),
4322 $this->currentDomain
->getSchema(),
4323 $this->tablePrefix()
4325 $this->lastPing
= microtime( true );
4328 $this->connLogger
->warning(
4329 $fname . ': lost connection to {dbserver}; reconnected',
4331 'dbserver' => $this->getServer(),
4332 'exception' => new RuntimeException()
4335 } catch ( DBConnectionError
$e ) {
4338 $this->connLogger
->error(
4339 $fname . ': lost connection to {dbserver} permanently',
4340 [ 'dbserver' => $this->getServer() ]
4344 $this->handleSessionLossPostconnect();
4349 public function getSessionLagStatus() {
4350 return $this->getRecordedTransactionLagStatus() ?
: $this->getApproximateLagStatus();
4354 * Get the replica DB lag when the current transaction started
4356 * This is useful when transactions might use snapshot isolation
4357 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
4358 * is this lag plus transaction duration. If they don't, it is still
4359 * safe to be pessimistic. This returns null if there is no transaction.
4361 * This returns null if the lag status for this transaction was not yet recorded.
4363 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
4366 final protected function getRecordedTransactionLagStatus() {
4367 return ( $this->trxLevel() && $this->trxReplicaLag
!== null )
4368 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
4373 * Get a replica DB lag estimate for this server
4375 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
4378 protected function getApproximateLagStatus() {
4380 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
4381 'since' => microtime( true )
4386 * Merge the result of getSessionLagStatus() for several DBs
4387 * using the most pessimistic values to estimate the lag of
4388 * any data derived from them in combination
4390 * This is information is useful for caching modules
4392 * @see WANObjectCache::set()
4393 * @see WANObjectCache::getWithSetCallback()
4395 * @param IDatabase $db1
4396 * @param IDatabase|null $db2 [optional]
4397 * @return array Map of values:
4398 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
4399 * - since: oldest UNIX timestamp of any of the DB lag estimates
4400 * - pending: whether any of the DBs have uncommitted changes
4404 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
4405 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
4406 foreach ( func_get_args() as $db ) {
4407 /** @var IDatabase $db */
4408 $status = $db->getSessionLagStatus();
4409 if ( $status['lag'] === false ) {
4410 $res['lag'] = false;
4411 } elseif ( $res['lag'] !== false ) {
4412 $res['lag'] = max( $res['lag'], $status['lag'] );
4414 $res['since'] = min( $res['since'], $status['since'] );
4415 $res['pending'] = $res['pending'] ?
: $db->writesPending();
4421 public function getLag() {
4422 if ( $this->getLBInfo( 'master' ) ) {
4423 return 0; // this is the master
4424 } elseif ( $this->getLBInfo( 'is static' ) ) {
4425 return 0; // static dataset
4428 return $this->doGetLag();
4431 protected function doGetLag() {
4435 public function maxListLen() {
4439 public function encodeBlob( $b ) {
4443 public function decodeBlob( $b ) {
4444 if ( $b instanceof Blob
) {
4450 public function setSessionOptions( array $options ) {
4453 public function sourceFile(
4455 callable
$lineCallback = null,
4456 callable
$resultCallback = null,
4458 callable
$inputCallback = null
4460 AtEase
::suppressWarnings();
4461 $fp = fopen( $filename, 'r' );
4462 AtEase
::restoreWarnings();
4464 if ( $fp === false ) {
4465 throw new RuntimeException( "Could not open \"{$filename}\"" );
4469 $fname = __METHOD__
. "( $filename )";
4473 $error = $this->sourceStream(
4474 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
4475 } catch ( Exception
$e ) {
4485 public function setSchemaVars( $vars ) {
4486 $this->schemaVars
= is_array( $vars ) ?
$vars : null;
4489 public function sourceStream(
4491 callable
$lineCallback = null,
4492 callable
$resultCallback = null,
4493 $fname = __METHOD__
,
4494 callable
$inputCallback = null
4496 $delimiterReset = new ScopedCallback(
4497 function ( $delimiter ) {
4498 $this->delimiter
= $delimiter;
4500 [ $this->delimiter
]
4504 while ( !feof( $fp ) ) {
4505 if ( $lineCallback ) {
4506 call_user_func( $lineCallback );
4509 $line = trim( fgets( $fp ) );
4511 if ( $line == '' ) {
4515 if ( $line[0] == '-' && $line[1] == '-' ) {
4523 $done = $this->streamStatementEnd( $cmd, $line );
4527 if ( $done ||
feof( $fp ) ) {
4528 $cmd = $this->replaceVars( $cmd );
4530 if ( $inputCallback ) {
4531 $callbackResult = $inputCallback( $cmd );
4533 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
4534 $cmd = $callbackResult;
4539 $res = $this->query( $cmd, $fname );
4541 if ( $resultCallback ) {
4542 $resultCallback( $res, $this );
4545 if ( $res === false ) {
4546 $err = $this->lastError();
4548 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4555 ScopedCallback
::consume( $delimiterReset );
4560 * Called by sourceStream() to check if we've reached a statement end
4562 * @param string &$sql SQL assembled so far
4563 * @param string &$newLine New line about to be added to $sql
4564 * @return bool Whether $newLine contains end of the statement
4566 public function streamStatementEnd( &$sql, &$newLine ) {
4567 if ( $this->delimiter
) {
4569 $newLine = preg_replace(
4570 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4571 if ( $newLine != $prev ) {
4580 * Database independent variable replacement. Replaces a set of variables
4581 * in an SQL statement with their contents as given by $this->getSchemaVars().
4583 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4585 * - '{$var}' should be used for text and is passed through the database's
4587 * - `{$var}` should be used for identifiers (e.g. table and database names).
4588 * It is passed through the database's addIdentifierQuotes method which
4589 * can be overridden if the database uses something other than backticks.
4590 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4591 * database's tableName method.
4592 * - / *i* / passes the name that follows through the database's indexName method.
4593 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4594 * its use should be avoided. In 1.24 and older, string encoding was applied.
4596 * @param string $ins SQL statement to replace variables in
4597 * @return string The new SQL statement with variables replaced
4599 protected function replaceVars( $ins ) {
4600 $vars = $this->getSchemaVars();
4601 return preg_replace_callback(
4603 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4604 \'\{\$ (\w+) }\' | # 3. addQuotes
4605 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4606 /\*\$ (\w+) \*/ # 5. leave unencoded
4608 function ( $m ) use ( $vars ) {
4609 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4610 // check for both nonexistent keys *and* the empty string.
4611 if ( isset( $m[1] ) && $m[1] !== '' ) {
4612 if ( $m[1] === 'i' ) {
4613 return $this->indexName( $m[2] );
4615 return $this->tableName( $m[2] );
4617 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4618 return $this->addQuotes( $vars[$m[3]] );
4619 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4620 return $this->addIdentifierQuotes( $vars[$m[4]] );
4621 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4622 return $vars[$m[5]];
4632 * Get schema variables. If none have been set via setSchemaVars(), then
4633 * use some defaults from the current object.
4637 protected function getSchemaVars() {
4638 return $this->schemaVars ??
$this->getDefaultSchemaVars();
4642 * Get schema variables to use if none have been set via setSchemaVars().
4644 * Override this in derived classes to provide variables for tables.sql
4645 * and SQL patch files.
4649 protected function getDefaultSchemaVars() {
4653 public function lockIsFree( $lockName, $method ) {
4654 // RDBMs methods for checking named locks may or may not count this thread itself.
4655 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
4656 // the behavior choosen by the interface for this method.
4657 return !isset( $this->sessionNamedLocks
[$lockName] );
4660 public function lock( $lockName, $method, $timeout = 5 ) {
4661 $this->sessionNamedLocks
[$lockName] = 1;
4666 public function unlock( $lockName, $method ) {
4667 unset( $this->sessionNamedLocks
[$lockName] );
4672 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
4673 if ( $this->writesOrCallbacksPending() ) {
4674 // This only flushes transactions to clear snapshots, not to write data
4675 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4676 throw new DBUnexpectedError(
4678 "$fname: Cannot flush pre-lock snapshot; " .
4679 "writes from transaction {$this->trxFname} are still pending ($fnames)"
4683 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
4687 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
4688 if ( $this->trxLevel() ) {
4689 // There is a good chance an exception was thrown, causing any early return
4690 // from the caller. Let any error handler get a chance to issue rollback().
4691 // If there isn't one, let the error bubble up and trigger server-side rollback.
4692 $this->onTransactionResolution(
4693 function () use ( $lockKey, $fname ) {
4694 $this->unlock( $lockKey, $fname );
4699 $this->unlock( $lockKey, $fname );
4703 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4708 public function namedLocksEnqueue() {
4712 public function tableLocksHaveTransactionScope() {
4716 final public function lockTables( array $read, array $write, $method ) {
4717 if ( $this->writesOrCallbacksPending() ) {
4718 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending" );
4721 if ( $this->tableLocksHaveTransactionScope() ) {
4722 $this->startAtomic( $method );
4725 return $this->doLockTables( $read, $write, $method );
4729 * Helper function for lockTables() that handles the actual table locking
4731 * @param array $read Array of tables to lock for read access
4732 * @param array $write Array of tables to lock for write access
4733 * @param string $method Name of caller
4736 protected function doLockTables( array $read, array $write, $method ) {
4740 final public function unlockTables( $method ) {
4741 if ( $this->tableLocksHaveTransactionScope() ) {
4742 $this->endAtomic( $method );
4744 return true; // locks released on COMMIT/ROLLBACK
4747 return $this->doUnlockTables( $method );
4751 * Helper function for unlockTables() that handles the actual table unlocking
4753 * @param string $method Name of caller
4756 protected function doUnlockTables( $method ) {
4762 * @param string $tableName
4763 * @param string $fName
4764 * @return bool|IResultWrapper
4767 public function dropTable( $tableName, $fName = __METHOD__
) {
4768 if ( !$this->tableExists( $tableName, $fName ) ) {
4771 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
4773 return $this->query( $sql, $fName );
4776 public function getInfinity() {
4780 public function encodeExpiry( $expiry ) {
4781 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4782 ?
$this->getInfinity()
4783 : $this->timestamp( $expiry );
4786 public function decodeExpiry( $expiry, $format = TS_MW
) {
4787 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
4791 return ConvertibleTimestamp
::convert( $format, $expiry );
4794 public function setBigSelects( $value = true ) {
4798 public function isReadOnly() {
4799 return ( $this->getReadOnlyReason() !== false );
4803 * @return string|bool Reason this DB is read-only or false if it is not
4805 protected function getReadOnlyReason() {
4806 $reason = $this->getLBInfo( 'readOnlyReason' );
4807 if ( is_string( $reason ) ) {
4809 } elseif ( $this->getLBInfo( 'replica' ) ) {
4810 return "Server is configured in the role of a read-only replica database.";
4816 public function setTableAliases( array $aliases ) {
4817 $this->tableAliases
= $aliases;
4820 public function setIndexAliases( array $aliases ) {
4821 $this->indexAliases
= $aliases;
4830 final protected function fieldHasBit( $field, $flags ) {
4831 return ( ( $field & $flags ) === $flags );
4835 * Get the underlying binding connection handle
4837 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
4838 * This catches broken callers than catch and ignore disconnection exceptions.
4839 * Unlike checking isOpen(), this is safe to call inside of open().
4842 * @throws DBUnexpectedError
4845 protected function getBindingHandle() {
4846 if ( !$this->conn
) {
4847 throw new DBUnexpectedError(
4849 'DB connection was already closed or the connection dropped'
4856 public function __toString() {
4857 // spl_object_id is PHP >= 7.2
4858 $id = function_exists( 'spl_object_id' )
4859 ?
spl_object_id( $this )
4860 : spl_object_hash( $this );
4862 $description = $this->getType() . ' object #' . $id;
4863 if ( is_resource( $this->conn
) ) {
4864 $description .= ' (' . (string)$this->conn
. ')'; // "resource id #<ID>"
4865 } elseif ( is_object( $this->conn
) ) {
4866 // spl_object_id is PHP >= 7.2
4867 $handleId = function_exists( 'spl_object_id' )
4868 ?
spl_object_id( $this->conn
)
4869 : spl_object_hash( $this->conn
);
4870 $description .= " (handle id #$handleId)";
4873 return $description;
4877 * Make sure that copies do not share the same client binding handle
4878 * @throws DBConnectionError
4880 public function __clone() {
4881 $this->connLogger
->warning(
4882 "Cloning " . static::class . " is not recommended; forking connection",
4883 [ 'exception' => new RuntimeException() ]
4886 if ( $this->isOpen() ) {
4887 // Open a new connection resource without messing with the old one
4889 $this->trxEndCallbacks
= []; // don't copy
4890 $this->trxSectionCancelCallbacks
= []; // don't copy
4891 $this->handleSessionLossPreconnect(); // no trx or locks anymore
4896 $this->currentDomain
->getDatabase(),
4897 $this->currentDomain
->getSchema(),
4898 $this->tablePrefix()
4900 $this->lastPing
= microtime( true );
4905 * Called by serialize. Throw an exception when DB connection is serialized.
4906 * This causes problems on some database engines because the connection is
4907 * not restored on unserialize.
4909 public function __sleep() {
4910 throw new RuntimeException( 'Database serialization may cause problems, since ' .
4911 'the connection is not restored on wakeup' );
4915 * Run a few simple sanity checks and close dangling connections
4917 public function __destruct() {
4918 if ( $this->trxLevel() && $this->trxDoneWrites
) {
4919 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})" );
4922 $danglingWriters = $this->pendingWriteAndCallbackCallers();
4923 if ( $danglingWriters ) {
4924 $fnames = implode( ', ', $danglingWriters );
4925 trigger_error( "DB transaction writes or callbacks still pending ($fnames)" );
4928 if ( $this->conn
) {
4929 // Avoid connection leaks for sanity. Normally, resources close at script completion.
4930 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4931 AtEase
::suppressWarnings();
4932 $this->closeConnection();
4933 AtEase
::restoreWarnings();
4940 * @deprecated since 1.28
4942 class_alias( Database
::class, 'DatabaseBase' );
4945 * @deprecated since 1.29
4947 class_alias( Database
::class, 'Database' );