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 string Lock granularity is on the level of the entire database */
178 const ATTR_DB_LEVEL_LOCKING
= 'db-level-locking';
179 /** @var string The SCHEMA keyword refers to a grouping of tables in a database */
180 const ATTR_SCHEMAS_AS_TABLE_GROUPS
= 'supports-schemas';
182 /** @var int New Database instance will not be connected yet when returned */
183 const NEW_UNCONNECTED
= 0;
184 /** @var int New Database instance will already be connected when returned */
185 const NEW_CONNECTED
= 1;
187 /** @var int Transaction is in a error state requiring a full or savepoint rollback */
188 const STATUS_TRX_ERROR
= 1;
189 /** @var int Transaction is active and in a normal state */
190 const STATUS_TRX_OK
= 2;
191 /** @var int No transaction is active */
192 const STATUS_TRX_NONE
= 3;
194 /** @var string Idiom used when a cancelable atomic section started the transaction */
195 private static $NOT_APPLICABLE = 'n/a';
196 /** @var string Prefix to the atomic section counter used to make savepoint IDs */
197 private static $SAVEPOINT_PREFIX = 'wikimedia_rdbms_atomic';
199 /** @var int Writes to this temporary table do not affect lastDoneWrites() */
200 private static $TEMP_NORMAL = 1;
201 /** @var int Writes to this temporary table effect lastDoneWrites() */
202 private static $TEMP_PSEUDO_PERMANENT = 2;
204 /** @var int Number of times to re-try an operation in case of deadlock */
205 private static $DEADLOCK_TRIES = 4;
206 /** @var int Minimum time to wait before retry, in microseconds */
207 private static $DEADLOCK_DELAY_MIN = 500000;
208 /** @var int Maximum time to wait before retry */
209 private static $DEADLOCK_DELAY_MAX = 1500000;
211 /** @var int How long before it is worth doing a dummy query to test the connection */
212 private static $PING_TTL = 1.0;
213 /** @var string Dummy SQL query */
214 private static $PING_QUERY = 'SELECT 1 AS ping';
216 /** @var float Guess of how many seconds it takes to replicate a small insert */
217 private static $TINY_WRITE_SEC = 0.010;
218 /** @var float Consider a write slow if it took more than this many seconds */
219 private static $SLOW_WRITE_SEC = 0.500;
220 /** @var float Assume an insert of this many rows or less should be fast to replicate */
221 private static $SMALL_WRITE_ROWS = 100;
223 /** @var string[] List of DBO_* flags that can be changed after connection */
224 protected static $MUTABLE_FLAGS = [
230 /** @var int Bit field of all DBO_* flags that can be changed after connection */
231 protected static $DBO_MUTABLE = (
232 self
::DBO_DEBUG | self
::DBO_NOBUFFER | self
::DBO_TRX | self
::DBO_DDLMODE
236 * @note exceptions for missing libraries/drivers should be thrown in initConnection()
237 * @param array $params Parameters passed from Database::factory()
239 public function __construct( array $params ) {
240 $this->connectionParams
= [];
241 foreach ( [ 'host', 'user', 'password', 'dbname', 'schema', 'tablePrefix' ] as $name ) {
242 $this->connectionParams
[$name] = $params[$name];
244 $this->connectionVariables
= $params['variables'] ??
[];
245 $this->cliMode
= $params['cliMode'];
246 $this->agent
= $params['agent'];
247 $this->flags
= $params['flags'];
248 if ( $this->flags
& self
::DBO_DEFAULT
) {
249 if ( $this->cliMode
) {
250 $this->flags
&= ~self
::DBO_TRX
;
252 $this->flags |
= self
::DBO_TRX
;
255 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'] ??
10000;
257 $this->srvCache
= $params['srvCache'] ??
new HashBagOStuff();
258 $this->profiler
= is_callable( $params['profiler'] ) ?
$params['profiler'] : null;
259 $this->trxProfiler
= $params['trxProfiler'];
260 $this->connLogger
= $params['connLogger'];
261 $this->queryLogger
= $params['queryLogger'];
262 $this->errorLogger
= $params['errorLogger'];
263 $this->deprecationLogger
= $params['deprecationLogger'];
265 // Set initial dummy domain until open() sets the final DB/prefix
266 $this->currentDomain
= new DatabaseDomain(
267 $params['dbname'] != '' ?
$params['dbname'] : null,
268 $params['schema'] != '' ?
$params['schema'] : null,
269 $params['tablePrefix']
274 * Initialize the connection to the database over the wire (or to local files)
276 * @throws LogicException
277 * @throws InvalidArgumentException
278 * @throws DBConnectionError
281 final public function initConnection() {
282 if ( $this->isOpen() ) {
283 throw new LogicException( __METHOD__
. ': already connected' );
285 // Establish the connection
286 $this->doInitConnection();
290 * Actually connect to the database over the wire (or to local files)
292 * @throws DBConnectionError
295 protected function doInitConnection() {
297 $this->connectionParams
['host'],
298 $this->connectionParams
['user'],
299 $this->connectionParams
['password'],
300 $this->connectionParams
['dbname'],
301 $this->connectionParams
['schema'],
302 $this->connectionParams
['tablePrefix']
307 * Open a new connection to the database (closing any existing one)
309 * @param string|null $server Database server host
310 * @param string|null $user Database user name
311 * @param string|null $password Database user password
312 * @param string|null $dbName Database name
313 * @param string|null $schema Database schema name
314 * @param string $tablePrefix Table prefix
315 * @throws DBConnectionError
317 abstract protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix );
320 * Construct a Database subclass instance given a database type and parameters
322 * This also connects to the database immediately upon object construction
324 * @param string $type A possible DB type (sqlite, mysql, postgres,...)
325 * @param array $params Parameter map with keys:
326 * - host : The hostname of the DB server
327 * - user : The name of the database user the client operates under
328 * - password : The password for the database user
329 * - dbname : The name of the database to use where queries do not specify one.
330 * The database must exist or an error might be thrown. Setting this to the empty string
331 * will avoid any such errors and make the handle have no implicit database scope. This is
332 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
333 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
334 * in which user names and such are defined, e.g. users are database-specific in Postgres.
335 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
336 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
337 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
338 * recognized in queries. This can be used in place of schemas for handle site farms.
339 * - flags : Optional bit field of DBO_* constants that define connection, protocol,
340 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
341 * flag in place UNLESS this this database simply acts as a key/value store.
342 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
343 * 'mysqli' driver; the old one 'mysql' has been removed.
344 * - variables: Optional map of session variables to set after connecting. This can be
345 * used to adjust lock timeouts or encoding modes and the like.
346 * - connLogger: Optional PSR-3 logger interface instance.
347 * - queryLogger: Optional PSR-3 logger interface instance.
348 * - profiler : Optional callback that takes a section name argument and returns
349 * a ScopedCallback instance that ends the profile section in its destructor.
350 * These will be called in query(), using a simplified version of the SQL that
351 * also includes the agent as a SQL comment.
352 * - trxProfiler: Optional TransactionProfiler instance.
353 * - errorLogger: Optional callback that takes an Exception and logs it.
354 * - deprecationLogger: Optional callback that takes a string and logs it.
355 * - cliMode: Whether to consider the execution context that of a CLI script.
356 * - agent: Optional name used to identify the end-user in query profiling/logging.
357 * - srvCache: Optional BagOStuff instance to an APC-style cache.
358 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
359 * @param int $connect One of the class constants (NEW_CONNECTED, NEW_UNCONNECTED) [optional]
360 * @return Database|null If the database driver or extension cannot be found
361 * @throws InvalidArgumentException If the database driver or extension cannot be found
364 final public static function factory( $type, $params = [], $connect = self
::NEW_CONNECTED
) {
365 $class = self
::getClass( $type, $params['driver'] ??
null );
367 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
377 'cliMode' => ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' ),
378 'agent' => basename( $_SERVER['SCRIPT_NAME'] ) . '@' . gethostname()
381 $normalizedParams = [
383 'host' => strlen( $params['host'] ) ?
$params['host'] : null,
384 'user' => strlen( $params['user'] ) ?
$params['user'] : null,
385 'password' => is_string( $params['password'] ) ?
$params['password'] : null,
386 'dbname' => strlen( $params['dbname'] ) ?
$params['dbname'] : null,
387 'schema' => strlen( $params['schema'] ) ?
$params['schema'] : null,
388 'tablePrefix' => (string)$params['tablePrefix'],
389 'flags' => (int)$params['flags'],
390 'variables' => $params['variables'],
391 'cliMode' => (bool)$params['cliMode'],
392 'agent' => (string)$params['agent'],
393 // Objects and callbacks
394 'srvCache' => $params['srvCache'] ??
new HashBagOStuff(),
395 'profiler' => $params['profiler'] ??
null,
396 'trxProfiler' => $params['trxProfiler'] ??
new TransactionProfiler(),
397 'connLogger' => $params['connLogger'] ??
new NullLogger(),
398 'queryLogger' => $params['queryLogger'] ??
new NullLogger(),
399 'errorLogger' => $params['errorLogger'] ??
function ( Exception
$e ) {
400 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
402 'deprecationLogger' => $params['deprecationLogger'] ??
function ( $msg ) {
403 trigger_error( $msg, E_USER_DEPRECATED
);
407 /** @var Database $conn */
408 $conn = new $class( $normalizedParams );
409 if ( $connect === self
::NEW_CONNECTED
) {
410 $conn->initConnection();
420 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
421 * @param string|null $driver Optional name of a specific DB client driver
422 * @return array Map of (Database::ATTR_* constant => value) for all such constants
423 * @throws InvalidArgumentException
426 final public static function attributesFromType( $dbType, $driver = null ) {
428 self
::ATTR_DB_LEVEL_LOCKING
=> false,
429 self
::ATTR_SCHEMAS_AS_TABLE_GROUPS
=> false
432 $class = self
::getClass( $dbType, $driver );
434 return call_user_func( [ $class, 'getAttributes' ] ) +
$defaults;
438 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
439 * @param string|null $driver Optional name of a specific DB client driver
440 * @return string Database subclass name to use
441 * @throws InvalidArgumentException
443 private static function getClass( $dbType, $driver = null ) {
444 // For database types with built-in support, the below maps type to IDatabase
445 // implementations. For types with multipe driver implementations (PHP extensions),
446 // an array can be used, keyed by extension name. In case of an array, the
447 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
448 // we auto-detect the first available driver. For types without built-in support,
449 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
450 static $builtinTypes = [
451 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
452 'sqlite' => DatabaseSqlite
::class,
453 'postgres' => DatabasePostgres
::class,
456 $dbType = strtolower( $dbType );
459 if ( isset( $builtinTypes[$dbType] ) ) {
460 $possibleDrivers = $builtinTypes[$dbType];
461 if ( is_string( $possibleDrivers ) ) {
462 $class = $possibleDrivers;
463 } elseif ( (string)$driver !== '' ) {
464 if ( !isset( $possibleDrivers[$driver] ) ) {
465 throw new InvalidArgumentException( __METHOD__
.
466 " type '$dbType' does not support driver '{$driver}'" );
469 $class = $possibleDrivers[$driver];
471 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
472 if ( extension_loaded( $posDriver ) ) {
473 $class = $possibleClass;
479 $class = 'Database' . ucfirst( $dbType );
482 if ( $class === false ) {
483 throw new InvalidArgumentException( __METHOD__
.
484 " no viable database extension found for type '$dbType'" );
491 * @return array Map of (Database::ATTR_* constant => value)
494 protected static function getAttributes() {
499 * Set the PSR-3 logger interface to use for query logging. (The logger
500 * interfaces for connection logging and error logging can be set with the
503 * @param LoggerInterface $logger
505 public function setLogger( LoggerInterface
$logger ) {
506 $this->queryLogger
= $logger;
509 public function getServerInfo() {
510 return $this->getServerVersion();
514 * Backwards-compatibility no-op method for disabling query buffering
516 * @param null|bool $buffer Whether to buffer queries (ignored)
517 * @return bool Whether buffering was already enabled (always true)
518 * @deprecated Since 1.34 Use query batching; this no longer does anything
520 public function bufferResults( $buffer = null ) {
524 final public function trxLevel() {
525 return ( $this->trxShortId
!= '' ) ?
1 : 0;
528 public function trxTimestamp() {
529 return $this->trxLevel() ?
$this->trxTimestamp
: null;
533 * @return int One of the STATUS_TRX_* class constants
536 public function trxStatus() {
537 return $this->trxStatus
;
540 public function tablePrefix( $prefix = null ) {
541 $old = $this->currentDomain
->getTablePrefix();
542 if ( $prefix !== null ) {
543 $this->currentDomain
= new DatabaseDomain(
544 $this->currentDomain
->getDatabase(),
545 $this->currentDomain
->getSchema(),
553 public function dbSchema( $schema = null ) {
554 if ( strlen( $schema ) && $this->getDBname() === null ) {
555 throw new DBUnexpectedError( $this, "Cannot set schema to '$schema'; no database set" );
558 $old = $this->currentDomain
->getSchema();
559 if ( $schema !== null ) {
560 $this->currentDomain
= new DatabaseDomain(
561 $this->currentDomain
->getDatabase(),
562 // DatabaseDomain uses null for unspecified schemas
563 strlen( $schema ) ?
$schema : null,
564 $this->currentDomain
->getTablePrefix()
572 * @return string Schema to use to qualify relations in queries
574 protected function relationSchemaQualifier() {
575 return $this->dbSchema();
578 public function getLBInfo( $name = null ) {
579 if ( is_null( $name ) ) {
580 return $this->lbInfo
;
583 if ( array_key_exists( $name, $this->lbInfo
) ) {
584 return $this->lbInfo
[$name];
590 public function setLBInfo( $nameOrArray, $value = null ) {
591 if ( is_array( $nameOrArray ) ) {
592 $this->lbInfo
= $nameOrArray;
593 } elseif ( is_string( $nameOrArray ) ) {
594 if ( $value !== null ) {
595 $this->lbInfo
[$nameOrArray] = $value;
597 unset( $this->lbInfo
[$nameOrArray] );
600 throw new InvalidArgumentException( "Got non-string key" );
604 public function setLazyMasterHandle( IDatabase
$conn ) {
605 $this->lazyMasterHandle
= $conn;
609 * @return IDatabase|null
610 * @see setLazyMasterHandle()
613 protected function getLazyMasterHandle() {
614 return $this->lazyMasterHandle
;
617 public function implicitOrderby() {
621 public function lastQuery() {
622 return $this->lastQuery
;
625 public function lastDoneWrites() {
626 return $this->lastWriteTime ?
: false;
629 public function writesPending() {
630 return $this->trxLevel() && $this->trxDoneWrites
;
633 public function writesOrCallbacksPending() {
634 return $this->trxLevel() && (
635 $this->trxDoneWrites ||
636 $this->trxIdleCallbacks ||
637 $this->trxPreCommitCallbacks ||
638 $this->trxEndCallbacks ||
639 $this->trxSectionCancelCallbacks
643 public function preCommitCallbacksPending() {
644 return $this->trxLevel() && $this->trxPreCommitCallbacks
;
648 * @return string|null
650 final protected function getTransactionRoundId() {
651 // If transaction round participation is enabled, see if one is active
652 if ( $this->getFlag( self
::DBO_TRX
) ) {
653 $id = $this->getLBInfo( 'trxRoundId' );
655 return is_string( $id ) ?
$id : null;
661 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
662 if ( !$this->trxLevel() ) {
664 } elseif ( !$this->trxDoneWrites
) {
669 case self
::ESTIMATE_DB_APPLY
:
670 return $this->pingAndCalculateLastTrxApplyTime();
671 default: // everything
672 return $this->trxWriteDuration
;
677 * @return float Time to apply writes to replicas based on trxWrite* fields
679 private function pingAndCalculateLastTrxApplyTime() {
682 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
683 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
684 // For omitted queries, make them count as something at least
685 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
686 $applyTime +
= self
::$TINY_WRITE_SEC * $omitted;
691 public function pendingWriteCallers() {
692 return $this->trxLevel() ?
$this->trxWriteCallers
: [];
695 public function pendingWriteRowsAffected() {
696 return $this->trxWriteAffectedRows
;
700 * List the methods that have write queries or callbacks for the current transaction
702 * This method should not be used outside of Database/LoadBalancer
707 public function pendingWriteAndCallbackCallers() {
708 $fnames = $this->pendingWriteCallers();
710 $this->trxIdleCallbacks
,
711 $this->trxPreCommitCallbacks
,
712 $this->trxEndCallbacks
,
713 $this->trxSectionCancelCallbacks
715 foreach ( $callbacks as $callback ) {
716 $fnames[] = $callback[1];
726 private function flatAtomicSectionList() {
727 return array_reduce( $this->trxAtomicLevels
, function ( $accum, $v ) {
728 return $accum === null ?
$v[0] : "$accum, " . $v[0];
732 public function isOpen() {
733 return (bool)$this->conn
;
736 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
737 if ( $flag & ~
static::$DBO_MUTABLE ) {
738 throw new DBUnexpectedError(
740 "Got $flag (allowed: " . implode( ', ', static::$MUTABLE_FLAGS ) . ')'
744 if ( $remember === self
::REMEMBER_PRIOR
) {
745 array_push( $this->priorFlags
, $this->flags
);
748 $this->flags |
= $flag;
751 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
752 if ( $flag & ~
static::$DBO_MUTABLE ) {
753 throw new DBUnexpectedError(
755 "Got $flag (allowed: " . implode( ', ', static::$MUTABLE_FLAGS ) . ')'
759 if ( $remember === self
::REMEMBER_PRIOR
) {
760 array_push( $this->priorFlags
, $this->flags
);
763 $this->flags
&= ~
$flag;
766 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
767 if ( !$this->priorFlags
) {
771 if ( $state === self
::RESTORE_INITIAL
) {
772 $this->flags
= reset( $this->priorFlags
);
773 $this->priorFlags
= [];
775 $this->flags
= array_pop( $this->priorFlags
);
779 public function getFlag( $flag ) {
780 return ( ( $this->flags
& $flag ) === $flag );
783 public function getDomainID() {
784 return $this->currentDomain
->getId();
788 * Get information about an index into an object
789 * @param string $table Table name
790 * @param string $index Index name
791 * @param string $fname Calling function name
792 * @return mixed Database-specific index description class or false if the index does not exist
794 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
797 * Wrapper for addslashes()
799 * @param string $s String to be slashed.
800 * @return string Slashed string.
802 abstract function strencode( $s );
805 * Set a custom error handler for logging errors during database connection
807 protected function installErrorHandler() {
808 $this->lastPhpError
= false;
809 $this->htmlErrors
= ini_set( 'html_errors', '0' );
810 set_error_handler( [ $this, 'connectionErrorLogger' ] );
814 * Restore the previous error handler and return the last PHP error for this DB
816 * @return bool|string
818 protected function restoreErrorHandler() {
819 restore_error_handler();
820 if ( $this->htmlErrors
!== false ) {
821 ini_set( 'html_errors', $this->htmlErrors
);
824 return $this->getLastPHPError();
828 * @return string|bool Last PHP error for this DB (typically connection errors)
830 protected function getLastPHPError() {
831 if ( $this->lastPhpError
) {
832 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->lastPhpError
);
833 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
842 * Error handler for logging errors during database connection
843 * This method should not be used outside of Database classes
846 * @param string $errstr
848 public function connectionErrorLogger( $errno, $errstr ) {
849 $this->lastPhpError
= $errstr;
853 * Create a log context to pass to PSR-3 logger functions.
855 * @param array $extras Additional data to add to context
858 protected function getLogContext( array $extras = [] ) {
861 'db_server' => $this->server
,
862 'db_name' => $this->getDBname(),
863 'db_user' => $this->user
,
869 final public function close() {
870 $exception = null; // error to throw after disconnecting
872 $wasOpen = (bool)$this->conn
;
873 // This should mostly do nothing if the connection is already closed
875 // Roll back any dangling transaction first
876 if ( $this->trxLevel() ) {
877 if ( $this->trxAtomicLevels
) {
878 // Cannot let incomplete atomic sections be committed
879 $levels = $this->flatAtomicSectionList();
880 $exception = new DBUnexpectedError(
882 __METHOD__
. ": atomic sections $levels are still open"
884 } elseif ( $this->trxAutomatic
) {
885 // Only the connection manager can commit non-empty DBO_TRX transactions
886 // (empty ones we can silently roll back)
887 if ( $this->writesOrCallbacksPending() ) {
888 $exception = new DBUnexpectedError(
891 ": mass commit/rollback of peer transaction required (DBO_TRX set)"
895 // Manual transactions should have been committed or rolled
896 // back, even if empty.
897 $exception = new DBUnexpectedError(
899 __METHOD__
. ": transaction is still open (from {$this->trxFname})"
903 if ( $this->trxEndCallbacksSuppressed
) {
904 $exception = $exception ?
: new DBUnexpectedError(
906 __METHOD__
. ': callbacks are suppressed; cannot properly commit'
910 // Rollback the changes and run any callbacks as needed
911 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
914 // Close the actual connection in the binding handle
915 $closed = $this->closeConnection();
917 $closed = true; // already closed; nothing to do
922 // Throw any unexpected errors after having disconnected
923 if ( $exception instanceof Exception
) {
927 // Note that various subclasses call close() at the start of open(), which itself is
928 // called by replaceLostConnection(). In that case, just because onTransactionResolution()
929 // callbacks are pending does not mean that an exception should be thrown. Rather, they
930 // will be executed after the reconnection step.
932 // Sanity check that no callbacks are dangling
933 $fnames = $this->pendingWriteAndCallbackCallers();
935 throw new RuntimeException(
936 "Transaction callbacks are still pending: " . implode( ', ', $fnames )
945 * Make sure there is an open connection handle (alive or not) as a sanity check
947 * This guards against fatal errors to the binding handle not being defined
948 * in cases where open() was never called or close() was already called
950 * @throws DBUnexpectedError
952 final protected function assertHasConnectionHandle() {
953 if ( !$this->isOpen() ) {
954 throw new DBUnexpectedError( $this, "DB connection was already closed" );
959 * Make sure that this server is not marked as a replica nor read-only as a sanity check
961 * @throws DBReadOnlyRoleError
962 * @throws DBReadOnlyError
964 protected function assertIsWritableMaster() {
965 if ( $this->getLBInfo( 'replica' ) ) {
966 throw new DBReadOnlyRoleError(
968 'Write operations are not allowed on replica database connections'
971 $reason = $this->getReadOnlyReason();
972 if ( $reason !== false ) {
973 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
978 * Closes underlying database connection
980 * @return bool Whether connection was closed successfully
982 abstract protected function closeConnection();
985 * Run a query and return a DBMS-dependent wrapper or boolean
987 * This is meant to handle the basic command of actually sending a query to the
988 * server via the driver. No implicit transaction, reconnection, nor retry logic
989 * should happen here. The higher level query() method is designed to handle those
990 * sorts of concerns. This method should not trigger such higher level methods.
992 * The lastError() and lastErrno() methods should meaningfully reflect what error,
993 * if any, occured during the last call to this method. Methods like executeQuery(),
994 * query(), select(), insert(), update(), delete(), and upsert() implement their calls
995 * to doQuery() such that an immediately subsequent call to lastError()/lastErrno()
996 * meaningfully reflects any error that occured during that public query method call.
998 * For SELECT queries, this returns either:
999 * - a) A driver-specific value/resource, only on success. This can be iterated
1000 * over by calling fetchObject()/fetchRow() until there are no more rows.
1001 * Alternatively, the result can be passed to resultObject() to obtain an
1002 * IResultWrapper instance which can then be iterated over via "foreach".
1003 * - b) False, on any query failure
1005 * For non-SELECT queries, this returns either:
1006 * - a) A driver-specific value/resource, only on success
1007 * - b) True, only on success (e.g. no meaningful result other than "OK")
1008 * - c) False, on any query failure
1010 * @param string $sql SQL query
1011 * @return mixed|bool An object, resource, or true on success; false on failure
1013 abstract protected function doQuery( $sql );
1016 * Determine whether a query writes to the DB. When in doubt, this returns true.
1020 * - Subsequent web requests should not need to wait for replication from
1021 * the master position seen by this web request, unless this request made
1022 * changes to the master. This is handled by ChronologyProtector by checking
1023 * doneWrites() at the end of the request. doneWrites() returns true if any
1024 * query set lastWriteTime; which query() does based on isWriteQuery().
1026 * - Reject write queries to replica DBs, in query().
1028 * @param string $sql
1031 protected function isWriteQuery( $sql ) {
1032 // BEGIN and COMMIT queries are considered read queries here.
1033 // Database backends and drivers (MySQL, MariaDB, php-mysqli) generally
1034 // treat these as write queries, in that their results have "affected rows"
1035 // as meta data as from writes, instead of "num rows" as from reads.
1036 // But, we treat them as read queries because when reading data (from
1037 // either replica or master) we use transactions to enable repeatable-read
1038 // snapshots, which ensures we get consistent results from the same snapshot
1039 // for all queries within a request. Use cases:
1040 // - Treating these as writes would trigger ChronologyProtector (see method doc).
1041 // - We use this method to reject writes to replicas, but we need to allow
1042 // use of transactions on replicas for read snapshots. This is fine given
1043 // that transactions by themselves don't make changes, only actual writes
1044 // within the transaction matter, which we still detect.
1046 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SAVEPOINT|RELEASE|SET|SHOW|EXPLAIN|USE|\(SELECT)\b/i',
1052 * @param string $sql
1053 * @return string|null
1055 protected function getQueryVerb( $sql ) {
1056 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
1060 * Determine whether a SQL statement is sensitive to isolation level.
1062 * A SQL statement is considered transactable if its result could vary
1063 * depending on the transaction isolation level. Operational commands
1064 * such as 'SET' and 'SHOW' are not considered to be transactable.
1066 * Main purpose: Used by query() to decide whether to begin a transaction
1067 * before the current query (in DBO_TRX mode, on by default).
1069 * @param string $sql
1072 protected function isTransactableQuery( $sql ) {
1074 $this->getQueryVerb( $sql ),
1075 [ 'BEGIN', 'ROLLBACK', 'COMMIT', 'SET', 'SHOW', 'CREATE', 'ALTER', 'USE', 'SHOW' ],
1081 * @param string $sql A SQL query
1082 * @param bool $pseudoPermanent Treat any table from CREATE TEMPORARY as pseudo-permanent
1083 * @return array A n-tuple of:
1084 * - int|null: A self::TEMP_* constant for temp table operations or null otherwise
1085 * - string|null: The name of the new temporary table $sql creates, or null
1086 * - string|null: The name of the temporary table that $sql drops, or null
1088 protected function getTempWrites( $sql, $pseudoPermanent ) {
1089 static $qt = '[`"\']?(\w+)[`"\']?'; // quoted table
1092 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?' . $qt . '/i',
1096 $type = $pseudoPermanent ? self
::$TEMP_PSEUDO_PERMANENT : self
::$TEMP_NORMAL;
1098 return [ $type, $matches[1], null ];
1099 } elseif ( preg_match(
1100 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt . '/i',
1104 return [ $this->sessionTempTables
[$matches[1]] ??
null, null, $matches[1] ];
1105 } elseif ( preg_match(
1106 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt . '/i',
1110 return [ $this->sessionTempTables
[$matches[1]] ??
null, null, null ];
1111 } elseif ( preg_match(
1112 '/^(?:(?:INSERT|REPLACE)\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+' . $qt . '/i',
1116 return [ $this->sessionTempTables
[$matches[1]] ??
null, null, null ];
1119 return [ null, null, null ];
1123 * @param IResultWrapper|bool $ret
1124 * @param int|null $tmpType TEMP_NORMAL or TEMP_PSEUDO_PERMANENT
1125 * @param string|null $tmpNew Name of created temp table
1126 * @param string|null $tmpDel Name of dropped temp table
1128 protected function registerTempWrites( $ret, $tmpType, $tmpNew, $tmpDel ) {
1129 if ( $ret !== false ) {
1130 if ( $tmpNew !== null ) {
1131 $this->sessionTempTables
[$tmpNew] = $tmpType;
1133 if ( $tmpDel !== null ) {
1134 unset( $this->sessionTempTables
[$tmpDel] );
1139 public function query( $sql, $fname = __METHOD__
, $flags = 0 ) {
1140 $flags = (int)$flags; // b/c; this field used to be a bool
1141 // Sanity check that the SQL query is appropriate in the current context and is
1142 // allowed for an outside caller (e.g. does not break transaction/session tracking).
1143 $this->assertQueryIsCurrentlyAllowed( $sql, $fname );
1145 // Send the query to the server and fetch any corresponding errors
1146 list( $ret, $err, $errno, $unignorable ) = $this->executeQuery( $sql, $fname, $flags );
1147 if ( $ret === false ) {
1148 $ignoreErrors = $this->fieldHasBit( $flags, self
::QUERY_SILENCE_ERRORS
);
1149 // Throw an error unless both the ignore flag was set and a rollback is not needed
1150 $this->reportQueryError( $err, $errno, $sql, $fname, $ignoreErrors && !$unignorable );
1153 return $this->resultObject( $ret );
1157 * Execute a query, retrying it if there is a recoverable connection loss
1159 * This is similar to query() except:
1160 * - It does not prevent all non-ROLLBACK queries if there is a corrupted transaction
1161 * - It does not disallow raw queries that are supposed to use dedicated IDatabase methods
1162 * - It does not throw exceptions for common error cases
1164 * This is meant for internal use with Database subclasses.
1166 * @param string $sql Original SQL query
1167 * @param string $fname Name of the calling function
1168 * @param int $flags Bit field of class QUERY_* constants
1169 * @return array An n-tuple of:
1170 * - mixed|bool: An object, resource, or true on success; false on failure
1171 * - string: The result of calling lastError()
1172 * - int: The result of calling lastErrno()
1173 * - bool: Whether a rollback is needed to allow future non-rollback queries
1174 * @throws DBUnexpectedError
1176 final protected function executeQuery( $sql, $fname, $flags ) {
1177 $this->assertHasConnectionHandle();
1179 $priorTransaction = $this->trxLevel();
1181 if ( $this->isWriteQuery( $sql ) ) {
1182 // In theory, non-persistent writes are allowed in read-only mode, but due to things
1183 // like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1184 $this->assertIsWritableMaster();
1185 // Do not treat temporary table writes as "meaningful writes" since they are only
1186 // visible to one session and are not permanent. Profile them as reads. Integration
1187 // tests can override this behavior via $flags.
1188 $pseudoPermanent = $this->fieldHasBit( $flags, self
::QUERY_PSEUDO_PERMANENT
);
1189 list( $tmpType, $tmpNew, $tmpDel ) = $this->getTempWrites( $sql, $pseudoPermanent );
1190 $isPermWrite = ( $tmpType !== self
::$TEMP_NORMAL );
1191 // DBConnRef uses QUERY_REPLICA_ROLE to enforce the replica role for raw SQL queries
1192 if ( $isPermWrite && $this->fieldHasBit( $flags, self
::QUERY_REPLICA_ROLE
) ) {
1193 throw new DBReadOnlyRoleError( $this, "Cannot write; target role is DB_REPLICA" );
1196 // No permanent writes in this query
1197 $isPermWrite = false;
1198 // No temporary tables written to either
1199 list( $tmpType, $tmpNew, $tmpDel ) = [ null, null, null ];
1202 // Add trace comment to the begin of the sql string, right after the operator.
1203 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598).
1204 $encAgent = str_replace( '/', '-', $this->agent
);
1205 $commentedSql = preg_replace( '/\s|$/', " /* $fname $encAgent */ ", $sql, 1 );
1207 // Send the query to the server and fetch any corresponding errors.
1208 // This also doubles as a "ping" to see if the connection was dropped.
1209 list( $ret, $err, $errno, $recoverableSR, $recoverableCL, $reconnected ) =
1210 $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1212 // Check if the query failed due to a recoverable connection loss
1213 $allowRetry = !$this->fieldHasBit( $flags, self
::QUERY_NO_RETRY
);
1214 if ( $ret === false && $recoverableCL && $reconnected && $allowRetry ) {
1215 // Silently resend the query to the server since it is safe and possible
1216 list( $ret, $err, $errno, $recoverableSR, $recoverableCL ) =
1217 $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1220 // Register creation and dropping of temporary tables
1221 $this->registerTempWrites( $ret, $tmpType, $tmpNew, $tmpDel );
1223 $corruptedTrx = false;
1225 if ( $ret === false ) {
1226 if ( $priorTransaction ) {
1227 if ( $recoverableSR ) {
1228 # We're ignoring an error that caused just the current query to be aborted.
1229 # But log the cause so we can log a deprecation notice if a caller actually
1231 $this->trxStatusIgnoredCause
= [ $err, $errno, $fname ];
1232 } elseif ( !$recoverableCL ) {
1233 # Either the query was aborted or all queries after BEGIN where aborted.
1234 # In the first case, the only options going forward are (a) ROLLBACK, or
1235 # (b) ROLLBACK TO SAVEPOINT (if one was set). If the later case, the only
1236 # option is ROLLBACK, since the snapshots would have been released.
1237 $corruptedTrx = true; // cannot recover
1238 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
1239 $this->trxStatusCause
=
1240 $this->getQueryExceptionAndLog( $err, $errno, $sql, $fname );
1241 $this->trxStatusIgnoredCause
= null;
1246 return [ $ret, $err, $errno, $corruptedTrx ];
1250 * Wrapper for doQuery() that handles DBO_TRX, profiling, logging, affected row count
1251 * tracking, and reconnects (without retry) on query failure due to connection loss
1253 * @param string $sql Original SQL query
1254 * @param string $commentedSql SQL query with debugging/trace comment
1255 * @param bool $isPermWrite Whether the query is a (non-temporary table) write
1256 * @param string $fname Name of the calling function
1257 * @param int $flags Bit field of class QUERY_* constants
1258 * @return array An n-tuple of:
1259 * - mixed|bool: An object, resource, or true on success; false on failure
1260 * - string: The result of calling lastError()
1261 * - int: The result of calling lastErrno()
1262 * - bool: Whether a statement rollback error occured
1263 * - bool: Whether a disconnect *both* happened *and* was recoverable
1264 * - bool: Whether a reconnection attempt was *both* made *and* succeeded
1265 * @throws DBUnexpectedError
1267 private function executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags ) {
1268 $priorWritesPending = $this->writesOrCallbacksPending();
1270 if ( ( $flags & self
::QUERY_IGNORE_DBO_TRX
) == 0 ) {
1271 $this->beginIfImplied( $sql, $fname );
1274 // Keep track of whether the transaction has write queries pending
1275 if ( $isPermWrite ) {
1276 $this->lastWriteTime
= microtime( true );
1277 if ( $this->trxLevel() && !$this->trxDoneWrites
) {
1278 $this->trxDoneWrites
= true;
1279 $this->trxProfiler
->transactionWritingIn(
1280 $this->server
, $this->getDomainID(), $this->trxShortId
);
1284 $prefix = $this->getLBInfo( 'master' ) ?
'query-m: ' : 'query: ';
1285 $generalizedSql = new GeneralizedSql( $sql, $this->trxShortId
, $prefix );
1287 $startTime = microtime( true );
1288 $ps = $this->profiler
1289 ?
( $this->profiler
)( $generalizedSql->stringify() )
1291 $this->affectedRowCount
= null;
1292 $this->lastQuery
= $sql;
1293 $ret = $this->doQuery( $commentedSql );
1294 $lastError = $this->lastError();
1295 $lastErrno = $this->lastErrno();
1297 $this->affectedRowCount
= $this->affectedRows();
1298 unset( $ps ); // profile out (if set)
1299 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1301 $recoverableSR = false; // recoverable statement rollback?
1302 $recoverableCL = false; // recoverable connection loss?
1303 $reconnected = false; // reconnection both attempted and succeeded?
1305 if ( $ret !== false ) {
1306 $this->lastPing
= $startTime;
1307 if ( $isPermWrite && $this->trxLevel() ) {
1308 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1309 $this->trxWriteCallers
[] = $fname;
1311 } elseif ( $this->wasConnectionError( $lastErrno ) ) {
1312 # Check if no meaningful session state was lost
1313 $recoverableCL = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1314 # Update session state tracking and try to restore the connection
1315 $reconnected = $this->replaceLostConnection( __METHOD__
);
1317 # Check if only the last query was rolled back
1318 $recoverableSR = $this->wasKnownStatementRollbackError();
1321 if ( $sql === self
::$PING_QUERY ) {
1322 $this->lastRoundTripEstimate
= $queryRuntime;
1325 $this->trxProfiler
->recordQueryCompletion(
1329 $isPermWrite ?
$this->affectedRows() : $this->numRows( $ret )
1332 // Avoid the overhead of logging calls unless debug mode is enabled
1333 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
1334 $this->queryLogger
->debug(
1335 "{method} [{runtime}s] {db_host}: $sql",
1338 'db_host' => $this->getServer(),
1339 'domain' => $this->getDomainID(),
1340 'runtime' => round( $queryRuntime, 3 )
1345 return [ $ret, $lastError, $lastErrno, $recoverableSR, $recoverableCL, $reconnected ];
1349 * Start an implicit transaction if DBO_TRX is enabled and no transaction is active
1351 * @param string $sql
1352 * @param string $fname
1354 private function beginIfImplied( $sql, $fname ) {
1356 !$this->trxLevel() &&
1357 $this->getFlag( self
::DBO_TRX
) &&
1358 $this->isTransactableQuery( $sql )
1360 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
1361 $this->trxAutomatic
= true;
1366 * Update the estimated run-time of a query, not counting large row lock times
1368 * LoadBalancer can be set to rollback transactions that will create huge replication
1369 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1370 * queries, like inserting a row can take a long time due to row locking. This method
1371 * uses some simple heuristics to discount those cases.
1373 * @param string $sql A SQL write query
1374 * @param float $runtime Total runtime, including RTT
1375 * @param int $affected Affected row count
1377 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1378 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1379 $indicativeOfReplicaRuntime = true;
1380 if ( $runtime > self
::$SLOW_WRITE_SEC ) {
1381 $verb = $this->getQueryVerb( $sql );
1382 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1383 if ( $verb === 'INSERT' ) {
1384 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::$SMALL_WRITE_ROWS;
1385 } elseif ( $verb === 'REPLACE' ) {
1386 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::$SMALL_WRITE_ROWS / 2;
1390 $this->trxWriteDuration +
= $runtime;
1391 $this->trxWriteQueryCount +
= 1;
1392 $this->trxWriteAffectedRows +
= $affected;
1393 if ( $indicativeOfReplicaRuntime ) {
1394 $this->trxWriteAdjDuration +
= $runtime;
1395 $this->trxWriteAdjQueryCount +
= 1;
1400 * Error out if the DB is not in a valid state for a query via query()
1402 * @param string $sql
1403 * @param string $fname
1404 * @throws DBTransactionStateError
1406 private function assertQueryIsCurrentlyAllowed( $sql, $fname ) {
1407 $verb = $this->getQueryVerb( $sql );
1408 if ( $verb === 'USE' ) {
1409 throw new DBUnexpectedError( $this, "Got USE query; use selectDomain() instead" );
1412 if ( $verb === 'ROLLBACK' ) { // transaction/savepoint
1416 if ( $this->trxStatus
< self
::STATUS_TRX_OK
) {
1417 throw new DBTransactionStateError(
1419 "Cannot execute query from $fname while transaction status is ERROR",
1421 $this->trxStatusCause
1423 } elseif ( $this->trxStatus
=== self
::STATUS_TRX_OK
&& $this->trxStatusIgnoredCause
) {
1424 list( $iLastError, $iLastErrno, $iFname ) = $this->trxStatusIgnoredCause
;
1425 call_user_func( $this->deprecationLogger
,
1426 "Caller from $fname ignored an error originally raised from $iFname: " .
1427 "[$iLastErrno] $iLastError"
1429 $this->trxStatusIgnoredCause
= null;
1433 public function assertNoOpenTransactions() {
1434 if ( $this->explicitTrxActive() ) {
1435 throw new DBTransactionError(
1437 "Explicit transaction still active. A caller may have caught an error. "
1438 . "Open transactions: " . $this->flatAtomicSectionList()
1444 * Determine whether it is safe to retry queries after a database connection is lost
1446 * @param string $sql SQL query
1447 * @param bool $priorWritesPending Whether there is a transaction open with
1448 * possible write queries or transaction pre-commit/idle callbacks
1449 * waiting on it to finish.
1450 * @return bool True if it is safe to retry the query, false otherwise
1452 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1453 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1454 # Dropped connections also mean that named locks are automatically released.
1455 # Only allow error suppression in autocommit mode or when the lost transaction
1456 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1457 if ( $this->sessionNamedLocks
) {
1458 return false; // possible critical section violation
1459 } elseif ( $this->sessionTempTables
) {
1460 return false; // tables might be queried latter
1461 } elseif ( $sql === 'COMMIT' ) {
1462 return !$priorWritesPending; // nothing written anyway? (T127428)
1463 } elseif ( $sql === 'ROLLBACK' ) {
1464 return true; // transaction lost...which is also what was requested :)
1465 } elseif ( $this->explicitTrxActive() ) {
1466 return false; // don't drop atomocity and explicit snapshots
1467 } elseif ( $priorWritesPending ) {
1468 return false; // prior writes lost from implicit transaction
1475 * Clean things up after session (and thus transaction) loss before reconnect
1477 private function handleSessionLossPreconnect() {
1478 // Clean up tracking of session-level things...
1479 // https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
1480 // https://www.postgresql.org/docs/9.2/static/sql-createtable.html (ignoring ON COMMIT)
1481 $this->sessionTempTables
= [];
1482 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1483 // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1484 $this->sessionNamedLocks
= [];
1485 // Session loss implies transaction loss
1486 $oldTrxShortId = $this->consumeTrxShortId();
1487 $this->trxAtomicCounter
= 0;
1488 $this->trxIdleCallbacks
= []; // T67263; transaction already lost
1489 $this->trxPreCommitCallbacks
= []; // T67263; transaction already lost
1490 // @note: leave trxRecurringCallbacks in place
1491 if ( $this->trxDoneWrites
) {
1492 $this->trxProfiler
->transactionWritingOut(
1494 $this->getDomainID(),
1496 $this->pendingWriteQueryDuration( self
::ESTIMATE_TOTAL
),
1497 $this->trxWriteAffectedRows
1503 * Clean things up after session (and thus transaction) loss after reconnect
1505 private function handleSessionLossPostconnect() {
1507 // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
1508 // If callback suppression is set then the array will remain unhandled.
1509 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1510 } catch ( Exception
$ex ) {
1511 // Already logged; move on...
1514 // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener()
1515 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1516 } catch ( Exception
$ex ) {
1517 // Already logged; move on...
1522 * Reset the transaction ID and return the old one
1524 * @return string The old transaction ID or the empty string if there wasn't one
1526 private function consumeTrxShortId() {
1527 $old = $this->trxShortId
;
1528 $this->trxShortId
= '';
1534 * Checks whether the cause of the error is detected to be a timeout.
1536 * It returns false by default, and not all engines support detecting this yet.
1537 * If this returns false, it will be treated as a generic query error.
1539 * @param string $error Error text
1540 * @param int $errno Error number
1543 protected function wasQueryTimeout( $error, $errno ) {
1548 * Report a query error. Log the error, and if neither the object ignore
1549 * flag nor the $ignoreErrors flag is set, throw a DBQueryError.
1551 * @param string $error
1553 * @param string $sql
1554 * @param string $fname
1555 * @param bool $ignore
1556 * @throws DBQueryError
1558 public function reportQueryError( $error, $errno, $sql, $fname, $ignore = false ) {
1560 $this->queryLogger
->debug( "SQL ERROR (ignored): $error" );
1562 throw $this->getQueryExceptionAndLog( $error, $errno, $sql, $fname );
1567 * @param string $error
1568 * @param string|int $errno
1569 * @param string $sql
1570 * @param string $fname
1573 private function getQueryExceptionAndLog( $error, $errno, $sql, $fname ) {
1574 $this->queryLogger
->error(
1575 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1576 $this->getLogContext( [
1577 'method' => __METHOD__
,
1580 'sql1line' => mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 ),
1582 'trace' => ( new RuntimeException() )->getTraceAsString()
1586 if ( $this->wasQueryTimeout( $error, $errno ) ) {
1587 $e = new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1588 } elseif ( $this->wasConnectionError( $errno ) ) {
1589 $e = new DBQueryDisconnectedError( $this, $error, $errno, $sql, $fname );
1591 $e = new DBQueryError( $this, $error, $errno, $sql, $fname );
1598 * @param string $error
1599 * @return DBConnectionError
1601 final protected function newExceptionAfterConnectError( $error ) {
1602 // Connection was not fully initialized and is not safe for use
1605 $this->connLogger
->error(
1606 "Error connecting to {db_server} as user {db_user}: {error}",
1607 $this->getLogContext( [
1609 'trace' => ( new RuntimeException() )->getTraceAsString()
1613 return new DBConnectionError( $this, $error );
1616 public function freeResult( $res ) {
1619 public function selectField(
1620 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1622 if ( $var === '*' ) { // sanity
1623 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1626 if ( !is_array( $options ) ) {
1627 $options = [ $options ];
1630 $options['LIMIT'] = 1;
1632 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1633 if ( $res === false ) {
1634 throw new DBUnexpectedError( $this, "Got false from select()" );
1637 $row = $this->fetchRow( $res );
1638 if ( $row === false ) {
1642 return reset( $row );
1645 public function selectFieldValues(
1646 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1648 if ( $var === '*' ) { // sanity
1649 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1650 } elseif ( !is_string( $var ) ) { // sanity
1651 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1654 if ( !is_array( $options ) ) {
1655 $options = [ $options ];
1658 $res = $this->select( $table, [ 'value' => $var ], $cond, $fname, $options, $join_conds );
1659 if ( $res === false ) {
1660 throw new DBUnexpectedError( $this, "Got false from select()" );
1664 foreach ( $res as $row ) {
1665 $values[] = $row->value
;
1672 * Returns an optional USE INDEX clause to go after the table, and a
1673 * string to go at the end of the query.
1675 * @param array $options Associative array of options to be turned into
1676 * an SQL query, valid keys are listed in the function.
1678 * @see Database::select()
1680 protected function makeSelectOptions( $options ) {
1681 $preLimitTail = $postLimitTail = '';
1686 foreach ( $options as $key => $option ) {
1687 if ( is_numeric( $key ) ) {
1688 $noKeyOptions[$option] = true;
1692 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1694 $preLimitTail .= $this->makeOrderBy( $options );
1696 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1697 $postLimitTail .= ' FOR UPDATE';
1700 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1701 $postLimitTail .= ' LOCK IN SHARE MODE';
1704 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1705 $startOpts .= 'DISTINCT';
1708 # Various MySQL extensions
1709 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1710 $startOpts .= ' /*! STRAIGHT_JOIN */';
1713 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1714 $startOpts .= ' SQL_BIG_RESULT';
1717 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1718 $startOpts .= ' SQL_BUFFER_RESULT';
1721 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1722 $startOpts .= ' SQL_SMALL_RESULT';
1725 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1726 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1729 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1730 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1734 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1735 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1740 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1744 * Returns an optional GROUP BY with an optional HAVING
1746 * @param array $options Associative array of options
1748 * @see Database::select()
1751 protected function makeGroupByWithHaving( $options ) {
1753 if ( isset( $options['GROUP BY'] ) ) {
1754 $gb = is_array( $options['GROUP BY'] )
1755 ?
implode( ',', $options['GROUP BY'] )
1756 : $options['GROUP BY'];
1757 $sql .= ' GROUP BY ' . $gb;
1759 if ( isset( $options['HAVING'] ) ) {
1760 $having = is_array( $options['HAVING'] )
1761 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1762 : $options['HAVING'];
1763 $sql .= ' HAVING ' . $having;
1770 * Returns an optional ORDER BY
1772 * @param array $options Associative array of options
1774 * @see Database::select()
1777 protected function makeOrderBy( $options ) {
1778 if ( isset( $options['ORDER BY'] ) ) {
1779 $ob = is_array( $options['ORDER BY'] )
1780 ?
implode( ',', $options['ORDER BY'] )
1781 : $options['ORDER BY'];
1783 return ' ORDER BY ' . $ob;
1789 public function select(
1790 $table, $vars, $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1792 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1794 return $this->query( $sql, $fname );
1797 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1798 $options = [], $join_conds = []
1800 if ( is_array( $vars ) ) {
1801 $fields = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1806 $options = (array)$options;
1807 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1808 ?
$options['USE INDEX']
1811 isset( $options['IGNORE INDEX'] ) &&
1812 is_array( $options['IGNORE INDEX'] )
1814 ?
$options['IGNORE INDEX']
1818 $this->selectOptionsIncludeLocking( $options ) &&
1819 $this->selectFieldsOrOptionsAggregate( $vars, $options )
1821 // Some DB types (e.g. postgres) disallow FOR UPDATE with aggregate
1822 // functions. Discourage use of such queries to encourage compatibility.
1824 $this->deprecationLogger
,
1825 __METHOD__
. ": aggregation used with a locking SELECT ($fname)"
1829 if ( is_array( $table ) ) {
1831 $this->tableNamesWithIndexClauseOrJOIN(
1832 $table, $useIndexes, $ignoreIndexes, $join_conds );
1833 } elseif ( $table != '' ) {
1835 $this->tableNamesWithIndexClauseOrJOIN(
1836 [ $table ], $useIndexes, $ignoreIndexes, [] );
1841 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1842 $this->makeSelectOptions( $options );
1844 if ( is_array( $conds ) ) {
1845 $conds = $this->makeList( $conds, self
::LIST_AND
);
1848 if ( $conds === null ||
$conds === false ) {
1849 $this->queryLogger
->warning(
1853 . ' with incorrect parameters: $conds must be a string or an array'
1858 if ( $conds === '' ||
$conds === '*' ) {
1859 $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex $preLimitTail";
1860 } elseif ( is_string( $conds ) ) {
1861 $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex " .
1862 "WHERE $conds $preLimitTail";
1864 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1867 if ( isset( $options['LIMIT'] ) ) {
1868 $sql = $this->limitResult( $sql, $options['LIMIT'],
1869 $options['OFFSET'] ??
false );
1871 $sql = "$sql $postLimitTail";
1873 if ( isset( $options['EXPLAIN'] ) ) {
1874 $sql = 'EXPLAIN ' . $sql;
1880 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1881 $options = [], $join_conds = []
1883 $options = (array)$options;
1884 $options['LIMIT'] = 1;
1886 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1887 if ( $res === false ) {
1888 throw new DBUnexpectedError( $this, "Got false from select()" );
1891 if ( !$this->numRows( $res ) ) {
1895 return $this->fetchObject( $res );
1898 public function estimateRowCount(
1899 $table, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1901 $conds = $this->normalizeConditions( $conds, $fname );
1902 $column = $this->extractSingleFieldFromList( $var );
1903 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1904 $conds[] = "$column IS NOT NULL";
1907 $res = $this->select(
1908 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1910 $row = $res ?
$this->fetchRow( $res ) : [];
1912 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1915 public function selectRowCount(
1916 $tables, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1918 $conds = $this->normalizeConditions( $conds, $fname );
1919 $column = $this->extractSingleFieldFromList( $var );
1920 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1921 $conds[] = "$column IS NOT NULL";
1924 $res = $this->select(
1926 'tmp_count' => $this->buildSelectSubquery(
1935 [ 'rowcount' => 'COUNT(*)' ],
1939 $row = $res ?
$this->fetchRow( $res ) : [];
1941 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1945 * @param string|array $options
1948 private function selectOptionsIncludeLocking( $options ) {
1949 $options = (array)$options;
1950 foreach ( [ 'FOR UPDATE', 'LOCK IN SHARE MODE' ] as $lock ) {
1951 if ( in_array( $lock, $options, true ) ) {
1960 * @param array|string $fields
1961 * @param array|string $options
1964 private function selectFieldsOrOptionsAggregate( $fields, $options ) {
1965 foreach ( (array)$options as $key => $value ) {
1966 if ( is_string( $key ) ) {
1967 if ( preg_match( '/^(?:GROUP BY|HAVING)$/i', $key ) ) {
1970 } elseif ( is_string( $value ) ) {
1971 if ( preg_match( '/^(?:DISTINCT|DISTINCTROW)$/i', $value ) ) {
1977 $regex = '/^(?:COUNT|MIN|MAX|SUM|GROUP_CONCAT|LISTAGG|ARRAY_AGG)\s*\\(/i';
1978 foreach ( (array)$fields as $field ) {
1979 if ( is_string( $field ) && preg_match( $regex, $field ) ) {
1988 * @param array|string $conds
1989 * @param string $fname
1992 final protected function normalizeConditions( $conds, $fname ) {
1993 if ( $conds === null ||
$conds === false ) {
1994 $this->queryLogger
->warning(
1998 . ' with incorrect parameters: $conds must be a string or an array'
2003 if ( !is_array( $conds ) ) {
2004 $conds = ( $conds === '' ) ?
[] : [ $conds ];
2011 * @param array|string $var Field parameter in the style of select()
2012 * @return string|null Column name or null; ignores aliases
2013 * @throws DBUnexpectedError Errors out if multiple columns are given
2015 final protected function extractSingleFieldFromList( $var ) {
2016 if ( is_array( $var ) ) {
2019 } elseif ( count( $var ) == 1 ) {
2020 $column = $var[0] ??
reset( $var );
2022 throw new DBUnexpectedError( $this, __METHOD__
. ': got multiple columns' );
2031 public function lockForUpdate(
2032 $table, $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
2034 if ( !$this->trxLevel() && !$this->getFlag( self
::DBO_TRX
) ) {
2035 throw new DBUnexpectedError(
2037 __METHOD__
. ': no transaction is active nor is DBO_TRX set'
2041 $options = (array)$options;
2042 $options[] = 'FOR UPDATE';
2044 return $this->selectRowCount( $table, '*', $conds, $fname, $options, $join_conds );
2047 public function fieldExists( $table, $field, $fname = __METHOD__
) {
2048 $info = $this->fieldInfo( $table, $field );
2053 public function indexExists( $table, $index, $fname = __METHOD__
) {
2054 if ( !$this->tableExists( $table ) ) {
2058 $info = $this->indexInfo( $table, $index, $fname );
2059 if ( is_null( $info ) ) {
2062 return $info !== false;
2066 abstract public function tableExists( $table, $fname = __METHOD__
);
2068 public function indexUnique( $table, $index ) {
2069 $indexInfo = $this->indexInfo( $table, $index );
2071 if ( !$indexInfo ) {
2075 return !$indexInfo[0]->Non_unique
;
2079 * Helper for Database::insert().
2081 * @param array $options
2084 protected function makeInsertOptions( $options ) {
2085 return implode( ' ', $options );
2088 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
2089 # No rows to insert, easy just return now
2090 if ( !count( $a ) ) {
2094 $table = $this->tableName( $table );
2096 if ( !is_array( $options ) ) {
2097 $options = [ $options ];
2100 $options = $this->makeInsertOptions( $options );
2102 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
2104 $keys = array_keys( $a[0] );
2107 $keys = array_keys( $a );
2110 $sql = 'INSERT ' . $options .
2111 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
2115 foreach ( $a as $row ) {
2121 $sql .= '(' . $this->makeList( $row ) . ')';
2124 $sql .= '(' . $this->makeList( $a ) . ')';
2127 $this->query( $sql, $fname );
2133 * Make UPDATE options array for Database::makeUpdateOptions
2135 * @param array $options
2138 protected function makeUpdateOptionsArray( $options ) {
2139 if ( !is_array( $options ) ) {
2140 $options = [ $options ];
2145 if ( in_array( 'IGNORE', $options ) ) {
2153 * Make UPDATE options for the Database::update function
2155 * @param array $options The options passed to Database::update
2158 protected function makeUpdateOptions( $options ) {
2159 $opts = $this->makeUpdateOptionsArray( $options );
2161 return implode( ' ', $opts );
2164 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
2165 $table = $this->tableName( $table );
2166 $opts = $this->makeUpdateOptions( $options );
2167 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
2169 if ( $conds !== [] && $conds !== '*' ) {
2170 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
2173 $this->query( $sql, $fname );
2178 public function makeList( $a, $mode = self
::LIST_COMMA
) {
2179 if ( !is_array( $a ) ) {
2180 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
2186 foreach ( $a as $field => $value ) {
2188 if ( $mode == self
::LIST_AND
) {
2190 } elseif ( $mode == self
::LIST_OR
) {
2199 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
2200 $list .= "($value)";
2201 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
2204 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
2206 // Remove null from array to be handled separately if found
2207 $includeNull = false;
2208 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2209 $includeNull = true;
2210 unset( $value[$nullKey] );
2212 if ( count( $value ) == 0 && !$includeNull ) {
2213 throw new InvalidArgumentException(
2214 __METHOD__
. ": empty input for field $field" );
2215 } elseif ( count( $value ) == 0 ) {
2216 // only check if $field is null
2217 $list .= "$field IS NULL";
2219 // IN clause contains at least one valid element
2220 if ( $includeNull ) {
2221 // Group subconditions to ensure correct precedence
2224 if ( count( $value ) == 1 ) {
2225 // Special-case single values, as IN isn't terribly efficient
2226 // Don't necessarily assume the single key is 0; we don't
2227 // enforce linear numeric ordering on other arrays here.
2228 $value = array_values( $value )[0];
2229 $list .= $field . " = " . $this->addQuotes( $value );
2231 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2233 // if null present in array, append IS NULL
2234 if ( $includeNull ) {
2235 $list .= " OR $field IS NULL)";
2238 } elseif ( $value === null ) {
2239 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
2240 $list .= "$field IS ";
2241 } elseif ( $mode == self
::LIST_SET
) {
2242 $list .= "$field = ";
2247 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
2249 $list .= "$field = ";
2251 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
2258 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2261 foreach ( $data as $base => $sub ) {
2262 if ( count( $sub ) ) {
2263 $conds[] = $this->makeList(
2264 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
2270 return $this->makeList( $conds, self
::LIST_OR
);
2272 // Nothing to search for...
2277 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2281 public function bitNot( $field ) {
2285 public function bitAnd( $fieldLeft, $fieldRight ) {
2286 return "($fieldLeft & $fieldRight)";
2289 public function bitOr( $fieldLeft, $fieldRight ) {
2290 return "($fieldLeft | $fieldRight)";
2293 public function buildConcat( $stringList ) {
2294 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2297 public function buildGroupConcatField(
2298 $delim, $table, $field, $conds = '', $join_conds = []
2300 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2302 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
2305 public function buildSubstring( $input, $startPosition, $length = null ) {
2306 $this->assertBuildSubstringParams( $startPosition, $length );
2307 $functionBody = "$input FROM $startPosition";
2308 if ( $length !== null ) {
2309 $functionBody .= " FOR $length";
2311 return 'SUBSTRING(' . $functionBody . ')';
2315 * Check type and bounds for parameters to self::buildSubstring()
2317 * All supported databases have substring functions that behave the same for
2318 * positive $startPosition and non-negative $length, but behaviors differ when
2319 * given 0 or negative $startPosition or negative $length. The simplest
2320 * solution to that is to just forbid those values.
2322 * @param int $startPosition
2323 * @param int|null $length
2326 protected function assertBuildSubstringParams( $startPosition, $length ) {
2327 if ( !is_int( $startPosition ) ||
$startPosition <= 0 ) {
2328 throw new InvalidArgumentException(
2329 '$startPosition must be a positive integer'
2332 if ( !( is_int( $length ) && $length >= 0 ||
$length === null ) ) {
2333 throw new InvalidArgumentException(
2334 '$length must be null or an integer greater than or equal to 0'
2339 public function buildStringCast( $field ) {
2340 // In theory this should work for any standards-compliant
2341 // SQL implementation, although it may not be the best way to do it.
2342 return "CAST( $field AS CHARACTER )";
2345 public function buildIntegerCast( $field ) {
2346 return 'CAST( ' . $field . ' AS INTEGER )';
2349 public function buildSelectSubquery(
2350 $table, $vars, $conds = '', $fname = __METHOD__
,
2351 $options = [], $join_conds = []
2353 return new Subquery(
2354 $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2358 public function databasesAreIndependent() {
2362 final public function selectDB( $db ) {
2363 $this->selectDomain( new DatabaseDomain(
2365 $this->currentDomain
->getSchema(),
2366 $this->currentDomain
->getTablePrefix()
2372 final public function selectDomain( $domain ) {
2373 $this->doSelectDomain( DatabaseDomain
::newFromId( $domain ) );
2377 * @param DatabaseDomain $domain
2378 * @throws DBConnectionError
2382 protected function doSelectDomain( DatabaseDomain
$domain ) {
2383 $this->currentDomain
= $domain;
2386 public function getDBname() {
2387 return $this->currentDomain
->getDatabase();
2390 public function getServer() {
2391 return $this->server
;
2394 public function tableName( $name, $format = 'quoted' ) {
2395 if ( $name instanceof Subquery
) {
2396 throw new DBUnexpectedError(
2398 __METHOD__
. ': got Subquery instance when expecting a string'
2402 # Skip the entire process when we have a string quoted on both ends.
2403 # Note that we check the end so that we will still quote any use of
2404 # use of `database`.table. But won't break things if someone wants
2405 # to query a database table with a dot in the name.
2406 if ( $this->isQuotedIdentifier( $name ) ) {
2410 # Lets test for any bits of text that should never show up in a table
2411 # name. Basically anything like JOIN or ON which are actually part of
2412 # SQL queries, but may end up inside of the table value to combine
2413 # sql. Such as how the API is doing.
2414 # Note that we use a whitespace test rather than a \b test to avoid
2415 # any remote case where a word like on may be inside of a table name
2416 # surrounded by symbols which may be considered word breaks.
2417 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2418 $this->queryLogger
->warning(
2419 __METHOD__
. ": use of subqueries is not supported this way",
2420 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
2426 # Split database and table into proper variables.
2427 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2429 # Quote $table and apply the prefix if not quoted.
2430 # $tableName might be empty if this is called from Database::replaceVars()
2431 $tableName = "{$prefix}{$table}";
2432 if ( $format === 'quoted'
2433 && !$this->isQuotedIdentifier( $tableName )
2434 && $tableName !== ''
2436 $tableName = $this->addIdentifierQuotes( $tableName );
2439 # Quote $schema and $database and merge them with the table name if needed
2440 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2441 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2447 * Get the table components needed for a query given the currently selected database
2449 * @param string $name Table name in the form of db.schema.table, db.table, or table
2450 * @return array (DB name or "" for default, schema name, table prefix, table name)
2452 protected function qualifiedTableComponents( $name ) {
2453 # We reverse the explode so that database.table and table both output the correct table.
2454 $dbDetails = explode( '.', $name, 3 );
2455 if ( count( $dbDetails ) == 3 ) {
2456 list( $database, $schema, $table ) = $dbDetails;
2457 # We don't want any prefix added in this case
2459 } elseif ( count( $dbDetails ) == 2 ) {
2460 list( $database, $table ) = $dbDetails;
2461 # We don't want any prefix added in this case
2463 # In dbs that support it, $database may actually be the schema
2464 # but that doesn't affect any of the functionality here
2467 list( $table ) = $dbDetails;
2468 if ( isset( $this->tableAliases
[$table] ) ) {
2469 $database = $this->tableAliases
[$table]['dbname'];
2470 $schema = is_string( $this->tableAliases
[$table]['schema'] )
2471 ?
$this->tableAliases
[$table]['schema']
2472 : $this->relationSchemaQualifier();
2473 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
2474 ?
$this->tableAliases
[$table]['prefix']
2475 : $this->tablePrefix();
2478 $schema = $this->relationSchemaQualifier(); # Default schema
2479 $prefix = $this->tablePrefix(); # Default prefix
2483 return [ $database, $schema, $prefix, $table ];
2487 * @param string|null $namespace Database or schema
2488 * @param string $relation Name of table, view, sequence, etc...
2489 * @param string $format One of (raw, quoted)
2490 * @return string Relation name with quoted and merged $namespace as needed
2492 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2493 if ( strlen( $namespace ) ) {
2494 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2495 $namespace = $this->addIdentifierQuotes( $namespace );
2497 $relation = $namespace . '.' . $relation;
2503 public function tableNames() {
2504 $inArray = func_get_args();
2507 foreach ( $inArray as $name ) {
2508 $retVal[$name] = $this->tableName( $name );
2514 public function tableNamesN() {
2515 $inArray = func_get_args();
2518 foreach ( $inArray as $name ) {
2519 $retVal[] = $this->tableName( $name );
2526 * Get an aliased table name
2528 * This returns strings like "tableName AS newTableName" for aliased tables
2529 * and "(SELECT * from tableA) newTablename" for subqueries (e.g. derived tables)
2531 * @see Database::tableName()
2532 * @param string|Subquery $table Table name or object with a 'sql' field
2533 * @param string|bool $alias Table alias (optional)
2534 * @return string SQL name for aliased table. Will not alias a table to its own name
2536 protected function tableNameWithAlias( $table, $alias = false ) {
2537 if ( is_string( $table ) ) {
2538 $quotedTable = $this->tableName( $table );
2539 } elseif ( $table instanceof Subquery
) {
2540 $quotedTable = (string)$table;
2542 throw new InvalidArgumentException( "Table must be a string or Subquery" );
2545 if ( $alias === false ||
$alias === $table ) {
2546 if ( $table instanceof Subquery
) {
2547 throw new InvalidArgumentException( "Subquery table missing alias" );
2550 return $quotedTable;
2552 return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2557 * Gets an array of aliased table names
2559 * @param array $tables [ [alias] => table ]
2560 * @return string[] See tableNameWithAlias()
2562 protected function tableNamesWithAlias( $tables ) {
2564 foreach ( $tables as $alias => $table ) {
2565 if ( is_numeric( $alias ) ) {
2568 $retval[] = $this->tableNameWithAlias( $table, $alias );
2575 * Get an aliased field name
2576 * e.g. fieldName AS newFieldName
2578 * @param string $name Field name
2579 * @param string|bool $alias Alias (optional)
2580 * @return string SQL name for aliased field. Will not alias a field to its own name
2582 protected function fieldNameWithAlias( $name, $alias = false ) {
2583 if ( !$alias ||
(string)$alias === (string)$name ) {
2586 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2591 * Gets an array of aliased field names
2593 * @param array $fields [ [alias] => field ]
2594 * @return string[] See fieldNameWithAlias()
2596 protected function fieldNamesWithAlias( $fields ) {
2598 foreach ( $fields as $alias => $field ) {
2599 if ( is_numeric( $alias ) ) {
2602 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2609 * Get the aliased table name clause for a FROM clause
2610 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2612 * @param array $tables ( [alias] => table )
2613 * @param array $use_index Same as for select()
2614 * @param array $ignore_index Same as for select()
2615 * @param array $join_conds Same as for select()
2618 protected function tableNamesWithIndexClauseOrJOIN(
2619 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2623 $use_index = (array)$use_index;
2624 $ignore_index = (array)$ignore_index;
2625 $join_conds = (array)$join_conds;
2627 foreach ( $tables as $alias => $table ) {
2628 if ( !is_string( $alias ) ) {
2629 // No alias? Set it equal to the table name
2633 if ( is_array( $table ) ) {
2634 // A parenthesized group
2635 if ( count( $table ) > 1 ) {
2636 $joinedTable = '(' .
2637 $this->tableNamesWithIndexClauseOrJOIN(
2638 $table, $use_index, $ignore_index, $join_conds ) . ')';
2641 $innerTable = reset( $table );
2642 $innerAlias = key( $table );
2643 $joinedTable = $this->tableNameWithAlias(
2645 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2649 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2652 // Is there a JOIN clause for this table?
2653 if ( isset( $join_conds[$alias] ) ) {
2654 list( $joinType, $conds ) = $join_conds[$alias];
2655 $tableClause = $joinType;
2656 $tableClause .= ' ' . $joinedTable;
2657 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2658 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2660 $tableClause .= ' ' . $use;
2663 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2664 $ignore = $this->ignoreIndexClause(
2665 implode( ',', (array)$ignore_index[$alias] ) );
2666 if ( $ignore != '' ) {
2667 $tableClause .= ' ' . $ignore;
2670 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2672 $tableClause .= ' ON (' . $on . ')';
2675 $retJOIN[] = $tableClause;
2676 } elseif ( isset( $use_index[$alias] ) ) {
2677 // Is there an INDEX clause for this table?
2678 $tableClause = $joinedTable;
2679 $tableClause .= ' ' . $this->useIndexClause(
2680 implode( ',', (array)$use_index[$alias] )
2683 $ret[] = $tableClause;
2684 } elseif ( isset( $ignore_index[$alias] ) ) {
2685 // Is there an INDEX clause for this table?
2686 $tableClause = $joinedTable;
2687 $tableClause .= ' ' . $this->ignoreIndexClause(
2688 implode( ',', (array)$ignore_index[$alias] )
2691 $ret[] = $tableClause;
2693 $tableClause = $joinedTable;
2695 $ret[] = $tableClause;
2699 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2700 $implicitJoins = implode( ',', $ret );
2701 $explicitJoins = implode( ' ', $retJOIN );
2703 // Compile our final table clause
2704 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2708 * Allows for index remapping in queries where this is not consistent across DBMS
2710 * @param string $index
2713 protected function indexName( $index ) {
2714 return $this->indexAliases
[$index] ??
$index;
2717 public function addQuotes( $s ) {
2718 if ( $s instanceof Blob
) {
2721 if ( $s === null ) {
2723 } elseif ( is_bool( $s ) ) {
2726 # This will also quote numeric values. This should be harmless,
2727 # and protects against weird problems that occur when they really
2728 # _are_ strings such as article titles and string->number->string
2729 # conversion is not 1:1.
2730 return "'" . $this->strencode( $s ) . "'";
2734 public function addIdentifierQuotes( $s ) {
2735 return '"' . str_replace( '"', '""', $s ) . '"';
2739 * Returns if the given identifier looks quoted or not according to
2740 * the database convention for quoting identifiers .
2742 * @note Do not use this to determine if untrusted input is safe.
2743 * A malicious user can trick this function.
2744 * @param string $name
2747 public function isQuotedIdentifier( $name ) {
2748 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2753 * @param string $escapeChar
2756 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2757 return str_replace( [ $escapeChar, '%', '_' ],
2758 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2762 public function buildLike( $param, ...$params ) {
2763 if ( is_array( $param ) ) {
2766 $params = func_get_args();
2771 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2772 // may escape backslashes, creating problems of double escaping. The `
2773 // character has good cross-DBMS compatibility, avoiding special operators
2774 // in MS SQL like ^ and %
2777 foreach ( $params as $value ) {
2778 if ( $value instanceof LikeMatch
) {
2779 $s .= $value->toString();
2781 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2786 $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2789 public function anyChar() {
2790 return new LikeMatch( '_' );
2793 public function anyString() {
2794 return new LikeMatch( '%' );
2797 public function nextSequenceValue( $seqName ) {
2802 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2803 * is only needed because a) MySQL must be as efficient as possible due to
2804 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2805 * which index to pick. Anyway, other databases might have different
2806 * indexes on a given table. So don't bother overriding this unless you're
2808 * @param string $index
2811 public function useIndexClause( $index ) {
2816 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2817 * is only needed because a) MySQL must be as efficient as possible due to
2818 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2819 * which index to pick. Anyway, other databases might have different
2820 * indexes on a given table. So don't bother overriding this unless you're
2822 * @param string $index
2825 public function ignoreIndexClause( $index ) {
2829 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2830 if ( count( $rows ) == 0 ) {
2834 $uniqueIndexes = (array)$uniqueIndexes;
2836 if ( !is_array( reset( $rows ) ) ) {
2841 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2842 $affectedRowCount = 0;
2843 foreach ( $rows as $row ) {
2844 // Delete rows which collide with this one
2845 $indexWhereClauses = [];
2846 foreach ( $uniqueIndexes as $index ) {
2847 $indexColumns = (array)$index;
2848 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2849 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2850 throw new DBUnexpectedError(
2852 'New record does not provide all values for unique key (' .
2853 implode( ', ', $indexColumns ) . ')'
2855 } elseif ( in_array( null, $indexRowValues, true ) ) {
2856 throw new DBUnexpectedError(
2858 'New record has a null value for unique key (' .
2859 implode( ', ', $indexColumns ) . ')'
2862 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2865 if ( $indexWhereClauses ) {
2866 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2867 $affectedRowCount +
= $this->affectedRows();
2870 // Now insert the row
2871 $this->insert( $table, $row, $fname );
2872 $affectedRowCount +
= $this->affectedRows();
2874 $this->endAtomic( $fname );
2875 $this->affectedRowCount
= $affectedRowCount;
2876 } catch ( Exception
$e ) {
2877 $this->cancelAtomic( $fname );
2883 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2886 * @param string $table Table name
2887 * @param array|string $rows Row(s) to insert
2888 * @param string $fname Caller function name
2890 protected function nativeReplace( $table, $rows, $fname ) {
2891 $table = $this->tableName( $table );
2894 if ( !is_array( reset( $rows ) ) ) {
2898 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2901 foreach ( $rows as $row ) {
2908 $sql .= '(' . $this->makeList( $row ) . ')';
2911 $this->query( $sql, $fname );
2914 public function upsert( $table, array $rows, $uniqueIndexes, array $set,
2917 if ( $rows === [] ) {
2918 return true; // nothing to do
2921 $uniqueIndexes = (array)$uniqueIndexes;
2922 if ( !is_array( reset( $rows ) ) ) {
2926 if ( count( $uniqueIndexes ) ) {
2927 $clauses = []; // list WHERE clauses that each identify a single row
2928 foreach ( $rows as $row ) {
2929 foreach ( $uniqueIndexes as $index ) {
2930 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2931 $rowKey = []; // unique key to this row
2932 foreach ( $index as $column ) {
2933 $rowKey[$column] = $row[$column];
2935 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2938 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2943 $affectedRowCount = 0;
2945 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2946 # Update any existing conflicting row(s)
2947 if ( $where !== false ) {
2948 $this->update( $table, $set, $where, $fname );
2949 $affectedRowCount +
= $this->affectedRows();
2951 # Now insert any non-conflicting row(s)
2952 $this->insert( $table, $rows, $fname, [ 'IGNORE' ] );
2953 $affectedRowCount +
= $this->affectedRows();
2954 $this->endAtomic( $fname );
2955 $this->affectedRowCount
= $affectedRowCount;
2956 } catch ( Exception
$e ) {
2957 $this->cancelAtomic( $fname );
2964 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2968 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2971 $delTable = $this->tableName( $delTable );
2972 $joinTable = $this->tableName( $joinTable );
2973 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2974 if ( $conds != '*' ) {
2975 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2979 $this->query( $sql, $fname );
2982 public function textFieldSize( $table, $field ) {
2983 $table = $this->tableName( $table );
2984 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\"";
2985 $res = $this->query( $sql, __METHOD__
);
2986 $row = $this->fetchObject( $res );
2990 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2999 public function delete( $table, $conds, $fname = __METHOD__
) {
3001 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
3004 $table = $this->tableName( $table );
3005 $sql = "DELETE FROM $table";
3007 if ( $conds != '*' ) {
3008 if ( is_array( $conds ) ) {
3009 $conds = $this->makeList( $conds, self
::LIST_AND
);
3011 $sql .= ' WHERE ' . $conds;
3014 $this->query( $sql, $fname );
3019 final public function insertSelect(
3020 $destTable, $srcTable, $varMap, $conds,
3021 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3023 static $hints = [ 'NO_AUTO_COLUMNS' ];
3025 $insertOptions = (array)$insertOptions;
3026 $selectOptions = (array)$selectOptions;
3028 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
3029 // For massive migrations with downtime, we don't want to select everything
3030 // into memory and OOM, so do all this native on the server side if possible.
3031 $this->nativeInsertSelect(
3037 array_diff( $insertOptions, $hints ),
3042 $this->nonNativeInsertSelect(
3048 array_diff( $insertOptions, $hints ),
3058 * @param array $insertOptions INSERT options
3059 * @param array $selectOptions SELECT options
3060 * @return bool Whether an INSERT SELECT with these options will be replication safe
3063 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
3068 * Implementation of insertSelect() based on select() and insert()
3070 * @see IDatabase::insertSelect()
3072 * @param string $destTable
3073 * @param string|array $srcTable
3074 * @param array $varMap
3075 * @param array $conds
3076 * @param string $fname
3077 * @param array $insertOptions
3078 * @param array $selectOptions
3079 * @param array $selectJoinConds
3081 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3082 $fname = __METHOD__
,
3083 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3085 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
3086 // on only the master (without needing row-based-replication). It also makes it easy to
3087 // know how big the INSERT is going to be.
3089 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
3090 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
3092 $selectOptions[] = 'FOR UPDATE';
3093 $res = $this->select(
3094 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
3101 $affectedRowCount = 0;
3102 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
3105 foreach ( $res as $row ) {
3106 $rows[] = (array)$row;
3108 // Avoid inserts that are too huge
3109 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
3110 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
3114 $affectedRowCount +
= $this->affectedRows();
3118 if ( $rows && $ok ) {
3119 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
3121 $affectedRowCount +
= $this->affectedRows();
3125 $this->endAtomic( $fname );
3126 $this->affectedRowCount
= $affectedRowCount;
3128 $this->cancelAtomic( $fname );
3130 } catch ( Exception
$e ) {
3131 $this->cancelAtomic( $fname );
3137 * Native server-side implementation of insertSelect() for situations where
3138 * we don't want to select everything into memory
3140 * @see IDatabase::insertSelect()
3141 * @param string $destTable
3142 * @param string|array $srcTable
3143 * @param array $varMap
3144 * @param array $conds
3145 * @param string $fname
3146 * @param array $insertOptions
3147 * @param array $selectOptions
3148 * @param array $selectJoinConds
3150 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3151 $fname = __METHOD__
,
3152 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3154 $destTable = $this->tableName( $destTable );
3156 if ( !is_array( $insertOptions ) ) {
3157 $insertOptions = [ $insertOptions ];
3160 $insertOptions = $this->makeInsertOptions( $insertOptions );
3162 $selectSql = $this->selectSQLText(
3164 array_values( $varMap ),
3171 $sql = "INSERT $insertOptions" .
3172 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
3175 $this->query( $sql, $fname );
3178 public function limitResult( $sql, $limit, $offset = false ) {
3179 if ( !is_numeric( $limit ) ) {
3180 throw new DBUnexpectedError(
3182 "Invalid non-numeric limit passed to " . __METHOD__
3185 // This version works in MySQL and SQLite. It will very likely need to be
3186 // overridden for most other RDBMS subclasses.
3187 return "$sql LIMIT "
3188 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3192 public function unionSupportsOrderAndLimit() {
3193 return true; // True for almost every DB supported
3196 public function unionQueries( $sqls, $all ) {
3197 $glue = $all ?
') UNION ALL (' : ') UNION (';
3199 return '(' . implode( $glue, $sqls ) . ')';
3202 public function unionConditionPermutations(
3203 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
3204 $options = [], $join_conds = []
3206 // First, build the Cartesian product of $permute_conds
3208 foreach ( $permute_conds as $field => $values ) {
3210 // Skip empty $values
3213 $values = array_unique( $values ); // For sanity
3215 foreach ( $conds as $cond ) {
3216 foreach ( $values as $value ) {
3217 $cond[$field] = $value;
3218 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
3224 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
3226 // If there's just one condition and no subordering, hand off to
3227 // selectSQLText directly.
3228 if ( count( $conds ) === 1 &&
3229 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
3231 return $this->selectSQLText(
3232 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
3236 // Otherwise, we need to pull out the order and limit to apply after
3237 // the union. Then build the SQL queries for each set of conditions in
3238 // $conds. Then union them together (using UNION ALL, because the
3239 // product *should* already be distinct).
3240 $orderBy = $this->makeOrderBy( $options );
3241 $limit = $options['LIMIT'] ??
null;
3242 $offset = $options['OFFSET'] ??
false;
3243 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
3244 if ( !$this->unionSupportsOrderAndLimit() ) {
3245 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
3247 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
3248 $options['ORDER BY'] = $options['INNER ORDER BY'];
3250 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
3251 // We need to increase the limit by the offset rather than
3252 // using the offset directly, otherwise it'll skip incorrectly
3253 // in the subqueries.
3254 $options['LIMIT'] = $limit +
$offset;
3255 unset( $options['OFFSET'] );
3260 foreach ( $conds as $cond ) {
3261 $sqls[] = $this->selectSQLText(
3262 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
3265 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
3266 if ( $limit !== null ) {
3267 $sql = $this->limitResult( $sql, $limit, $offset );
3273 public function conditional( $cond, $trueVal, $falseVal ) {
3274 if ( is_array( $cond ) ) {
3275 $cond = $this->makeList( $cond, self
::LIST_AND
);
3278 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3281 public function strreplace( $orig, $old, $new ) {
3282 return "REPLACE({$orig}, {$old}, {$new})";
3285 public function getServerUptime() {
3289 public function wasDeadlock() {
3293 public function wasLockTimeout() {
3297 public function wasConnectionLoss() {
3298 return $this->wasConnectionError( $this->lastErrno() );
3301 public function wasReadOnlyError() {
3305 public function wasErrorReissuable() {
3307 $this->wasDeadlock() ||
3308 $this->wasLockTimeout() ||
3309 $this->wasConnectionLoss()
3314 * Do not use this method outside of Database/DBError classes
3316 * @param int|string $errno
3317 * @return bool Whether the given query error was a connection drop
3319 public function wasConnectionError( $errno ) {
3324 * @return bool Whether it is known that the last query error only caused statement rollback
3325 * @note This is for backwards compatibility for callers catching DBError exceptions in
3326 * order to ignore problems like duplicate key errors or foriegn key violations
3329 protected function wasKnownStatementRollbackError() {
3330 return false; // don't know; it could have caused a transaction rollback
3333 public function deadlockLoop() {
3334 $args = func_get_args();
3335 $function = array_shift( $args );
3336 $tries = self
::$DEADLOCK_TRIES;
3338 $this->begin( __METHOD__
);
3341 /** @var Exception $e */
3345 $retVal = $function( ...$args );
3347 } catch ( DBQueryError
$e ) {
3348 if ( $this->wasDeadlock() ) {
3349 // Retry after a randomized delay
3350 usleep( mt_rand( self
::$DEADLOCK_DELAY_MIN, self
::$DEADLOCK_DELAY_MAX ) );
3352 // Throw the error back up
3356 } while ( --$tries > 0 );
3358 if ( $tries <= 0 ) {
3359 // Too many deadlocks; give up
3360 $this->rollback( __METHOD__
);
3363 $this->commit( __METHOD__
);
3369 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3370 # Real waits are implemented in the subclass.
3374 public function getReplicaPos() {
3379 public function getMasterPos() {
3384 public function serverIsReadOnly() {
3388 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
3389 if ( !$this->trxLevel() ) {
3390 throw new DBUnexpectedError( $this, "No transaction is active" );
3392 $this->trxEndCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3395 final public function onTransactionCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3396 if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
3397 // Start an implicit transaction similar to how query() does
3398 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3399 $this->trxAutomatic
= true;
3402 $this->trxIdleCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3403 if ( !$this->trxLevel() ) {
3404 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
3408 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
3409 $this->onTransactionCommitOrIdle( $callback, $fname );
3412 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3413 if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
3414 // Start an implicit transaction similar to how query() does
3415 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3416 $this->trxAutomatic
= true;
3419 if ( $this->trxLevel() ) {
3420 $this->trxPreCommitCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3422 // No transaction is active nor will start implicitly, so make one for this callback
3423 $this->startAtomic( __METHOD__
, self
::ATOMIC_CANCELABLE
);
3426 $this->endAtomic( __METHOD__
);
3427 } catch ( Exception
$e ) {
3428 $this->cancelAtomic( __METHOD__
);
3434 final public function onAtomicSectionCancel( callable
$callback, $fname = __METHOD__
) {
3435 if ( !$this->trxLevel() ||
!$this->trxAtomicLevels
) {
3436 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3438 $this->trxSectionCancelCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3442 * @return AtomicSectionIdentifier|null ID of the topmost atomic section level
3444 private function currentAtomicSectionId() {
3445 if ( $this->trxLevel() && $this->trxAtomicLevels
) {
3446 $levelInfo = end( $this->trxAtomicLevels
);
3448 return $levelInfo[1];
3455 * Hoist callback ownership for callbacks in a section to a parent section.
3456 * All callbacks should have an owner that is present in trxAtomicLevels.
3457 * @param AtomicSectionIdentifier $old
3458 * @param AtomicSectionIdentifier $new
3460 private function reassignCallbacksForSection(
3461 AtomicSectionIdentifier
$old, AtomicSectionIdentifier
$new
3463 foreach ( $this->trxPreCommitCallbacks
as $key => $info ) {
3464 if ( $info[2] === $old ) {
3465 $this->trxPreCommitCallbacks
[$key][2] = $new;
3468 foreach ( $this->trxIdleCallbacks
as $key => $info ) {
3469 if ( $info[2] === $old ) {
3470 $this->trxIdleCallbacks
[$key][2] = $new;
3473 foreach ( $this->trxEndCallbacks
as $key => $info ) {
3474 if ( $info[2] === $old ) {
3475 $this->trxEndCallbacks
[$key][2] = $new;
3478 foreach ( $this->trxSectionCancelCallbacks
as $key => $info ) {
3479 if ( $info[2] === $old ) {
3480 $this->trxSectionCancelCallbacks
[$key][2] = $new;
3486 * Update callbacks that were owned by cancelled atomic sections.
3488 * Callbacks for "on commit" should never be run if they're owned by a
3489 * section that won't be committed.
3491 * Callbacks for "on resolution" need to reflect that the section was
3492 * rolled back, even if the transaction as a whole commits successfully.
3494 * Callbacks for "on section cancel" should already have been consumed,
3495 * but errors during the cancellation itself can prevent that while still
3496 * destroying the section. Hoist any such callbacks to the new top section,
3497 * which we assume will itself have to be cancelled or rolled back to
3498 * resolve the error.
3500 * @param AtomicSectionIdentifier[] $sectionIds ID of an actual savepoint
3501 * @param AtomicSectionIdentifier|null $newSectionId New top section ID.
3502 * @throws UnexpectedValueException
3504 private function modifyCallbacksForCancel(
3505 array $sectionIds, AtomicSectionIdentifier
$newSectionId = null
3507 // Cancel the "on commit" callbacks owned by this savepoint
3508 $this->trxIdleCallbacks
= array_filter(
3509 $this->trxIdleCallbacks
,
3510 function ( $entry ) use ( $sectionIds ) {
3511 return !in_array( $entry[2], $sectionIds, true );
3514 $this->trxPreCommitCallbacks
= array_filter(
3515 $this->trxPreCommitCallbacks
,
3516 function ( $entry ) use ( $sectionIds ) {
3517 return !in_array( $entry[2], $sectionIds, true );
3520 // Make "on resolution" callbacks owned by this savepoint to perceive a rollback
3521 foreach ( $this->trxEndCallbacks
as $key => $entry ) {
3522 if ( in_array( $entry[2], $sectionIds, true ) ) {
3523 $callback = $entry[0];
3524 $this->trxEndCallbacks
[$key][0] = function () use ( $callback ) {
3525 // @phan-suppress-next-line PhanInfiniteRecursion No recursion at all here, phan is confused
3526 return $callback( self
::TRIGGER_ROLLBACK
, $this );
3528 // This "on resolution" callback no longer belongs to a section.
3529 $this->trxEndCallbacks
[$key][2] = null;
3532 // Hoist callback ownership for section cancel callbacks to the new top section
3533 foreach ( $this->trxSectionCancelCallbacks
as $key => $entry ) {
3534 if ( in_array( $entry[2], $sectionIds, true ) ) {
3535 $this->trxSectionCancelCallbacks
[$key][2] = $newSectionId;
3540 final public function setTransactionListener( $name, callable
$callback = null ) {
3542 $this->trxRecurringCallbacks
[$name] = $callback;
3544 unset( $this->trxRecurringCallbacks
[$name] );
3549 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
3551 * This method should not be used outside of Database/LoadBalancer
3553 * @param bool $suppress
3556 final public function setTrxEndCallbackSuppression( $suppress ) {
3557 $this->trxEndCallbacksSuppressed
= $suppress;
3561 * Actually consume and run any "on transaction idle/resolution" callbacks.
3563 * This method should not be used outside of Database/LoadBalancer
3565 * @param int $trigger IDatabase::TRIGGER_* constant
3566 * @return int Number of callbacks attempted
3570 public function runOnTransactionIdleCallbacks( $trigger ) {
3571 if ( $this->trxLevel() ) { // sanity
3572 throw new DBUnexpectedError( $this, __METHOD__
. ': a transaction is still open' );
3575 if ( $this->trxEndCallbacksSuppressed
) {
3580 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
3581 /** @var Exception $e */
3582 $e = null; // first exception
3583 do { // callbacks may add callbacks :)
3584 $callbacks = array_merge(
3585 $this->trxIdleCallbacks
,
3586 $this->trxEndCallbacks
// include "transaction resolution" callbacks
3588 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
3589 $this->trxEndCallbacks
= []; // consumed (recursion guard)
3591 // Only run trxSectionCancelCallbacks on rollback, not commit.
3592 // But always consume them.
3593 if ( $trigger === self
::TRIGGER_ROLLBACK
) {
3594 $callbacks = array_merge( $callbacks, $this->trxSectionCancelCallbacks
);
3596 $this->trxSectionCancelCallbacks
= []; // consumed (recursion guard)
3598 foreach ( $callbacks as $callback ) {
3600 list( $phpCallback ) = $callback;
3601 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
3603 // @phan-suppress-next-line PhanParamTooManyCallable
3604 call_user_func( $phpCallback, $trigger, $this );
3605 } catch ( Exception
$ex ) {
3606 call_user_func( $this->errorLogger
, $ex );
3608 // Some callbacks may use startAtomic/endAtomic, so make sure
3609 // their transactions are ended so other callbacks don't fail
3610 if ( $this->trxLevel() ) {
3611 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3615 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
3617 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
3621 } while ( count( $this->trxIdleCallbacks
) );
3623 if ( $e instanceof Exception
) {
3624 throw $e; // re-throw any first exception
3631 * Actually consume and run any "on transaction pre-commit" callbacks.
3633 * This method should not be used outside of Database/LoadBalancer
3636 * @return int Number of callbacks attempted
3639 public function runOnTransactionPreCommitCallbacks() {
3642 $e = null; // first exception
3643 do { // callbacks may add callbacks :)
3644 $callbacks = $this->trxPreCommitCallbacks
;
3645 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
3646 foreach ( $callbacks as $callback ) {
3649 list( $phpCallback ) = $callback;
3650 $phpCallback( $this );
3651 } catch ( Exception
$ex ) {
3652 ( $this->errorLogger
)( $ex );
3656 } while ( count( $this->trxPreCommitCallbacks
) );
3658 if ( $e instanceof Exception
) {
3659 throw $e; // re-throw any first exception
3666 * Actually run any "atomic section cancel" callbacks.
3668 * @param int $trigger IDatabase::TRIGGER_* constant
3669 * @param AtomicSectionIdentifier[]|null $sectionIds Section IDs to cancel,
3670 * null on transaction rollback
3672 private function runOnAtomicSectionCancelCallbacks(
3673 $trigger, array $sectionIds = null
3675 /** @var Exception|Throwable $e */
3676 $e = null; // first exception
3680 $callbacks = $this->trxSectionCancelCallbacks
;
3681 $this->trxSectionCancelCallbacks
= []; // consumed (recursion guard)
3682 foreach ( $callbacks as $entry ) {
3683 if ( $sectionIds === null ||
in_array( $entry[2], $sectionIds, true ) ) {
3685 $entry[0]( $trigger, $this );
3686 } catch ( Exception
$ex ) {
3687 ( $this->errorLogger
)( $ex );
3689 } catch ( Throwable
$ex ) {
3694 $notCancelled[] = $entry;
3697 } while ( count( $this->trxSectionCancelCallbacks
) );
3698 $this->trxSectionCancelCallbacks
= $notCancelled;
3700 if ( $e !== null ) {
3701 throw $e; // re-throw any first Exception/Throwable
3706 * Actually run any "transaction listener" callbacks.
3708 * This method should not be used outside of Database/LoadBalancer
3710 * @param int $trigger IDatabase::TRIGGER_* constant
3714 public function runTransactionListenerCallbacks( $trigger ) {
3715 if ( $this->trxEndCallbacksSuppressed
) {
3719 /** @var Exception $e */
3720 $e = null; // first exception
3722 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3724 $phpCallback( $trigger, $this );
3725 } catch ( Exception
$ex ) {
3726 ( $this->errorLogger
)( $ex );
3731 if ( $e instanceof Exception
) {
3732 throw $e; // re-throw any first exception
3737 * Create a savepoint
3739 * This is used internally to implement atomic sections. It should not be
3743 * @param string $identifier Identifier for the savepoint
3744 * @param string $fname Calling function name
3746 protected function doSavepoint( $identifier, $fname ) {
3747 $this->query( 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3751 * Release a savepoint
3753 * This is used internally to implement atomic sections. It should not be
3757 * @param string $identifier Identifier for the savepoint
3758 * @param string $fname Calling function name
3760 protected function doReleaseSavepoint( $identifier, $fname ) {
3761 $this->query( 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3765 * Rollback to a savepoint
3767 * This is used internally to implement atomic sections. It should not be
3771 * @param string $identifier Identifier for the savepoint
3772 * @param string $fname Calling function name
3774 protected function doRollbackToSavepoint( $identifier, $fname ) {
3775 $this->query( 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3779 * @param string $fname
3782 private function nextSavepointId( $fname ) {
3783 $savepointId = self
::$SAVEPOINT_PREFIX . ++
$this->trxAtomicCounter
;
3784 if ( strlen( $savepointId ) > 30 ) {
3785 // 30 == Oracle's identifier length limit (pre 12c)
3786 // With a 22 character prefix, that puts the highest number at 99999999.
3787 throw new DBUnexpectedError(
3789 'There have been an excessively large number of atomic sections in a transaction'
3790 . " started by $this->trxFname (at $fname)"
3794 return $savepointId;
3797 final public function startAtomic(
3798 $fname = __METHOD__
, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3800 $savepointId = $cancelable === self
::ATOMIC_CANCELABLE ? self
::$NOT_APPLICABLE : null;
3802 if ( !$this->trxLevel() ) {
3803 $this->begin( $fname, self
::TRANSACTION_INTERNAL
); // sets trxAutomatic
3804 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3805 // in all changes being in one transaction to keep requests transactional.
3806 if ( $this->getFlag( self
::DBO_TRX
) ) {
3807 // Since writes could happen in between the topmost atomic sections as part
3808 // of the transaction, those sections will need savepoints.
3809 $savepointId = $this->nextSavepointId( $fname );
3810 $this->doSavepoint( $savepointId, $fname );
3812 $this->trxAutomaticAtomic
= true;
3814 } elseif ( $cancelable === self
::ATOMIC_CANCELABLE
) {
3815 $savepointId = $this->nextSavepointId( $fname );
3816 $this->doSavepoint( $savepointId, $fname );
3819 $sectionId = new AtomicSectionIdentifier
;
3820 $this->trxAtomicLevels
[] = [ $fname, $sectionId, $savepointId ];
3821 $this->queryLogger
->debug( 'startAtomic: entering level ' .
3822 ( count( $this->trxAtomicLevels
) - 1 ) . " ($fname)" );
3827 final public function endAtomic( $fname = __METHOD__
) {
3828 if ( !$this->trxLevel() ||
!$this->trxAtomicLevels
) {
3829 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3832 // Check if the current section matches $fname
3833 $pos = count( $this->trxAtomicLevels
) - 1;
3834 list( $savedFname, $sectionId, $savepointId ) = $this->trxAtomicLevels
[$pos];
3835 $this->queryLogger
->debug( "endAtomic: leaving level $pos ($fname)" );
3837 if ( $savedFname !== $fname ) {
3838 throw new DBUnexpectedError(
3840 "Invalid atomic section ended (got $fname but expected $savedFname)"
3844 // Remove the last section (no need to re-index the array)
3845 array_pop( $this->trxAtomicLevels
);
3847 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3848 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3849 } elseif ( $savepointId !== null && $savepointId !== self
::$NOT_APPLICABLE ) {
3850 $this->doReleaseSavepoint( $savepointId, $fname );
3853 // Hoist callback ownership for callbacks in the section that just ended;
3854 // all callbacks should have an owner that is present in trxAtomicLevels.
3855 $currentSectionId = $this->currentAtomicSectionId();
3856 if ( $currentSectionId ) {
3857 $this->reassignCallbacksForSection( $sectionId, $currentSectionId );
3861 final public function cancelAtomic(
3862 $fname = __METHOD__
, AtomicSectionIdentifier
$sectionId = null
3864 if ( !$this->trxLevel() ||
!$this->trxAtomicLevels
) {
3865 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3869 $newTopSection = $this->currentAtomicSectionId();
3871 $excisedFnames = [];
3872 if ( $sectionId !== null ) {
3873 // Find the (last) section with the given $sectionId
3875 foreach ( $this->trxAtomicLevels
as $i => list( $asFname, $asId, $spId ) ) {
3876 if ( $asId === $sectionId ) {
3881 throw new DBUnexpectedError( $this, "Atomic section not found (for $fname)" );
3883 // Remove all descendant sections and re-index the array
3884 $len = count( $this->trxAtomicLevels
);
3885 for ( $i = $pos +
1; $i < $len; ++
$i ) {
3886 $excisedFnames[] = $this->trxAtomicLevels
[$i][0];
3887 $excisedIds[] = $this->trxAtomicLevels
[$i][1];
3889 $this->trxAtomicLevels
= array_slice( $this->trxAtomicLevels
, 0, $pos +
1 );
3890 $newTopSection = $this->currentAtomicSectionId();
3893 // Check if the current section matches $fname
3894 $pos = count( $this->trxAtomicLevels
) - 1;
3895 list( $savedFname, $savedSectionId, $savepointId ) = $this->trxAtomicLevels
[$pos];
3897 if ( $excisedFnames ) {
3898 $this->queryLogger
->debug( "cancelAtomic: canceling level $pos ($savedFname) " .
3899 "and descendants " . implode( ', ', $excisedFnames ) );
3901 $this->queryLogger
->debug( "cancelAtomic: canceling level $pos ($savedFname)" );
3904 if ( $savedFname !== $fname ) {
3905 throw new DBUnexpectedError(
3907 "Invalid atomic section ended (got $fname but expected $savedFname)"
3911 // Remove the last section (no need to re-index the array)
3912 array_pop( $this->trxAtomicLevels
);
3913 $excisedIds[] = $savedSectionId;
3914 $newTopSection = $this->currentAtomicSectionId();
3916 if ( $savepointId !== null ) {
3917 // Rollback the transaction to the state just before this atomic section
3918 if ( $savepointId === self
::$NOT_APPLICABLE ) {
3919 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3920 // Note: rollback() will run trxSectionCancelCallbacks
3922 $this->doRollbackToSavepoint( $savepointId, $fname );
3923 $this->trxStatus
= self
::STATUS_TRX_OK
; // no exception; recovered
3924 $this->trxStatusIgnoredCause
= null;
3926 // Run trxSectionCancelCallbacks now.
3927 $this->runOnAtomicSectionCancelCallbacks( self
::TRIGGER_CANCEL
, $excisedIds );
3929 } elseif ( $this->trxStatus
> self
::STATUS_TRX_ERROR
) {
3930 // Put the transaction into an error state if it's not already in one
3931 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
3932 $this->trxStatusCause
= new DBUnexpectedError(
3934 "Uncancelable atomic section canceled (got $fname)"
3938 // Fix up callbacks owned by the sections that were just cancelled.
3939 // All callbacks should have an owner that is present in trxAtomicLevels.
3940 $this->modifyCallbacksForCancel( $excisedIds, $newTopSection );
3943 $this->affectedRowCount
= 0; // for the sake of consistency
3946 final public function doAtomicSection(
3947 $fname, callable
$callback, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3949 $sectionId = $this->startAtomic( $fname, $cancelable );
3951 $res = $callback( $this, $fname );
3952 } catch ( Exception
$e ) {
3953 $this->cancelAtomic( $fname, $sectionId );
3957 $this->endAtomic( $fname );
3962 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3963 static $modes = [ self
::TRANSACTION_EXPLICIT
, self
::TRANSACTION_INTERNAL
];
3964 if ( !in_array( $mode, $modes, true ) ) {
3965 throw new DBUnexpectedError( $this, "$fname: invalid mode parameter '$mode'" );
3968 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3969 if ( $this->trxLevel() ) {
3970 if ( $this->trxAtomicLevels
) {
3971 $levels = $this->flatAtomicSectionList();
3972 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open";
3973 throw new DBUnexpectedError( $this, $msg );
3974 } elseif ( !$this->trxAutomatic
) {
3975 $msg = "$fname: Explicit transaction already active (from {$this->trxFname})";
3976 throw new DBUnexpectedError( $this, $msg );
3978 $msg = "$fname: Implicit transaction already active (from {$this->trxFname})";
3979 throw new DBUnexpectedError( $this, $msg );
3981 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3982 $msg = "$fname: Implicit transaction expected (DBO_TRX set)";
3983 throw new DBUnexpectedError( $this, $msg );
3986 $this->assertHasConnectionHandle();
3988 $this->doBegin( $fname );
3989 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3990 $this->trxStatus
= self
::STATUS_TRX_OK
;
3991 $this->trxStatusIgnoredCause
= null;
3992 $this->trxAtomicCounter
= 0;
3993 $this->trxTimestamp
= microtime( true );
3994 $this->trxFname
= $fname;
3995 $this->trxDoneWrites
= false;
3996 $this->trxAutomaticAtomic
= false;
3997 $this->trxAtomicLevels
= [];
3998 $this->trxWriteDuration
= 0.0;
3999 $this->trxWriteQueryCount
= 0;
4000 $this->trxWriteAffectedRows
= 0;
4001 $this->trxWriteAdjDuration
= 0.0;
4002 $this->trxWriteAdjQueryCount
= 0;
4003 $this->trxWriteCallers
= [];
4004 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
4005 // Get an estimate of the replication lag before any such queries.
4006 $this->trxReplicaLag
= null; // clear cached value first
4007 $this->trxReplicaLag
= $this->getApproximateLagStatus()['lag'];
4008 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
4009 // caller will think its OK to muck around with the transaction just because startAtomic()
4010 // has not yet completed (e.g. setting trxAtomicLevels).
4011 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
4015 * Issues the BEGIN command to the database server.
4017 * @see Database::begin()
4018 * @param string $fname
4021 protected function doBegin( $fname ) {
4022 $this->query( 'BEGIN', $fname );
4025 final public function commit( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
4026 static $modes = [ self
::FLUSHING_ONE
, self
::FLUSHING_ALL_PEERS
, self
::FLUSHING_INTERNAL
];
4027 if ( !in_array( $flush, $modes, true ) ) {
4028 throw new DBUnexpectedError( $this, "$fname: invalid flush parameter '$flush'" );
4031 if ( $this->trxLevel() && $this->trxAtomicLevels
) {
4032 // There are still atomic sections open; this cannot be ignored
4033 $levels = $this->flatAtomicSectionList();
4034 throw new DBUnexpectedError(
4036 "$fname: Got COMMIT while atomic sections $levels are still open"
4040 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
4041 if ( !$this->trxLevel() ) {
4042 return; // nothing to do
4043 } elseif ( !$this->trxAutomatic
) {
4044 throw new DBUnexpectedError(
4046 "$fname: Flushing an explicit transaction, getting out of sync"
4049 } elseif ( !$this->trxLevel() ) {
4050 $this->queryLogger
->error(
4051 "$fname: No transaction to commit, something got out of sync" );
4052 return; // nothing to do
4053 } elseif ( $this->trxAutomatic
) {
4054 throw new DBUnexpectedError(
4056 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)"
4060 $this->assertHasConnectionHandle();
4062 $this->runOnTransactionPreCommitCallbacks();
4064 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
4065 $this->doCommit( $fname );
4066 $oldTrxShortId = $this->consumeTrxShortId();
4067 $this->trxStatus
= self
::STATUS_TRX_NONE
;
4069 if ( $this->trxDoneWrites
) {
4070 $this->lastWriteTime
= microtime( true );
4071 $this->trxProfiler
->transactionWritingOut(
4073 $this->getDomainID(),
4076 $this->trxWriteAffectedRows
4080 // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4081 if ( $flush !== self
::FLUSHING_ALL_PEERS
) {
4082 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
4083 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
4088 * Issues the COMMIT command to the database server.
4090 * @see Database::commit()
4091 * @param string $fname
4094 protected function doCommit( $fname ) {
4095 if ( $this->trxLevel() ) {
4096 $this->query( 'COMMIT', $fname );
4100 final public function rollback( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
4101 $trxActive = $this->trxLevel();
4103 if ( $flush !== self
::FLUSHING_INTERNAL
4104 && $flush !== self
::FLUSHING_ALL_PEERS
4105 && $this->getFlag( self
::DBO_TRX
)
4107 throw new DBUnexpectedError(
4109 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)"
4114 $this->assertHasConnectionHandle();
4116 $this->doRollback( $fname );
4117 $oldTrxShortId = $this->consumeTrxShortId();
4118 $this->trxStatus
= self
::STATUS_TRX_NONE
;
4119 $this->trxAtomicLevels
= [];
4120 // Estimate the RTT via a query now that trxStatus is OK
4121 $writeTime = $this->pingAndCalculateLastTrxApplyTime();
4123 if ( $this->trxDoneWrites
) {
4124 $this->trxProfiler
->transactionWritingOut(
4126 $this->getDomainID(),
4129 $this->trxWriteAffectedRows
4134 // Clear any commit-dependant callbacks. They might even be present
4135 // only due to transaction rounds, with no SQL transaction being active
4136 $this->trxIdleCallbacks
= [];
4137 $this->trxPreCommitCallbacks
= [];
4139 // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4140 if ( $trxActive && $flush !== self
::FLUSHING_ALL_PEERS
) {
4142 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
4143 } catch ( Exception
$e ) {
4144 // already logged; finish and let LoadBalancer move on during mass-rollback
4147 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
4148 } catch ( Exception
$e ) {
4149 // already logged; let LoadBalancer move on during mass-rollback
4152 $this->affectedRowCount
= 0; // for the sake of consistency
4157 * Issues the ROLLBACK command to the database server.
4159 * @see Database::rollback()
4160 * @param string $fname
4163 protected function doRollback( $fname ) {
4164 if ( $this->trxLevel() ) {
4165 # Disconnects cause rollback anyway, so ignore those errors
4166 $ignoreErrors = true;
4167 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
4171 public function flushSnapshot( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
4172 if ( $this->explicitTrxActive() ) {
4173 // Committing this transaction would break callers that assume it is still open
4174 throw new DBUnexpectedError(
4176 "$fname: Cannot flush snapshot; " .
4177 "explicit transaction '{$this->trxFname}' is still open"
4179 } elseif ( $this->writesOrCallbacksPending() ) {
4180 // This only flushes transactions to clear snapshots, not to write data
4181 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4182 throw new DBUnexpectedError(
4184 "$fname: Cannot flush snapshot; " .
4185 "writes from transaction {$this->trxFname} are still pending ($fnames)"
4188 $this->trxLevel() &&
4189 $this->getTransactionRoundId() &&
4190 $flush !== self
::FLUSHING_INTERNAL
&&
4191 $flush !== self
::FLUSHING_ALL_PEERS
4193 $this->queryLogger
->warning(
4194 "$fname: Expected mass snapshot flush of all peer transactions " .
4195 "in the explicit transactions round '{$this->getTransactionRoundId()}'",
4196 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
4200 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4203 public function explicitTrxActive() {
4204 return $this->trxLevel() && ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
4207 public function duplicateTableStructure(
4208 $oldName, $newName, $temporary = false, $fname = __METHOD__
4210 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4213 public function listTables( $prefix = null, $fname = __METHOD__
) {
4214 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4217 public function listViews( $prefix = null, $fname = __METHOD__
) {
4218 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4221 public function timestamp( $ts = 0 ) {
4222 $t = new ConvertibleTimestamp( $ts );
4223 // Let errors bubble up to avoid putting garbage in the DB
4224 return $t->getTimestamp( TS_MW
);
4227 public function timestampOrNull( $ts = null ) {
4228 if ( is_null( $ts ) ) {
4231 return $this->timestamp( $ts );
4235 public function affectedRows() {
4236 return ( $this->affectedRowCount
=== null )
4237 ?
$this->fetchAffectedRowCount() // default to driver value
4238 : $this->affectedRowCount
;
4242 * @return int Number of retrieved rows according to the driver
4244 abstract protected function fetchAffectedRowCount();
4247 * Take a query result and wrap it in an iterable result wrapper if necessary.
4248 * Booleans are passed through as-is to indicate success/failure of write queries.
4250 * Once upon a time, Database::query() returned a bare MySQL result
4251 * resource, and it was necessary to call this function to convert it to
4252 * a wrapper. Nowadays, raw database objects are never exposed to external
4253 * callers, so this is unnecessary in external code.
4255 * @param bool|IResultWrapper|resource $result
4256 * @return bool|IResultWrapper
4258 protected function resultObject( $result ) {
4260 return false; // failed query
4261 } elseif ( $result instanceof IResultWrapper
) {
4263 } elseif ( $result === true ) {
4264 return $result; // succesful write query
4266 return new ResultWrapper( $this, $result );
4270 public function ping( &$rtt = null ) {
4271 // Avoid hitting the server if it was hit recently
4272 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::$PING_TTL ) {
4273 if ( !func_num_args() ||
$this->lastRoundTripEstimate
> 0 ) {
4274 $rtt = $this->lastRoundTripEstimate
;
4275 return true; // don't care about $rtt
4279 // This will reconnect if possible or return false if not
4280 $flags = self
::QUERY_IGNORE_DBO_TRX | self
::QUERY_SILENCE_ERRORS
;
4281 $ok = ( $this->query( self
::$PING_QUERY, __METHOD__
, $flags ) !== false );
4283 $rtt = $this->lastRoundTripEstimate
;
4290 * Close any existing (dead) database connection and open a new connection
4292 * @param string $fname
4293 * @return bool True if new connection is opened successfully, false if error
4295 protected function replaceLostConnection( $fname ) {
4296 $this->closeConnection();
4299 $this->handleSessionLossPreconnect();
4306 $this->currentDomain
->getDatabase(),
4307 $this->currentDomain
->getSchema(),
4308 $this->tablePrefix()
4310 $this->lastPing
= microtime( true );
4313 $this->connLogger
->warning(
4314 $fname . ': lost connection to {dbserver}; reconnected',
4316 'dbserver' => $this->getServer(),
4317 'trace' => ( new RuntimeException() )->getTraceAsString()
4320 } catch ( DBConnectionError
$e ) {
4323 $this->connLogger
->error(
4324 $fname . ': lost connection to {dbserver} permanently',
4325 [ 'dbserver' => $this->getServer() ]
4329 $this->handleSessionLossPostconnect();
4334 public function getSessionLagStatus() {
4335 return $this->getRecordedTransactionLagStatus() ?
: $this->getApproximateLagStatus();
4339 * Get the replica DB lag when the current transaction started
4341 * This is useful when transactions might use snapshot isolation
4342 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
4343 * is this lag plus transaction duration. If they don't, it is still
4344 * safe to be pessimistic. This returns null if there is no transaction.
4346 * This returns null if the lag status for this transaction was not yet recorded.
4348 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
4351 final protected function getRecordedTransactionLagStatus() {
4352 return ( $this->trxLevel() && $this->trxReplicaLag
!== null )
4353 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
4358 * Get a replica DB lag estimate for this server
4360 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
4363 protected function getApproximateLagStatus() {
4365 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
4366 'since' => microtime( true )
4371 * Merge the result of getSessionLagStatus() for several DBs
4372 * using the most pessimistic values to estimate the lag of
4373 * any data derived from them in combination
4375 * This is information is useful for caching modules
4377 * @see WANObjectCache::set()
4378 * @see WANObjectCache::getWithSetCallback()
4380 * @param IDatabase $db1
4381 * @param IDatabase|null $db2 [optional]
4382 * @return array Map of values:
4383 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
4384 * - since: oldest UNIX timestamp of any of the DB lag estimates
4385 * - pending: whether any of the DBs have uncommitted changes
4389 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
4390 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
4391 foreach ( func_get_args() as $db ) {
4392 /** @var IDatabase $db */
4393 $status = $db->getSessionLagStatus();
4394 if ( $status['lag'] === false ) {
4395 $res['lag'] = false;
4396 } elseif ( $res['lag'] !== false ) {
4397 $res['lag'] = max( $res['lag'], $status['lag'] );
4399 $res['since'] = min( $res['since'], $status['since'] );
4400 $res['pending'] = $res['pending'] ?
: $db->writesPending();
4406 public function getLag() {
4407 if ( $this->getLBInfo( 'master' ) ) {
4408 return 0; // this is the master
4409 } elseif ( $this->getLBInfo( 'is static' ) ) {
4410 return 0; // static dataset
4413 return $this->doGetLag();
4416 protected function doGetLag() {
4420 public function maxListLen() {
4424 public function encodeBlob( $b ) {
4428 public function decodeBlob( $b ) {
4429 if ( $b instanceof Blob
) {
4435 public function setSessionOptions( array $options ) {
4438 public function sourceFile(
4440 callable
$lineCallback = null,
4441 callable
$resultCallback = null,
4443 callable
$inputCallback = null
4445 AtEase
::suppressWarnings();
4446 $fp = fopen( $filename, 'r' );
4447 AtEase
::restoreWarnings();
4449 if ( $fp === false ) {
4450 throw new RuntimeException( "Could not open \"{$filename}\"" );
4454 $fname = __METHOD__
. "( $filename )";
4458 $error = $this->sourceStream(
4459 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
4460 } catch ( Exception
$e ) {
4470 public function setSchemaVars( $vars ) {
4471 $this->schemaVars
= is_array( $vars ) ?
$vars : null;
4474 public function sourceStream(
4476 callable
$lineCallback = null,
4477 callable
$resultCallback = null,
4478 $fname = __METHOD__
,
4479 callable
$inputCallback = null
4481 $delimiterReset = new ScopedCallback(
4482 function ( $delimiter ) {
4483 $this->delimiter
= $delimiter;
4485 [ $this->delimiter
]
4489 while ( !feof( $fp ) ) {
4490 if ( $lineCallback ) {
4491 call_user_func( $lineCallback );
4494 $line = trim( fgets( $fp ) );
4496 if ( $line == '' ) {
4500 if ( $line[0] == '-' && $line[1] == '-' ) {
4508 $done = $this->streamStatementEnd( $cmd, $line );
4512 if ( $done ||
feof( $fp ) ) {
4513 $cmd = $this->replaceVars( $cmd );
4515 if ( $inputCallback ) {
4516 $callbackResult = $inputCallback( $cmd );
4518 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
4519 $cmd = $callbackResult;
4524 $res = $this->query( $cmd, $fname );
4526 if ( $resultCallback ) {
4527 $resultCallback( $res, $this );
4530 if ( $res === false ) {
4531 $err = $this->lastError();
4533 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4540 ScopedCallback
::consume( $delimiterReset );
4545 * Called by sourceStream() to check if we've reached a statement end
4547 * @param string &$sql SQL assembled so far
4548 * @param string &$newLine New line about to be added to $sql
4549 * @return bool Whether $newLine contains end of the statement
4551 public function streamStatementEnd( &$sql, &$newLine ) {
4552 if ( $this->delimiter
) {
4554 $newLine = preg_replace(
4555 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4556 if ( $newLine != $prev ) {
4565 * Database independent variable replacement. Replaces a set of variables
4566 * in an SQL statement with their contents as given by $this->getSchemaVars().
4568 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4570 * - '{$var}' should be used for text and is passed through the database's
4572 * - `{$var}` should be used for identifiers (e.g. table and database names).
4573 * It is passed through the database's addIdentifierQuotes method which
4574 * can be overridden if the database uses something other than backticks.
4575 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4576 * database's tableName method.
4577 * - / *i* / passes the name that follows through the database's indexName method.
4578 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4579 * its use should be avoided. In 1.24 and older, string encoding was applied.
4581 * @param string $ins SQL statement to replace variables in
4582 * @return string The new SQL statement with variables replaced
4584 protected function replaceVars( $ins ) {
4585 $vars = $this->getSchemaVars();
4586 return preg_replace_callback(
4588 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4589 \'\{\$ (\w+) }\' | # 3. addQuotes
4590 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4591 /\*\$ (\w+) \*/ # 5. leave unencoded
4593 function ( $m ) use ( $vars ) {
4594 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4595 // check for both nonexistent keys *and* the empty string.
4596 if ( isset( $m[1] ) && $m[1] !== '' ) {
4597 if ( $m[1] === 'i' ) {
4598 return $this->indexName( $m[2] );
4600 return $this->tableName( $m[2] );
4602 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4603 return $this->addQuotes( $vars[$m[3]] );
4604 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4605 return $this->addIdentifierQuotes( $vars[$m[4]] );
4606 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4607 return $vars[$m[5]];
4617 * Get schema variables. If none have been set via setSchemaVars(), then
4618 * use some defaults from the current object.
4622 protected function getSchemaVars() {
4623 return $this->schemaVars ??
$this->getDefaultSchemaVars();
4627 * Get schema variables to use if none have been set via setSchemaVars().
4629 * Override this in derived classes to provide variables for tables.sql
4630 * and SQL patch files.
4634 protected function getDefaultSchemaVars() {
4638 public function lockIsFree( $lockName, $method ) {
4639 // RDBMs methods for checking named locks may or may not count this thread itself.
4640 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
4641 // the behavior choosen by the interface for this method.
4642 return !isset( $this->sessionNamedLocks
[$lockName] );
4645 public function lock( $lockName, $method, $timeout = 5 ) {
4646 $this->sessionNamedLocks
[$lockName] = 1;
4651 public function unlock( $lockName, $method ) {
4652 unset( $this->sessionNamedLocks
[$lockName] );
4657 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
4658 if ( $this->writesOrCallbacksPending() ) {
4659 // This only flushes transactions to clear snapshots, not to write data
4660 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4661 throw new DBUnexpectedError(
4663 "$fname: Cannot flush pre-lock snapshot; " .
4664 "writes from transaction {$this->trxFname} are still pending ($fnames)"
4668 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
4672 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
4673 if ( $this->trxLevel() ) {
4674 // There is a good chance an exception was thrown, causing any early return
4675 // from the caller. Let any error handler get a chance to issue rollback().
4676 // If there isn't one, let the error bubble up and trigger server-side rollback.
4677 $this->onTransactionResolution(
4678 function () use ( $lockKey, $fname ) {
4679 $this->unlock( $lockKey, $fname );
4684 $this->unlock( $lockKey, $fname );
4688 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4693 public function namedLocksEnqueue() {
4697 public function tableLocksHaveTransactionScope() {
4701 final public function lockTables( array $read, array $write, $method ) {
4702 if ( $this->writesOrCallbacksPending() ) {
4703 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending" );
4706 if ( $this->tableLocksHaveTransactionScope() ) {
4707 $this->startAtomic( $method );
4710 return $this->doLockTables( $read, $write, $method );
4714 * Helper function for lockTables() that handles the actual table locking
4716 * @param array $read Array of tables to lock for read access
4717 * @param array $write Array of tables to lock for write access
4718 * @param string $method Name of caller
4721 protected function doLockTables( array $read, array $write, $method ) {
4725 final public function unlockTables( $method ) {
4726 if ( $this->tableLocksHaveTransactionScope() ) {
4727 $this->endAtomic( $method );
4729 return true; // locks released on COMMIT/ROLLBACK
4732 return $this->doUnlockTables( $method );
4736 * Helper function for unlockTables() that handles the actual table unlocking
4738 * @param string $method Name of caller
4741 protected function doUnlockTables( $method ) {
4747 * @param string $tableName
4748 * @param string $fName
4749 * @return bool|IResultWrapper
4752 public function dropTable( $tableName, $fName = __METHOD__
) {
4753 if ( !$this->tableExists( $tableName, $fName ) ) {
4756 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
4758 return $this->query( $sql, $fName );
4761 public function getInfinity() {
4765 public function encodeExpiry( $expiry ) {
4766 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4767 ?
$this->getInfinity()
4768 : $this->timestamp( $expiry );
4771 public function decodeExpiry( $expiry, $format = TS_MW
) {
4772 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
4776 return ConvertibleTimestamp
::convert( $format, $expiry );
4779 public function setBigSelects( $value = true ) {
4783 public function isReadOnly() {
4784 return ( $this->getReadOnlyReason() !== false );
4788 * @return string|bool Reason this DB is read-only or false if it is not
4790 protected function getReadOnlyReason() {
4791 $reason = $this->getLBInfo( 'readOnlyReason' );
4792 if ( is_string( $reason ) ) {
4794 } elseif ( $this->getLBInfo( 'replica' ) ) {
4795 return "Server is configured in the role of a read-only replica database.";
4801 public function setTableAliases( array $aliases ) {
4802 $this->tableAliases
= $aliases;
4805 public function setIndexAliases( array $aliases ) {
4806 $this->indexAliases
= $aliases;
4815 final protected function fieldHasBit( $field, $flags ) {
4816 return ( ( $field & $flags ) === $flags );
4820 * Get the underlying binding connection handle
4822 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
4823 * This catches broken callers than catch and ignore disconnection exceptions.
4824 * Unlike checking isOpen(), this is safe to call inside of open().
4827 * @throws DBUnexpectedError
4830 protected function getBindingHandle() {
4831 if ( !$this->conn
) {
4832 throw new DBUnexpectedError(
4834 'DB connection was already closed or the connection dropped'
4841 public function __toString() {
4842 // spl_object_id is PHP >= 7.2
4843 $id = function_exists( 'spl_object_id' )
4844 ?
spl_object_id( $this )
4845 : spl_object_hash( $this );
4847 $description = $this->getType() . ' object #' . $id;
4848 if ( is_resource( $this->conn
) ) {
4849 $description .= ' (' . (string)$this->conn
. ')'; // "resource id #<ID>"
4850 } elseif ( is_object( $this->conn
) ) {
4851 // spl_object_id is PHP >= 7.2
4852 $handleId = function_exists( 'spl_object_id' )
4853 ?
spl_object_id( $this->conn
)
4854 : spl_object_hash( $this->conn
);
4855 $description .= " (handle id #$handleId)";
4858 return $description;
4862 * Make sure that copies do not share the same client binding handle
4863 * @throws DBConnectionError
4865 public function __clone() {
4866 $this->connLogger
->warning(
4867 "Cloning " . static::class . " is not recommended; forking connection",
4868 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
4871 if ( $this->isOpen() ) {
4872 // Open a new connection resource without messing with the old one
4874 $this->trxEndCallbacks
= []; // don't copy
4875 $this->trxSectionCancelCallbacks
= []; // don't copy
4876 $this->handleSessionLossPreconnect(); // no trx or locks anymore
4881 $this->currentDomain
->getDatabase(),
4882 $this->currentDomain
->getSchema(),
4883 $this->tablePrefix()
4885 $this->lastPing
= microtime( true );
4890 * Called by serialize. Throw an exception when DB connection is serialized.
4891 * This causes problems on some database engines because the connection is
4892 * not restored on unserialize.
4894 public function __sleep() {
4895 throw new RuntimeException( 'Database serialization may cause problems, since ' .
4896 'the connection is not restored on wakeup' );
4900 * Run a few simple sanity checks and close dangling connections
4902 public function __destruct() {
4903 if ( $this->trxLevel() && $this->trxDoneWrites
) {
4904 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})" );
4907 $danglingWriters = $this->pendingWriteAndCallbackCallers();
4908 if ( $danglingWriters ) {
4909 $fnames = implode( ', ', $danglingWriters );
4910 trigger_error( "DB transaction writes or callbacks still pending ($fnames)" );
4913 if ( $this->conn
) {
4914 // Avoid connection leaks for sanity. Normally, resources close at script completion.
4915 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4916 AtEase
::suppressWarnings();
4917 $this->closeConnection();
4918 AtEase
::restoreWarnings();
4925 * @deprecated since 1.28
4927 class_alias( Database
::class, 'DatabaseBase' );
4930 * @deprecated since 1.29
4932 class_alias( Database
::class, 'Database' );