Merge "rdbms: make LBFactory close/rollback dangling handles like LoadBalancer"
[lhc/web/wiklou.git] / includes / libs / rdbms / database / Database.php
1 <?php
2 /**
3 * @defgroup Database Database
4 *
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
7 *
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.
12 *
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.
17 *
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
22 *
23 * @file
24 * @ingroup Database
25 */
26 namespace Wikimedia\Rdbms;
27
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;
34 use BagOStuff;
35 use HashBagOStuff;
36 use LogicException;
37 use InvalidArgumentException;
38 use UnexpectedValueException;
39 use Exception;
40 use RuntimeException;
41 use Throwable;
42
43 /**
44 * Relational database abstraction object
45 *
46 * @ingroup Database
47 * @since 1.28
48 */
49 abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAwareInterface {
50 /** @var BagOStuff APC cache */
51 protected $srvCache;
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 */
61 protected $profiler;
62 /** @var TransactionProfiler */
63 protected $trxProfiler;
64
65 /** @var DatabaseDomain */
66 protected $currentDomain;
67
68 /** @var object|resource|null Database connection */
69 protected $conn;
70
71 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
72 private $lazyMasterHandle;
73
74 /** @var string Server that this instance is currently connected to */
75 protected $server;
76 /** @var string User that this instance is currently connected under the name of */
77 protected $user;
78 /** @var string Password used to establish the current connection */
79 protected $password;
80 /** @var bool Whether this PHP instance is for a CLI script */
81 protected $cliMode;
82 /** @var string Agent name for query profiling */
83 protected $agent;
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;
90
91 /** @var int Current bit field of class DBO_* constants */
92 protected $flags;
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;
103
104 /** @var string|bool|null Stashed value of html_errors INI setting */
105 private $htmlErrors;
106 /** @var int[] Prior flags member variable values */
107 private $priorFlags = [];
108
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 = [];
113
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;
162
163 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
164 protected $affectedRowCount;
165
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;
176
177 /** @var string Whether the database is a file on disk */
178 const ATTR_DB_IS_FILE = 'db-is-file';
179 /** @var string Lock granularity is on the level of the entire database */
180 const ATTR_DB_LEVEL_LOCKING = 'db-level-locking';
181 /** @var string The SCHEMA keyword refers to a grouping of tables in a database */
182 const ATTR_SCHEMAS_AS_TABLE_GROUPS = 'supports-schemas';
183
184 /** @var int New Database instance will not be connected yet when returned */
185 const NEW_UNCONNECTED = 0;
186 /** @var int New Database instance will already be connected when returned */
187 const NEW_CONNECTED = 1;
188
189 /** @var int Transaction is in a error state requiring a full or savepoint rollback */
190 const STATUS_TRX_ERROR = 1;
191 /** @var int Transaction is active and in a normal state */
192 const STATUS_TRX_OK = 2;
193 /** @var int No transaction is active */
194 const STATUS_TRX_NONE = 3;
195
196 /** @var string Idiom used when a cancelable atomic section started the transaction */
197 private static $NOT_APPLICABLE = 'n/a';
198 /** @var string Prefix to the atomic section counter used to make savepoint IDs */
199 private static $SAVEPOINT_PREFIX = 'wikimedia_rdbms_atomic';
200
201 /** @var int Writes to this temporary table do not affect lastDoneWrites() */
202 private static $TEMP_NORMAL = 1;
203 /** @var int Writes to this temporary table effect lastDoneWrites() */
204 private static $TEMP_PSEUDO_PERMANENT = 2;
205
206 /** @var int Number of times to re-try an operation in case of deadlock */
207 private static $DEADLOCK_TRIES = 4;
208 /** @var int Minimum time to wait before retry, in microseconds */
209 private static $DEADLOCK_DELAY_MIN = 500000;
210 /** @var int Maximum time to wait before retry */
211 private static $DEADLOCK_DELAY_MAX = 1500000;
212
213 /** @var int How long before it is worth doing a dummy query to test the connection */
214 private static $PING_TTL = 1.0;
215 /** @var string Dummy SQL query */
216 private static $PING_QUERY = 'SELECT 1 AS ping';
217
218 /** @var float Guess of how many seconds it takes to replicate a small insert */
219 private static $TINY_WRITE_SEC = 0.010;
220 /** @var float Consider a write slow if it took more than this many seconds */
221 private static $SLOW_WRITE_SEC = 0.500;
222 /** @var float Assume an insert of this many rows or less should be fast to replicate */
223 private static $SMALL_WRITE_ROWS = 100;
224
225 /** @var string[] List of DBO_* flags that can be changed after connection */
226 protected static $MUTABLE_FLAGS = [
227 'DBO_DEBUG',
228 'DBO_NOBUFFER',
229 'DBO_TRX',
230 'DBO_DDLMODE',
231 ];
232 /** @var int Bit field of all DBO_* flags that can be changed after connection */
233 protected static $DBO_MUTABLE = (
234 self::DBO_DEBUG | self::DBO_NOBUFFER | self::DBO_TRX | self::DBO_DDLMODE
235 );
236
237 /**
238 * @note exceptions for missing libraries/drivers should be thrown in initConnection()
239 * @param array $params Parameters passed from Database::factory()
240 */
241 public function __construct( array $params ) {
242 $this->connectionParams = [];
243 foreach ( [ 'host', 'user', 'password', 'dbname', 'schema', 'tablePrefix' ] as $name ) {
244 $this->connectionParams[$name] = $params[$name];
245 }
246 $this->connectionVariables = $params['variables'] ?? [];
247 $this->cliMode = $params['cliMode'];
248 $this->agent = $params['agent'];
249 $this->flags = $params['flags'];
250 $this->nonNativeInsertSelectBatchSize = $params['nonNativeInsertSelectBatchSize'] ?? 10000;
251
252 $this->srvCache = $params['srvCache'] ?? new HashBagOStuff();
253 $this->profiler = is_callable( $params['profiler'] ) ? $params['profiler'] : null;
254 $this->trxProfiler = $params['trxProfiler'];
255 $this->connLogger = $params['connLogger'];
256 $this->queryLogger = $params['queryLogger'];
257 $this->errorLogger = $params['errorLogger'];
258 $this->deprecationLogger = $params['deprecationLogger'];
259
260 // Set initial dummy domain until open() sets the final DB/prefix
261 $this->currentDomain = new DatabaseDomain(
262 $params['dbname'] != '' ? $params['dbname'] : null,
263 $params['schema'] != '' ? $params['schema'] : null,
264 $params['tablePrefix']
265 );
266 }
267
268 /**
269 * Initialize the connection to the database over the wire (or to local files)
270 *
271 * @throws LogicException
272 * @throws InvalidArgumentException
273 * @throws DBConnectionError
274 * @since 1.31
275 */
276 final public function initConnection() {
277 if ( $this->isOpen() ) {
278 throw new LogicException( __METHOD__ . ': already connected' );
279 }
280 // Establish the connection
281 $this->doInitConnection();
282 }
283
284 /**
285 * Actually connect to the database over the wire (or to local files)
286 *
287 * @throws DBConnectionError
288 * @since 1.31
289 */
290 protected function doInitConnection() {
291 $this->open(
292 $this->connectionParams['host'],
293 $this->connectionParams['user'],
294 $this->connectionParams['password'],
295 $this->connectionParams['dbname'],
296 $this->connectionParams['schema'],
297 $this->connectionParams['tablePrefix']
298 );
299 }
300
301 /**
302 * Open a new connection to the database (closing any existing one)
303 *
304 * @param string|null $server Database server host
305 * @param string|null $user Database user name
306 * @param string|null $password Database user password
307 * @param string|null $dbName Database name
308 * @param string|null $schema Database schema name
309 * @param string $tablePrefix Table prefix
310 * @throws DBConnectionError
311 */
312 abstract protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix );
313
314 /**
315 * Construct a Database subclass instance given a database type and parameters
316 *
317 * This also connects to the database immediately upon object construction
318 *
319 * @param string $type A possible DB type (sqlite, mysql, postgres,...)
320 * @param array $params Parameter map with keys:
321 * - host : The hostname of the DB server
322 * - user : The name of the database user the client operates under
323 * - password : The password for the database user
324 * - dbname : The name of the database to use where queries do not specify one.
325 * The database must exist or an error might be thrown. Setting this to the empty string
326 * will avoid any such errors and make the handle have no implicit database scope. This is
327 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
328 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
329 * in which user names and such are defined, e.g. users are database-specific in Postgres.
330 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
331 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
332 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
333 * recognized in queries. This can be used in place of schemas for handle site farms.
334 * - flags : Optional bit field of DBO_* constants that define connection, protocol,
335 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
336 * flag in place UNLESS this this database simply acts as a key/value store.
337 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
338 * 'mysqli' driver; the old one 'mysql' has been removed.
339 * - variables: Optional map of session variables to set after connecting. This can be
340 * used to adjust lock timeouts or encoding modes and the like.
341 * - connLogger: Optional PSR-3 logger interface instance.
342 * - queryLogger: Optional PSR-3 logger interface instance.
343 * - profiler : Optional callback that takes a section name argument and returns
344 * a ScopedCallback instance that ends the profile section in its destructor.
345 * These will be called in query(), using a simplified version of the SQL that
346 * also includes the agent as a SQL comment.
347 * - trxProfiler: Optional TransactionProfiler instance.
348 * - errorLogger: Optional callback that takes an Exception and logs it.
349 * - deprecationLogger: Optional callback that takes a string and logs it.
350 * - cliMode: Whether to consider the execution context that of a CLI script.
351 * - agent: Optional name used to identify the end-user in query profiling/logging.
352 * - srvCache: Optional BagOStuff instance to an APC-style cache.
353 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
354 * @param int $connect One of the class constants (NEW_CONNECTED, NEW_UNCONNECTED) [optional]
355 * @return Database|null If the database driver or extension cannot be found
356 * @throws InvalidArgumentException If the database driver or extension cannot be found
357 * @since 1.18
358 */
359 final public static function factory( $type, $params = [], $connect = self::NEW_CONNECTED ) {
360 $class = self::getClass( $type, $params['driver'] ?? null );
361
362 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase::class ) ) {
363 $params += [
364 'host' => null,
365 'user' => null,
366 'password' => null,
367 'dbname' => null,
368 'schema' => null,
369 'tablePrefix' => '',
370 'flags' => 0,
371 'variables' => [],
372 'cliMode' => ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ),
373 'agent' => basename( $_SERVER['SCRIPT_NAME'] ) . '@' . gethostname()
374 ];
375
376 $normalizedParams = [
377 // Configuration
378 'host' => strlen( $params['host'] ) ? $params['host'] : null,
379 'user' => strlen( $params['user'] ) ? $params['user'] : null,
380 'password' => is_string( $params['password'] ) ? $params['password'] : null,
381 'dbname' => strlen( $params['dbname'] ) ? $params['dbname'] : null,
382 'schema' => strlen( $params['schema'] ) ? $params['schema'] : null,
383 'tablePrefix' => (string)$params['tablePrefix'],
384 'flags' => (int)$params['flags'],
385 'variables' => $params['variables'],
386 'cliMode' => (bool)$params['cliMode'],
387 'agent' => (string)$params['agent'],
388 // Objects and callbacks
389 'srvCache' => $params['srvCache'] ?? new HashBagOStuff(),
390 'profiler' => $params['profiler'] ?? null,
391 'trxProfiler' => $params['trxProfiler'] ?? new TransactionProfiler(),
392 'connLogger' => $params['connLogger'] ?? new NullLogger(),
393 'queryLogger' => $params['queryLogger'] ?? new NullLogger(),
394 'errorLogger' => $params['errorLogger'] ?? function ( Exception $e ) {
395 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
396 },
397 'deprecationLogger' => $params['deprecationLogger'] ?? function ( $msg ) {
398 trigger_error( $msg, E_USER_DEPRECATED );
399 }
400 ] + $params;
401
402 /** @var Database $conn */
403 $conn = new $class( $normalizedParams );
404 if ( $connect === self::NEW_CONNECTED ) {
405 $conn->initConnection();
406 }
407 } else {
408 $conn = null;
409 }
410
411 return $conn;
412 }
413
414 /**
415 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
416 * @param string|null $driver Optional name of a specific DB client driver
417 * @return array Map of (Database::ATTR_* constant => value) for all such constants
418 * @throws InvalidArgumentException
419 * @since 1.31
420 */
421 final public static function attributesFromType( $dbType, $driver = null ) {
422 static $defaults = [
423 self::ATTR_DB_IS_FILE => false,
424 self::ATTR_DB_LEVEL_LOCKING => false,
425 self::ATTR_SCHEMAS_AS_TABLE_GROUPS => false
426 ];
427
428 $class = self::getClass( $dbType, $driver );
429
430 return call_user_func( [ $class, 'getAttributes' ] ) + $defaults;
431 }
432
433 /**
434 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
435 * @param string|null $driver Optional name of a specific DB client driver
436 * @return string Database subclass name to use
437 * @throws InvalidArgumentException
438 */
439 private static function getClass( $dbType, $driver = null ) {
440 // For database types with built-in support, the below maps type to IDatabase
441 // implementations. For types with multipe driver implementations (PHP extensions),
442 // an array can be used, keyed by extension name. In case of an array, the
443 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
444 // we auto-detect the first available driver. For types without built-in support,
445 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
446 static $builtinTypes = [
447 'mysql' => [ 'mysqli' => DatabaseMysqli::class ],
448 'sqlite' => DatabaseSqlite::class,
449 'postgres' => DatabasePostgres::class,
450 ];
451
452 $dbType = strtolower( $dbType );
453 $class = false;
454
455 if ( isset( $builtinTypes[$dbType] ) ) {
456 $possibleDrivers = $builtinTypes[$dbType];
457 if ( is_string( $possibleDrivers ) ) {
458 $class = $possibleDrivers;
459 } elseif ( (string)$driver !== '' ) {
460 if ( !isset( $possibleDrivers[$driver] ) ) {
461 throw new InvalidArgumentException( __METHOD__ .
462 " type '$dbType' does not support driver '{$driver}'" );
463 }
464
465 $class = $possibleDrivers[$driver];
466 } else {
467 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
468 if ( extension_loaded( $posDriver ) ) {
469 $class = $possibleClass;
470 break;
471 }
472 }
473 }
474 } else {
475 $class = 'Database' . ucfirst( $dbType );
476 }
477
478 if ( $class === false ) {
479 throw new InvalidArgumentException( __METHOD__ .
480 " no viable database extension found for type '$dbType'" );
481 }
482
483 return $class;
484 }
485
486 /**
487 * @return array Map of (Database::ATTR_* constant => value)
488 * @since 1.31
489 */
490 protected static function getAttributes() {
491 return [];
492 }
493
494 /**
495 * Set the PSR-3 logger interface to use for query logging. (The logger
496 * interfaces for connection logging and error logging can be set with the
497 * constructor.)
498 *
499 * @param LoggerInterface $logger
500 */
501 public function setLogger( LoggerInterface $logger ) {
502 $this->queryLogger = $logger;
503 }
504
505 public function getServerInfo() {
506 return $this->getServerVersion();
507 }
508
509 /**
510 * Backwards-compatibility no-op method for disabling query buffering
511 *
512 * @param null|bool $buffer Whether to buffer queries (ignored)
513 * @return bool Whether buffering was already enabled (always true)
514 * @deprecated Since 1.34 Use query batching; this no longer does anything
515 */
516 public function bufferResults( $buffer = null ) {
517 return true;
518 }
519
520 final public function trxLevel() {
521 return ( $this->trxShortId != '' ) ? 1 : 0;
522 }
523
524 public function trxTimestamp() {
525 return $this->trxLevel() ? $this->trxTimestamp : null;
526 }
527
528 /**
529 * @return int One of the STATUS_TRX_* class constants
530 * @since 1.31
531 */
532 public function trxStatus() {
533 return $this->trxStatus;
534 }
535
536 public function tablePrefix( $prefix = null ) {
537 $old = $this->currentDomain->getTablePrefix();
538 if ( $prefix !== null ) {
539 $this->currentDomain = new DatabaseDomain(
540 $this->currentDomain->getDatabase(),
541 $this->currentDomain->getSchema(),
542 $prefix
543 );
544 }
545
546 return $old;
547 }
548
549 public function dbSchema( $schema = null ) {
550 if ( strlen( $schema ) && $this->getDBname() === null ) {
551 throw new DBUnexpectedError( $this, "Cannot set schema to '$schema'; no database set" );
552 }
553
554 $old = $this->currentDomain->getSchema();
555 if ( $schema !== null ) {
556 $this->currentDomain = new DatabaseDomain(
557 $this->currentDomain->getDatabase(),
558 // DatabaseDomain uses null for unspecified schemas
559 strlen( $schema ) ? $schema : null,
560 $this->currentDomain->getTablePrefix()
561 );
562 }
563
564 return (string)$old;
565 }
566
567 /**
568 * @return string Schema to use to qualify relations in queries
569 */
570 protected function relationSchemaQualifier() {
571 return $this->dbSchema();
572 }
573
574 public function getLBInfo( $name = null ) {
575 if ( is_null( $name ) ) {
576 return $this->lbInfo;
577 }
578
579 if ( array_key_exists( $name, $this->lbInfo ) ) {
580 return $this->lbInfo[$name];
581 }
582
583 return null;
584 }
585
586 public function setLBInfo( $nameOrArray, $value = null ) {
587 if ( is_array( $nameOrArray ) ) {
588 $this->lbInfo = $nameOrArray;
589 } elseif ( is_string( $nameOrArray ) ) {
590 if ( $value !== null ) {
591 $this->lbInfo[$nameOrArray] = $value;
592 } else {
593 unset( $this->lbInfo[$nameOrArray] );
594 }
595 } else {
596 throw new InvalidArgumentException( "Got non-string key" );
597 }
598 }
599
600 public function setLazyMasterHandle( IDatabase $conn ) {
601 $this->lazyMasterHandle = $conn;
602 }
603
604 /**
605 * @return IDatabase|null
606 * @see setLazyMasterHandle()
607 * @since 1.27
608 */
609 protected function getLazyMasterHandle() {
610 return $this->lazyMasterHandle;
611 }
612
613 public function implicitOrderby() {
614 return true;
615 }
616
617 public function lastQuery() {
618 return $this->lastQuery;
619 }
620
621 public function lastDoneWrites() {
622 return $this->lastWriteTime ?: false;
623 }
624
625 public function writesPending() {
626 return $this->trxLevel() && $this->trxDoneWrites;
627 }
628
629 public function writesOrCallbacksPending() {
630 return $this->trxLevel() && (
631 $this->trxDoneWrites ||
632 $this->trxIdleCallbacks ||
633 $this->trxPreCommitCallbacks ||
634 $this->trxEndCallbacks ||
635 $this->trxSectionCancelCallbacks
636 );
637 }
638
639 public function preCommitCallbacksPending() {
640 return $this->trxLevel() && $this->trxPreCommitCallbacks;
641 }
642
643 /**
644 * @return string|null
645 */
646 final protected function getTransactionRoundId() {
647 // If transaction round participation is enabled, see if one is active
648 if ( $this->getFlag( self::DBO_TRX ) ) {
649 $id = $this->getLBInfo( 'trxRoundId' );
650
651 return is_string( $id ) ? $id : null;
652 }
653
654 return null;
655 }
656
657 public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL ) {
658 if ( !$this->trxLevel() ) {
659 return false;
660 } elseif ( !$this->trxDoneWrites ) {
661 return 0.0;
662 }
663
664 switch ( $type ) {
665 case self::ESTIMATE_DB_APPLY:
666 return $this->pingAndCalculateLastTrxApplyTime();
667 default: // everything
668 return $this->trxWriteDuration;
669 }
670 }
671
672 /**
673 * @return float Time to apply writes to replicas based on trxWrite* fields
674 */
675 private function pingAndCalculateLastTrxApplyTime() {
676 $this->ping( $rtt );
677
678 $rttAdjTotal = $this->trxWriteAdjQueryCount * $rtt;
679 $applyTime = max( $this->trxWriteAdjDuration - $rttAdjTotal, 0 );
680 // For omitted queries, make them count as something at least
681 $omitted = $this->trxWriteQueryCount - $this->trxWriteAdjQueryCount;
682 $applyTime += self::$TINY_WRITE_SEC * $omitted;
683
684 return $applyTime;
685 }
686
687 public function pendingWriteCallers() {
688 return $this->trxLevel() ? $this->trxWriteCallers : [];
689 }
690
691 public function pendingWriteRowsAffected() {
692 return $this->trxWriteAffectedRows;
693 }
694
695 /**
696 * List the methods that have write queries or callbacks for the current transaction
697 *
698 * This method should not be used outside of Database/LoadBalancer
699 *
700 * @return string[]
701 * @since 1.32
702 */
703 public function pendingWriteAndCallbackCallers() {
704 $fnames = $this->pendingWriteCallers();
705 foreach ( [
706 $this->trxIdleCallbacks,
707 $this->trxPreCommitCallbacks,
708 $this->trxEndCallbacks,
709 $this->trxSectionCancelCallbacks
710 ] as $callbacks ) {
711 foreach ( $callbacks as $callback ) {
712 $fnames[] = $callback[1];
713 }
714 }
715
716 return $fnames;
717 }
718
719 /**
720 * @return string
721 */
722 private function flatAtomicSectionList() {
723 return array_reduce( $this->trxAtomicLevels, function ( $accum, $v ) {
724 return $accum === null ? $v[0] : "$accum, " . $v[0];
725 } );
726 }
727
728 public function isOpen() {
729 return (bool)$this->conn;
730 }
731
732 public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
733 if ( $flag & ~static::$DBO_MUTABLE ) {
734 throw new DBUnexpectedError(
735 $this,
736 "Got $flag (allowed: " . implode( ', ', static::$MUTABLE_FLAGS ) . ')'
737 );
738 }
739
740 if ( $remember === self::REMEMBER_PRIOR ) {
741 array_push( $this->priorFlags, $this->flags );
742 }
743
744 $this->flags |= $flag;
745 }
746
747 public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
748 if ( $flag & ~static::$DBO_MUTABLE ) {
749 throw new DBUnexpectedError(
750 $this,
751 "Got $flag (allowed: " . implode( ', ', static::$MUTABLE_FLAGS ) . ')'
752 );
753 }
754
755 if ( $remember === self::REMEMBER_PRIOR ) {
756 array_push( $this->priorFlags, $this->flags );
757 }
758
759 $this->flags &= ~$flag;
760 }
761
762 public function restoreFlags( $state = self::RESTORE_PRIOR ) {
763 if ( !$this->priorFlags ) {
764 return;
765 }
766
767 if ( $state === self::RESTORE_INITIAL ) {
768 $this->flags = reset( $this->priorFlags );
769 $this->priorFlags = [];
770 } else {
771 $this->flags = array_pop( $this->priorFlags );
772 }
773 }
774
775 public function getFlag( $flag ) {
776 return ( ( $this->flags & $flag ) === $flag );
777 }
778
779 public function getDomainID() {
780 return $this->currentDomain->getId();
781 }
782
783 /**
784 * Get information about an index into an object
785 * @param string $table Table name
786 * @param string $index Index name
787 * @param string $fname Calling function name
788 * @return mixed Database-specific index description class or false if the index does not exist
789 */
790 abstract function indexInfo( $table, $index, $fname = __METHOD__ );
791
792 /**
793 * Wrapper for addslashes()
794 *
795 * @param string $s String to be slashed.
796 * @return string Slashed string.
797 */
798 abstract function strencode( $s );
799
800 /**
801 * Set a custom error handler for logging errors during database connection
802 */
803 protected function installErrorHandler() {
804 $this->lastPhpError = false;
805 $this->htmlErrors = ini_set( 'html_errors', '0' );
806 set_error_handler( [ $this, 'connectionErrorLogger' ] );
807 }
808
809 /**
810 * Restore the previous error handler and return the last PHP error for this DB
811 *
812 * @return bool|string
813 */
814 protected function restoreErrorHandler() {
815 restore_error_handler();
816 if ( $this->htmlErrors !== false ) {
817 ini_set( 'html_errors', $this->htmlErrors );
818 }
819
820 return $this->getLastPHPError();
821 }
822
823 /**
824 * @return string|bool Last PHP error for this DB (typically connection errors)
825 */
826 protected function getLastPHPError() {
827 if ( $this->lastPhpError ) {
828 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->lastPhpError );
829 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
830
831 return $error;
832 }
833
834 return false;
835 }
836
837 /**
838 * Error handler for logging errors during database connection
839 * This method should not be used outside of Database classes
840 *
841 * @param int $errno
842 * @param string $errstr
843 */
844 public function connectionErrorLogger( $errno, $errstr ) {
845 $this->lastPhpError = $errstr;
846 }
847
848 /**
849 * Create a log context to pass to PSR-3 logger functions.
850 *
851 * @param array $extras Additional data to add to context
852 * @return array
853 */
854 protected function getLogContext( array $extras = [] ) {
855 return array_merge(
856 [
857 'db_server' => $this->server,
858 'db_name' => $this->getDBname(),
859 'db_user' => $this->user,
860 ],
861 $extras
862 );
863 }
864
865 final public function close() {
866 $exception = null; // error to throw after disconnecting
867
868 $wasOpen = (bool)$this->conn;
869 // This should mostly do nothing if the connection is already closed
870 if ( $this->conn ) {
871 // Roll back any dangling transaction first
872 if ( $this->trxLevel() ) {
873 if ( $this->trxAtomicLevels ) {
874 // Cannot let incomplete atomic sections be committed
875 $levels = $this->flatAtomicSectionList();
876 $exception = new DBUnexpectedError(
877 $this,
878 __METHOD__ . ": atomic sections $levels are still open"
879 );
880 } elseif ( $this->trxAutomatic ) {
881 // Only the connection manager can commit non-empty DBO_TRX transactions
882 // (empty ones we can silently roll back)
883 if ( $this->writesOrCallbacksPending() ) {
884 $exception = new DBUnexpectedError(
885 $this,
886 __METHOD__ .
887 ": mass commit/rollback of peer transaction required (DBO_TRX set)"
888 );
889 }
890 } else {
891 // Manual transactions should have been committed or rolled
892 // back, even if empty.
893 $exception = new DBUnexpectedError(
894 $this,
895 __METHOD__ . ": transaction is still open (from {$this->trxFname})"
896 );
897 }
898
899 if ( $this->trxEndCallbacksSuppressed ) {
900 $exception = $exception ?: new DBUnexpectedError(
901 $this,
902 __METHOD__ . ': callbacks are suppressed; cannot properly commit'
903 );
904 }
905
906 // Rollback the changes and run any callbacks as needed
907 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
908 }
909
910 // Close the actual connection in the binding handle
911 $closed = $this->closeConnection();
912 } else {
913 $closed = true; // already closed; nothing to do
914 }
915
916 $this->conn = null;
917
918 // Throw any unexpected errors after having disconnected
919 if ( $exception instanceof Exception ) {
920 throw $exception;
921 }
922
923 // Note that various subclasses call close() at the start of open(), which itself is
924 // called by replaceLostConnection(). In that case, just because onTransactionResolution()
925 // callbacks are pending does not mean that an exception should be thrown. Rather, they
926 // will be executed after the reconnection step.
927 if ( $wasOpen ) {
928 // Sanity check that no callbacks are dangling
929 $fnames = $this->pendingWriteAndCallbackCallers();
930 if ( $fnames ) {
931 throw new RuntimeException(
932 "Transaction callbacks are still pending: " . implode( ', ', $fnames )
933 );
934 }
935 }
936
937 return $closed;
938 }
939
940 /**
941 * Make sure there is an open connection handle (alive or not) as a sanity check
942 *
943 * This guards against fatal errors to the binding handle not being defined
944 * in cases where open() was never called or close() was already called
945 *
946 * @throws DBUnexpectedError
947 */
948 final protected function assertHasConnectionHandle() {
949 if ( !$this->isOpen() ) {
950 throw new DBUnexpectedError( $this, "DB connection was already closed" );
951 }
952 }
953
954 /**
955 * Make sure that this server is not marked as a replica nor read-only as a sanity check
956 *
957 * @throws DBReadOnlyRoleError
958 * @throws DBReadOnlyError
959 */
960 protected function assertIsWritableMaster() {
961 if ( $this->getLBInfo( 'replica' ) ) {
962 throw new DBReadOnlyRoleError(
963 $this,
964 'Write operations are not allowed on replica database connections'
965 );
966 }
967 $reason = $this->getReadOnlyReason();
968 if ( $reason !== false ) {
969 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
970 }
971 }
972
973 /**
974 * Closes underlying database connection
975 * @since 1.20
976 * @return bool Whether connection was closed successfully
977 */
978 abstract protected function closeConnection();
979
980 /**
981 * Run a query and return a DBMS-dependent wrapper or boolean
982 *
983 * This is meant to handle the basic command of actually sending a query to the
984 * server via the driver. No implicit transaction, reconnection, nor retry logic
985 * should happen here. The higher level query() method is designed to handle those
986 * sorts of concerns. This method should not trigger such higher level methods.
987 *
988 * The lastError() and lastErrno() methods should meaningfully reflect what error,
989 * if any, occured during the last call to this method. Methods like executeQuery(),
990 * query(), select(), insert(), update(), delete(), and upsert() implement their calls
991 * to doQuery() such that an immediately subsequent call to lastError()/lastErrno()
992 * meaningfully reflects any error that occured during that public query method call.
993 *
994 * For SELECT queries, this returns either:
995 * - a) A driver-specific value/resource, only on success. This can be iterated
996 * over by calling fetchObject()/fetchRow() until there are no more rows.
997 * Alternatively, the result can be passed to resultObject() to obtain an
998 * IResultWrapper instance which can then be iterated over via "foreach".
999 * - b) False, on any query failure
1000 *
1001 * For non-SELECT queries, this returns either:
1002 * - a) A driver-specific value/resource, only on success
1003 * - b) True, only on success (e.g. no meaningful result other than "OK")
1004 * - c) False, on any query failure
1005 *
1006 * @param string $sql SQL query
1007 * @return mixed|bool An object, resource, or true on success; false on failure
1008 */
1009 abstract protected function doQuery( $sql );
1010
1011 /**
1012 * Determine whether a query writes to the DB. When in doubt, this returns true.
1013 *
1014 * Main use cases:
1015 *
1016 * - Subsequent web requests should not need to wait for replication from
1017 * the master position seen by this web request, unless this request made
1018 * changes to the master. This is handled by ChronologyProtector by checking
1019 * doneWrites() at the end of the request. doneWrites() returns true if any
1020 * query set lastWriteTime; which query() does based on isWriteQuery().
1021 *
1022 * - Reject write queries to replica DBs, in query().
1023 *
1024 * @param string $sql
1025 * @return bool
1026 */
1027 protected function isWriteQuery( $sql ) {
1028 // BEGIN and COMMIT queries are considered read queries here.
1029 // Database backends and drivers (MySQL, MariaDB, php-mysqli) generally
1030 // treat these as write queries, in that their results have "affected rows"
1031 // as meta data as from writes, instead of "num rows" as from reads.
1032 // But, we treat them as read queries because when reading data (from
1033 // either replica or master) we use transactions to enable repeatable-read
1034 // snapshots, which ensures we get consistent results from the same snapshot
1035 // for all queries within a request. Use cases:
1036 // - Treating these as writes would trigger ChronologyProtector (see method doc).
1037 // - We use this method to reject writes to replicas, but we need to allow
1038 // use of transactions on replicas for read snapshots. This is fine given
1039 // that transactions by themselves don't make changes, only actual writes
1040 // within the transaction matter, which we still detect.
1041 return !preg_match(
1042 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SAVEPOINT|RELEASE|SET|SHOW|EXPLAIN|USE|\(SELECT)\b/i',
1043 $sql
1044 );
1045 }
1046
1047 /**
1048 * @param string $sql
1049 * @return string|null
1050 */
1051 protected function getQueryVerb( $sql ) {
1052 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ? strtoupper( $m[1] ) : null;
1053 }
1054
1055 /**
1056 * Determine whether a SQL statement is sensitive to isolation level.
1057 *
1058 * A SQL statement is considered transactable if its result could vary
1059 * depending on the transaction isolation level. Operational commands
1060 * such as 'SET' and 'SHOW' are not considered to be transactable.
1061 *
1062 * Main purpose: Used by query() to decide whether to begin a transaction
1063 * before the current query (in DBO_TRX mode, on by default).
1064 *
1065 * @param string $sql
1066 * @return bool
1067 */
1068 protected function isTransactableQuery( $sql ) {
1069 return !in_array(
1070 $this->getQueryVerb( $sql ),
1071 [ 'BEGIN', 'ROLLBACK', 'COMMIT', 'SET', 'SHOW', 'CREATE', 'ALTER', 'USE', 'SHOW' ],
1072 true
1073 );
1074 }
1075
1076 /**
1077 * @param string $sql A SQL query
1078 * @param bool $pseudoPermanent Treat any table from CREATE TEMPORARY as pseudo-permanent
1079 * @return array A n-tuple of:
1080 * - int|null: A self::TEMP_* constant for temp table operations or null otherwise
1081 * - string|null: The name of the new temporary table $sql creates, or null
1082 * - string|null: The name of the temporary table that $sql drops, or null
1083 */
1084 protected function getTempWrites( $sql, $pseudoPermanent ) {
1085 static $qt = '[`"\']?(\w+)[`"\']?'; // quoted table
1086
1087 if ( preg_match(
1088 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?' . $qt . '/i',
1089 $sql,
1090 $matches
1091 ) ) {
1092 $type = $pseudoPermanent ? self::$TEMP_PSEUDO_PERMANENT : self::$TEMP_NORMAL;
1093
1094 return [ $type, $matches[1], null ];
1095 } elseif ( preg_match(
1096 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt . '/i',
1097 $sql,
1098 $matches
1099 ) ) {
1100 return [ $this->sessionTempTables[$matches[1]] ?? null, null, $matches[1] ];
1101 } elseif ( preg_match(
1102 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt . '/i',
1103 $sql,
1104 $matches
1105 ) ) {
1106 return [ $this->sessionTempTables[$matches[1]] ?? null, null, null ];
1107 } elseif ( preg_match(
1108 '/^(?:(?:INSERT|REPLACE)\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+' . $qt . '/i',
1109 $sql,
1110 $matches
1111 ) ) {
1112 return [ $this->sessionTempTables[$matches[1]] ?? null, null, null ];
1113 }
1114
1115 return [ null, null, null ];
1116 }
1117
1118 /**
1119 * @param IResultWrapper|bool $ret
1120 * @param int|null $tmpType TEMP_NORMAL or TEMP_PSEUDO_PERMANENT
1121 * @param string|null $tmpNew Name of created temp table
1122 * @param string|null $tmpDel Name of dropped temp table
1123 */
1124 protected function registerTempWrites( $ret, $tmpType, $tmpNew, $tmpDel ) {
1125 if ( $ret !== false ) {
1126 if ( $tmpNew !== null ) {
1127 $this->sessionTempTables[$tmpNew] = $tmpType;
1128 }
1129 if ( $tmpDel !== null ) {
1130 unset( $this->sessionTempTables[$tmpDel] );
1131 }
1132 }
1133 }
1134
1135 public function query( $sql, $fname = __METHOD__, $flags = 0 ) {
1136 $flags = (int)$flags; // b/c; this field used to be a bool
1137 // Sanity check that the SQL query is appropriate in the current context and is
1138 // allowed for an outside caller (e.g. does not break transaction/session tracking).
1139 $this->assertQueryIsCurrentlyAllowed( $sql, $fname );
1140
1141 // Send the query to the server and fetch any corresponding errors
1142 list( $ret, $err, $errno, $unignorable ) = $this->executeQuery( $sql, $fname, $flags );
1143 if ( $ret === false ) {
1144 $ignoreErrors = $this->fieldHasBit( $flags, self::QUERY_SILENCE_ERRORS );
1145 // Throw an error unless both the ignore flag was set and a rollback is not needed
1146 $this->reportQueryError( $err, $errno, $sql, $fname, $ignoreErrors && !$unignorable );
1147 }
1148
1149 return $this->resultObject( $ret );
1150 }
1151
1152 /**
1153 * Execute a query, retrying it if there is a recoverable connection loss
1154 *
1155 * This is similar to query() except:
1156 * - It does not prevent all non-ROLLBACK queries if there is a corrupted transaction
1157 * - It does not disallow raw queries that are supposed to use dedicated IDatabase methods
1158 * - It does not throw exceptions for common error cases
1159 *
1160 * This is meant for internal use with Database subclasses.
1161 *
1162 * @param string $sql Original SQL query
1163 * @param string $fname Name of the calling function
1164 * @param int $flags Bit field of class QUERY_* constants
1165 * @return array An n-tuple of:
1166 * - mixed|bool: An object, resource, or true on success; false on failure
1167 * - string: The result of calling lastError()
1168 * - int: The result of calling lastErrno()
1169 * - bool: Whether a rollback is needed to allow future non-rollback queries
1170 * @throws DBUnexpectedError
1171 */
1172 final protected function executeQuery( $sql, $fname, $flags ) {
1173 $this->assertHasConnectionHandle();
1174
1175 $priorTransaction = $this->trxLevel();
1176
1177 if ( $this->isWriteQuery( $sql ) ) {
1178 // In theory, non-persistent writes are allowed in read-only mode, but due to things
1179 // like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1180 $this->assertIsWritableMaster();
1181 // Do not treat temporary table writes as "meaningful writes" since they are only
1182 // visible to one session and are not permanent. Profile them as reads. Integration
1183 // tests can override this behavior via $flags.
1184 $pseudoPermanent = $this->fieldHasBit( $flags, self::QUERY_PSEUDO_PERMANENT );
1185 list( $tmpType, $tmpNew, $tmpDel ) = $this->getTempWrites( $sql, $pseudoPermanent );
1186 $isPermWrite = ( $tmpType !== self::$TEMP_NORMAL );
1187 // DBConnRef uses QUERY_REPLICA_ROLE to enforce the replica role for raw SQL queries
1188 if ( $isPermWrite && $this->fieldHasBit( $flags, self::QUERY_REPLICA_ROLE ) ) {
1189 throw new DBReadOnlyRoleError( $this, "Cannot write; target role is DB_REPLICA" );
1190 }
1191 } else {
1192 // No permanent writes in this query
1193 $isPermWrite = false;
1194 // No temporary tables written to either
1195 list( $tmpType, $tmpNew, $tmpDel ) = [ null, null, null ];
1196 }
1197
1198 // Add trace comment to the begin of the sql string, right after the operator.
1199 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598).
1200 $encAgent = str_replace( '/', '-', $this->agent );
1201 $commentedSql = preg_replace( '/\s|$/', " /* $fname $encAgent */ ", $sql, 1 );
1202
1203 // Send the query to the server and fetch any corresponding errors.
1204 // This also doubles as a "ping" to see if the connection was dropped.
1205 list( $ret, $err, $errno, $recoverableSR, $recoverableCL, $reconnected ) =
1206 $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1207
1208 // Check if the query failed due to a recoverable connection loss
1209 $allowRetry = !$this->fieldHasBit( $flags, self::QUERY_NO_RETRY );
1210 if ( $ret === false && $recoverableCL && $reconnected && $allowRetry ) {
1211 // Silently resend the query to the server since it is safe and possible
1212 list( $ret, $err, $errno, $recoverableSR, $recoverableCL ) =
1213 $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1214 }
1215
1216 // Register creation and dropping of temporary tables
1217 $this->registerTempWrites( $ret, $tmpType, $tmpNew, $tmpDel );
1218
1219 $corruptedTrx = false;
1220
1221 if ( $ret === false ) {
1222 if ( $priorTransaction ) {
1223 if ( $recoverableSR ) {
1224 # We're ignoring an error that caused just the current query to be aborted.
1225 # But log the cause so we can log a deprecation notice if a caller actually
1226 # does ignore it.
1227 $this->trxStatusIgnoredCause = [ $err, $errno, $fname ];
1228 } elseif ( !$recoverableCL ) {
1229 # Either the query was aborted or all queries after BEGIN where aborted.
1230 # In the first case, the only options going forward are (a) ROLLBACK, or
1231 # (b) ROLLBACK TO SAVEPOINT (if one was set). If the later case, the only
1232 # option is ROLLBACK, since the snapshots would have been released.
1233 $corruptedTrx = true; // cannot recover
1234 $this->trxStatus = self::STATUS_TRX_ERROR;
1235 $this->trxStatusCause =
1236 $this->getQueryExceptionAndLog( $err, $errno, $sql, $fname );
1237 $this->trxStatusIgnoredCause = null;
1238 }
1239 }
1240 }
1241
1242 return [ $ret, $err, $errno, $corruptedTrx ];
1243 }
1244
1245 /**
1246 * Wrapper for doQuery() that handles DBO_TRX, profiling, logging, affected row count
1247 * tracking, and reconnects (without retry) on query failure due to connection loss
1248 *
1249 * @param string $sql Original SQL query
1250 * @param string $commentedSql SQL query with debugging/trace comment
1251 * @param bool $isPermWrite Whether the query is a (non-temporary table) write
1252 * @param string $fname Name of the calling function
1253 * @param int $flags Bit field of class QUERY_* constants
1254 * @return array An n-tuple of:
1255 * - mixed|bool: An object, resource, or true on success; false on failure
1256 * - string: The result of calling lastError()
1257 * - int: The result of calling lastErrno()
1258 * - bool: Whether a statement rollback error occured
1259 * - bool: Whether a disconnect *both* happened *and* was recoverable
1260 * - bool: Whether a reconnection attempt was *both* made *and* succeeded
1261 * @throws DBUnexpectedError
1262 */
1263 private function executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags ) {
1264 $priorWritesPending = $this->writesOrCallbacksPending();
1265
1266 if ( ( $flags & self::QUERY_IGNORE_DBO_TRX ) == 0 ) {
1267 $this->beginIfImplied( $sql, $fname );
1268 }
1269
1270 // Keep track of whether the transaction has write queries pending
1271 if ( $isPermWrite ) {
1272 $this->lastWriteTime = microtime( true );
1273 if ( $this->trxLevel() && !$this->trxDoneWrites ) {
1274 $this->trxDoneWrites = true;
1275 $this->trxProfiler->transactionWritingIn(
1276 $this->server, $this->getDomainID(), $this->trxShortId );
1277 }
1278 }
1279
1280 $prefix = $this->getLBInfo( 'master' ) ? 'query-m: ' : 'query: ';
1281 $generalizedSql = new GeneralizedSql( $sql, $this->trxShortId, $prefix );
1282
1283 $startTime = microtime( true );
1284 $ps = $this->profiler
1285 ? ( $this->profiler )( $generalizedSql->stringify() )
1286 : null;
1287 $this->affectedRowCount = null;
1288 $this->lastQuery = $sql;
1289 $ret = $this->doQuery( $commentedSql );
1290 $lastError = $this->lastError();
1291 $lastErrno = $this->lastErrno();
1292
1293 $this->affectedRowCount = $this->affectedRows();
1294 unset( $ps ); // profile out (if set)
1295 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1296
1297 $recoverableSR = false; // recoverable statement rollback?
1298 $recoverableCL = false; // recoverable connection loss?
1299 $reconnected = false; // reconnection both attempted and succeeded?
1300
1301 if ( $ret !== false ) {
1302 $this->lastPing = $startTime;
1303 if ( $isPermWrite && $this->trxLevel() ) {
1304 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1305 $this->trxWriteCallers[] = $fname;
1306 }
1307 } elseif ( $this->wasConnectionError( $lastErrno ) ) {
1308 # Check if no meaningful session state was lost
1309 $recoverableCL = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1310 # Update session state tracking and try to restore the connection
1311 $reconnected = $this->replaceLostConnection( __METHOD__ );
1312 } else {
1313 # Check if only the last query was rolled back
1314 $recoverableSR = $this->wasKnownStatementRollbackError();
1315 }
1316
1317 if ( $sql === self::$PING_QUERY ) {
1318 $this->lastRoundTripEstimate = $queryRuntime;
1319 }
1320
1321 $this->trxProfiler->recordQueryCompletion(
1322 $generalizedSql,
1323 $startTime,
1324 $isPermWrite,
1325 $isPermWrite ? $this->affectedRows() : $this->numRows( $ret )
1326 );
1327
1328 // Avoid the overhead of logging calls unless debug mode is enabled
1329 if ( $this->getFlag( self::DBO_DEBUG ) ) {
1330 $this->queryLogger->debug(
1331 "{method} [{runtime}s] {db_host}: $sql",
1332 [
1333 'method' => $fname,
1334 'db_host' => $this->getServer(),
1335 'domain' => $this->getDomainID(),
1336 'runtime' => round( $queryRuntime, 3 )
1337 ]
1338 );
1339 }
1340
1341 return [ $ret, $lastError, $lastErrno, $recoverableSR, $recoverableCL, $reconnected ];
1342 }
1343
1344 /**
1345 * Start an implicit transaction if DBO_TRX is enabled and no transaction is active
1346 *
1347 * @param string $sql
1348 * @param string $fname
1349 */
1350 private function beginIfImplied( $sql, $fname ) {
1351 if (
1352 !$this->trxLevel() &&
1353 $this->getFlag( self::DBO_TRX ) &&
1354 $this->isTransactableQuery( $sql )
1355 ) {
1356 $this->begin( __METHOD__ . " ($fname)", self::TRANSACTION_INTERNAL );
1357 $this->trxAutomatic = true;
1358 }
1359 }
1360
1361 /**
1362 * Update the estimated run-time of a query, not counting large row lock times
1363 *
1364 * LoadBalancer can be set to rollback transactions that will create huge replication
1365 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1366 * queries, like inserting a row can take a long time due to row locking. This method
1367 * uses some simple heuristics to discount those cases.
1368 *
1369 * @param string $sql A SQL write query
1370 * @param float $runtime Total runtime, including RTT
1371 * @param int $affected Affected row count
1372 */
1373 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1374 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1375 $indicativeOfReplicaRuntime = true;
1376 if ( $runtime > self::$SLOW_WRITE_SEC ) {
1377 $verb = $this->getQueryVerb( $sql );
1378 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1379 if ( $verb === 'INSERT' ) {
1380 $indicativeOfReplicaRuntime = $this->affectedRows() > self::$SMALL_WRITE_ROWS;
1381 } elseif ( $verb === 'REPLACE' ) {
1382 $indicativeOfReplicaRuntime = $this->affectedRows() > self::$SMALL_WRITE_ROWS / 2;
1383 }
1384 }
1385
1386 $this->trxWriteDuration += $runtime;
1387 $this->trxWriteQueryCount += 1;
1388 $this->trxWriteAffectedRows += $affected;
1389 if ( $indicativeOfReplicaRuntime ) {
1390 $this->trxWriteAdjDuration += $runtime;
1391 $this->trxWriteAdjQueryCount += 1;
1392 }
1393 }
1394
1395 /**
1396 * Error out if the DB is not in a valid state for a query via query()
1397 *
1398 * @param string $sql
1399 * @param string $fname
1400 * @throws DBTransactionStateError
1401 */
1402 private function assertQueryIsCurrentlyAllowed( $sql, $fname ) {
1403 $verb = $this->getQueryVerb( $sql );
1404 if ( $verb === 'USE' ) {
1405 throw new DBUnexpectedError( $this, "Got USE query; use selectDomain() instead" );
1406 }
1407
1408 if ( $verb === 'ROLLBACK' ) { // transaction/savepoint
1409 return;
1410 }
1411
1412 if ( $this->trxStatus < self::STATUS_TRX_OK ) {
1413 throw new DBTransactionStateError(
1414 $this,
1415 "Cannot execute query from $fname while transaction status is ERROR",
1416 [],
1417 $this->trxStatusCause
1418 );
1419 } elseif ( $this->trxStatus === self::STATUS_TRX_OK && $this->trxStatusIgnoredCause ) {
1420 list( $iLastError, $iLastErrno, $iFname ) = $this->trxStatusIgnoredCause;
1421 call_user_func( $this->deprecationLogger,
1422 "Caller from $fname ignored an error originally raised from $iFname: " .
1423 "[$iLastErrno] $iLastError"
1424 );
1425 $this->trxStatusIgnoredCause = null;
1426 }
1427 }
1428
1429 public function assertNoOpenTransactions() {
1430 if ( $this->explicitTrxActive() ) {
1431 throw new DBTransactionError(
1432 $this,
1433 "Explicit transaction still active. A caller may have caught an error. "
1434 . "Open transactions: " . $this->flatAtomicSectionList()
1435 );
1436 }
1437 }
1438
1439 /**
1440 * Determine whether it is safe to retry queries after a database connection is lost
1441 *
1442 * @param string $sql SQL query
1443 * @param bool $priorWritesPending Whether there is a transaction open with
1444 * possible write queries or transaction pre-commit/idle callbacks
1445 * waiting on it to finish.
1446 * @return bool True if it is safe to retry the query, false otherwise
1447 */
1448 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1449 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1450 # Dropped connections also mean that named locks are automatically released.
1451 # Only allow error suppression in autocommit mode or when the lost transaction
1452 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1453 if ( $this->sessionNamedLocks ) {
1454 return false; // possible critical section violation
1455 } elseif ( $this->sessionTempTables ) {
1456 return false; // tables might be queried latter
1457 } elseif ( $sql === 'COMMIT' ) {
1458 return !$priorWritesPending; // nothing written anyway? (T127428)
1459 } elseif ( $sql === 'ROLLBACK' ) {
1460 return true; // transaction lost...which is also what was requested :)
1461 } elseif ( $this->explicitTrxActive() ) {
1462 return false; // don't drop atomocity and explicit snapshots
1463 } elseif ( $priorWritesPending ) {
1464 return false; // prior writes lost from implicit transaction
1465 }
1466
1467 return true;
1468 }
1469
1470 /**
1471 * Clean things up after session (and thus transaction) loss before reconnect
1472 */
1473 private function handleSessionLossPreconnect() {
1474 // Clean up tracking of session-level things...
1475 // https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
1476 // https://www.postgresql.org/docs/9.2/static/sql-createtable.html (ignoring ON COMMIT)
1477 $this->sessionTempTables = [];
1478 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1479 // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1480 $this->sessionNamedLocks = [];
1481 // Session loss implies transaction loss
1482 $oldTrxShortId = $this->consumeTrxShortId();
1483 $this->trxAtomicCounter = 0;
1484 $this->trxIdleCallbacks = []; // T67263; transaction already lost
1485 $this->trxPreCommitCallbacks = []; // T67263; transaction already lost
1486 // @note: leave trxRecurringCallbacks in place
1487 if ( $this->trxDoneWrites ) {
1488 $this->trxProfiler->transactionWritingOut(
1489 $this->server,
1490 $this->getDomainID(),
1491 $oldTrxShortId,
1492 $this->pendingWriteQueryDuration( self::ESTIMATE_TOTAL ),
1493 $this->trxWriteAffectedRows
1494 );
1495 }
1496 }
1497
1498 /**
1499 * Clean things up after session (and thus transaction) loss after reconnect
1500 */
1501 private function handleSessionLossPostconnect() {
1502 try {
1503 // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
1504 // If callback suppression is set then the array will remain unhandled.
1505 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
1506 } catch ( Exception $ex ) {
1507 // Already logged; move on...
1508 }
1509 try {
1510 // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener()
1511 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
1512 } catch ( Exception $ex ) {
1513 // Already logged; move on...
1514 }
1515 }
1516
1517 /**
1518 * Reset the transaction ID and return the old one
1519 *
1520 * @return string The old transaction ID or the empty string if there wasn't one
1521 */
1522 private function consumeTrxShortId() {
1523 $old = $this->trxShortId;
1524 $this->trxShortId = '';
1525
1526 return $old;
1527 }
1528
1529 /**
1530 * Checks whether the cause of the error is detected to be a timeout.
1531 *
1532 * It returns false by default, and not all engines support detecting this yet.
1533 * If this returns false, it will be treated as a generic query error.
1534 *
1535 * @param string $error Error text
1536 * @param int $errno Error number
1537 * @return bool
1538 */
1539 protected function wasQueryTimeout( $error, $errno ) {
1540 return false;
1541 }
1542
1543 /**
1544 * Report a query error. Log the error, and if neither the object ignore
1545 * flag nor the $ignoreErrors flag is set, throw a DBQueryError.
1546 *
1547 * @param string $error
1548 * @param int $errno
1549 * @param string $sql
1550 * @param string $fname
1551 * @param bool $ignore
1552 * @throws DBQueryError
1553 */
1554 public function reportQueryError( $error, $errno, $sql, $fname, $ignore = false ) {
1555 if ( $ignore ) {
1556 $this->queryLogger->debug( "SQL ERROR (ignored): $error" );
1557 } else {
1558 throw $this->getQueryExceptionAndLog( $error, $errno, $sql, $fname );
1559 }
1560 }
1561
1562 /**
1563 * @param string $error
1564 * @param string|int $errno
1565 * @param string $sql
1566 * @param string $fname
1567 * @return DBError
1568 */
1569 private function getQueryExceptionAndLog( $error, $errno, $sql, $fname ) {
1570 $this->queryLogger->error(
1571 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1572 $this->getLogContext( [
1573 'method' => __METHOD__,
1574 'errno' => $errno,
1575 'error' => $error,
1576 'sql1line' => mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 ),
1577 'fname' => $fname,
1578 'trace' => ( new RuntimeException() )->getTraceAsString()
1579 ] )
1580 );
1581
1582 if ( $this->wasQueryTimeout( $error, $errno ) ) {
1583 $e = new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1584 } elseif ( $this->wasConnectionError( $errno ) ) {
1585 $e = new DBQueryDisconnectedError( $this, $error, $errno, $sql, $fname );
1586 } else {
1587 $e = new DBQueryError( $this, $error, $errno, $sql, $fname );
1588 }
1589
1590 return $e;
1591 }
1592
1593 /**
1594 * @param string $error
1595 * @return DBConnectionError
1596 */
1597 final protected function newExceptionAfterConnectError( $error ) {
1598 // Connection was not fully initialized and is not safe for use
1599 $this->conn = null;
1600
1601 $this->connLogger->error(
1602 "Error connecting to {db_server} as user {db_user}: {error}",
1603 $this->getLogContext( [
1604 'error' => $error,
1605 'trace' => ( new RuntimeException() )->getTraceAsString()
1606 ] )
1607 );
1608
1609 return new DBConnectionError( $this, $error );
1610 }
1611
1612 public function freeResult( $res ) {
1613 }
1614
1615 public function selectField(
1616 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1617 ) {
1618 if ( $var === '*' ) { // sanity
1619 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1620 }
1621
1622 if ( !is_array( $options ) ) {
1623 $options = [ $options ];
1624 }
1625
1626 $options['LIMIT'] = 1;
1627
1628 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1629 if ( $res === false ) {
1630 throw new DBUnexpectedError( $this, "Got false from select()" );
1631 }
1632
1633 $row = $this->fetchRow( $res );
1634 if ( $row === false ) {
1635 return false;
1636 }
1637
1638 return reset( $row );
1639 }
1640
1641 public function selectFieldValues(
1642 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1643 ) {
1644 if ( $var === '*' ) { // sanity
1645 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1646 } elseif ( !is_string( $var ) ) { // sanity
1647 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1648 }
1649
1650 if ( !is_array( $options ) ) {
1651 $options = [ $options ];
1652 }
1653
1654 $res = $this->select( $table, [ 'value' => $var ], $cond, $fname, $options, $join_conds );
1655 if ( $res === false ) {
1656 throw new DBUnexpectedError( $this, "Got false from select()" );
1657 }
1658
1659 $values = [];
1660 foreach ( $res as $row ) {
1661 $values[] = $row->value;
1662 }
1663
1664 return $values;
1665 }
1666
1667 /**
1668 * Returns an optional USE INDEX clause to go after the table, and a
1669 * string to go at the end of the query.
1670 *
1671 * @param array $options Associative array of options to be turned into
1672 * an SQL query, valid keys are listed in the function.
1673 * @return array
1674 * @see Database::select()
1675 */
1676 protected function makeSelectOptions( $options ) {
1677 $preLimitTail = $postLimitTail = '';
1678 $startOpts = '';
1679
1680 $noKeyOptions = [];
1681
1682 foreach ( $options as $key => $option ) {
1683 if ( is_numeric( $key ) ) {
1684 $noKeyOptions[$option] = true;
1685 }
1686 }
1687
1688 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1689
1690 $preLimitTail .= $this->makeOrderBy( $options );
1691
1692 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1693 $postLimitTail .= ' FOR UPDATE';
1694 }
1695
1696 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1697 $postLimitTail .= ' LOCK IN SHARE MODE';
1698 }
1699
1700 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1701 $startOpts .= 'DISTINCT';
1702 }
1703
1704 # Various MySQL extensions
1705 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1706 $startOpts .= ' /*! STRAIGHT_JOIN */';
1707 }
1708
1709 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1710 $startOpts .= ' SQL_BIG_RESULT';
1711 }
1712
1713 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1714 $startOpts .= ' SQL_BUFFER_RESULT';
1715 }
1716
1717 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1718 $startOpts .= ' SQL_SMALL_RESULT';
1719 }
1720
1721 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1722 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1723 }
1724
1725 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1726 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1727 } else {
1728 $useIndex = '';
1729 }
1730 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1731 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1732 } else {
1733 $ignoreIndex = '';
1734 }
1735
1736 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1737 }
1738
1739 /**
1740 * Returns an optional GROUP BY with an optional HAVING
1741 *
1742 * @param array $options Associative array of options
1743 * @return string
1744 * @see Database::select()
1745 * @since 1.21
1746 */
1747 protected function makeGroupByWithHaving( $options ) {
1748 $sql = '';
1749 if ( isset( $options['GROUP BY'] ) ) {
1750 $gb = is_array( $options['GROUP BY'] )
1751 ? implode( ',', $options['GROUP BY'] )
1752 : $options['GROUP BY'];
1753 $sql .= ' GROUP BY ' . $gb;
1754 }
1755 if ( isset( $options['HAVING'] ) ) {
1756 $having = is_array( $options['HAVING'] )
1757 ? $this->makeList( $options['HAVING'], self::LIST_AND )
1758 : $options['HAVING'];
1759 $sql .= ' HAVING ' . $having;
1760 }
1761
1762 return $sql;
1763 }
1764
1765 /**
1766 * Returns an optional ORDER BY
1767 *
1768 * @param array $options Associative array of options
1769 * @return string
1770 * @see Database::select()
1771 * @since 1.21
1772 */
1773 protected function makeOrderBy( $options ) {
1774 if ( isset( $options['ORDER BY'] ) ) {
1775 $ob = is_array( $options['ORDER BY'] )
1776 ? implode( ',', $options['ORDER BY'] )
1777 : $options['ORDER BY'];
1778
1779 return ' ORDER BY ' . $ob;
1780 }
1781
1782 return '';
1783 }
1784
1785 public function select(
1786 $table, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1787 ) {
1788 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1789
1790 return $this->query( $sql, $fname );
1791 }
1792
1793 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1794 $options = [], $join_conds = []
1795 ) {
1796 if ( is_array( $vars ) ) {
1797 $fields = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1798 } else {
1799 $fields = $vars;
1800 }
1801
1802 $options = (array)$options;
1803 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1804 ? $options['USE INDEX']
1805 : [];
1806 $ignoreIndexes = (
1807 isset( $options['IGNORE INDEX'] ) &&
1808 is_array( $options['IGNORE INDEX'] )
1809 )
1810 ? $options['IGNORE INDEX']
1811 : [];
1812
1813 if (
1814 $this->selectOptionsIncludeLocking( $options ) &&
1815 $this->selectFieldsOrOptionsAggregate( $vars, $options )
1816 ) {
1817 // Some DB types (postgres/oracle) disallow FOR UPDATE with aggregate
1818 // functions. Discourage use of such queries to encourage compatibility.
1819 call_user_func(
1820 $this->deprecationLogger,
1821 __METHOD__ . ": aggregation used with a locking SELECT ($fname)"
1822 );
1823 }
1824
1825 if ( is_array( $table ) ) {
1826 $from = ' FROM ' .
1827 $this->tableNamesWithIndexClauseOrJOIN(
1828 $table, $useIndexes, $ignoreIndexes, $join_conds );
1829 } elseif ( $table != '' ) {
1830 $from = ' FROM ' .
1831 $this->tableNamesWithIndexClauseOrJOIN(
1832 [ $table ], $useIndexes, $ignoreIndexes, [] );
1833 } else {
1834 $from = '';
1835 }
1836
1837 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1838 $this->makeSelectOptions( $options );
1839
1840 if ( is_array( $conds ) ) {
1841 $conds = $this->makeList( $conds, self::LIST_AND );
1842 }
1843
1844 if ( $conds === null || $conds === false ) {
1845 $this->queryLogger->warning(
1846 __METHOD__
1847 . ' called from '
1848 . $fname
1849 . ' with incorrect parameters: $conds must be a string or an array'
1850 );
1851 $conds = '';
1852 }
1853
1854 if ( $conds === '' || $conds === '*' ) {
1855 $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex $preLimitTail";
1856 } elseif ( is_string( $conds ) ) {
1857 $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex " .
1858 "WHERE $conds $preLimitTail";
1859 } else {
1860 throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
1861 }
1862
1863 if ( isset( $options['LIMIT'] ) ) {
1864 $sql = $this->limitResult( $sql, $options['LIMIT'],
1865 $options['OFFSET'] ?? false );
1866 }
1867 $sql = "$sql $postLimitTail";
1868
1869 if ( isset( $options['EXPLAIN'] ) ) {
1870 $sql = 'EXPLAIN ' . $sql;
1871 }
1872
1873 return $sql;
1874 }
1875
1876 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1877 $options = [], $join_conds = []
1878 ) {
1879 $options = (array)$options;
1880 $options['LIMIT'] = 1;
1881
1882 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1883 if ( $res === false ) {
1884 throw new DBUnexpectedError( $this, "Got false from select()" );
1885 }
1886
1887 if ( !$this->numRows( $res ) ) {
1888 return false;
1889 }
1890
1891 return $this->fetchObject( $res );
1892 }
1893
1894 public function estimateRowCount(
1895 $table, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1896 ) {
1897 $conds = $this->normalizeConditions( $conds, $fname );
1898 $column = $this->extractSingleFieldFromList( $var );
1899 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1900 $conds[] = "$column IS NOT NULL";
1901 }
1902
1903 $res = $this->select(
1904 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1905 );
1906 $row = $res ? $this->fetchRow( $res ) : [];
1907
1908 return isset( $row['rowcount'] ) ? (int)$row['rowcount'] : 0;
1909 }
1910
1911 public function selectRowCount(
1912 $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1913 ) {
1914 $conds = $this->normalizeConditions( $conds, $fname );
1915 $column = $this->extractSingleFieldFromList( $var );
1916 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1917 $conds[] = "$column IS NOT NULL";
1918 }
1919
1920 $res = $this->select(
1921 [
1922 'tmp_count' => $this->buildSelectSubquery(
1923 $tables,
1924 '1',
1925 $conds,
1926 $fname,
1927 $options,
1928 $join_conds
1929 )
1930 ],
1931 [ 'rowcount' => 'COUNT(*)' ],
1932 [],
1933 $fname
1934 );
1935 $row = $res ? $this->fetchRow( $res ) : [];
1936
1937 return isset( $row['rowcount'] ) ? (int)$row['rowcount'] : 0;
1938 }
1939
1940 /**
1941 * @param string|array $options
1942 * @return bool
1943 */
1944 private function selectOptionsIncludeLocking( $options ) {
1945 $options = (array)$options;
1946 foreach ( [ 'FOR UPDATE', 'LOCK IN SHARE MODE' ] as $lock ) {
1947 if ( in_array( $lock, $options, true ) ) {
1948 return true;
1949 }
1950 }
1951
1952 return false;
1953 }
1954
1955 /**
1956 * @param array|string $fields
1957 * @param array|string $options
1958 * @return bool
1959 */
1960 private function selectFieldsOrOptionsAggregate( $fields, $options ) {
1961 foreach ( (array)$options as $key => $value ) {
1962 if ( is_string( $key ) ) {
1963 if ( preg_match( '/^(?:GROUP BY|HAVING)$/i', $key ) ) {
1964 return true;
1965 }
1966 } elseif ( is_string( $value ) ) {
1967 if ( preg_match( '/^(?:DISTINCT|DISTINCTROW)$/i', $value ) ) {
1968 return true;
1969 }
1970 }
1971 }
1972
1973 $regex = '/^(?:COUNT|MIN|MAX|SUM|GROUP_CONCAT|LISTAGG|ARRAY_AGG)\s*\\(/i';
1974 foreach ( (array)$fields as $field ) {
1975 if ( is_string( $field ) && preg_match( $regex, $field ) ) {
1976 return true;
1977 }
1978 }
1979
1980 return false;
1981 }
1982
1983 /**
1984 * @param array|string $conds
1985 * @param string $fname
1986 * @return array
1987 */
1988 final protected function normalizeConditions( $conds, $fname ) {
1989 if ( $conds === null || $conds === false ) {
1990 $this->queryLogger->warning(
1991 __METHOD__
1992 . ' called from '
1993 . $fname
1994 . ' with incorrect parameters: $conds must be a string or an array'
1995 );
1996 $conds = '';
1997 }
1998
1999 if ( !is_array( $conds ) ) {
2000 $conds = ( $conds === '' ) ? [] : [ $conds ];
2001 }
2002
2003 return $conds;
2004 }
2005
2006 /**
2007 * @param array|string $var Field parameter in the style of select()
2008 * @return string|null Column name or null; ignores aliases
2009 * @throws DBUnexpectedError Errors out if multiple columns are given
2010 */
2011 final protected function extractSingleFieldFromList( $var ) {
2012 if ( is_array( $var ) ) {
2013 if ( !$var ) {
2014 $column = null;
2015 } elseif ( count( $var ) == 1 ) {
2016 $column = $var[0] ?? reset( $var );
2017 } else {
2018 throw new DBUnexpectedError( $this, __METHOD__ . ': got multiple columns' );
2019 }
2020 } else {
2021 $column = $var;
2022 }
2023
2024 return $column;
2025 }
2026
2027 public function lockForUpdate(
2028 $table, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
2029 ) {
2030 if ( !$this->trxLevel() && !$this->getFlag( self::DBO_TRX ) ) {
2031 throw new DBUnexpectedError(
2032 $this,
2033 __METHOD__ . ': no transaction is active nor is DBO_TRX set'
2034 );
2035 }
2036
2037 $options = (array)$options;
2038 $options[] = 'FOR UPDATE';
2039
2040 return $this->selectRowCount( $table, '*', $conds, $fname, $options, $join_conds );
2041 }
2042
2043 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
2044 $info = $this->fieldInfo( $table, $field );
2045
2046 return (bool)$info;
2047 }
2048
2049 public function indexExists( $table, $index, $fname = __METHOD__ ) {
2050 if ( !$this->tableExists( $table ) ) {
2051 return null;
2052 }
2053
2054 $info = $this->indexInfo( $table, $index, $fname );
2055 if ( is_null( $info ) ) {
2056 return null;
2057 } else {
2058 return $info !== false;
2059 }
2060 }
2061
2062 abstract public function tableExists( $table, $fname = __METHOD__ );
2063
2064 public function indexUnique( $table, $index ) {
2065 $indexInfo = $this->indexInfo( $table, $index );
2066
2067 if ( !$indexInfo ) {
2068 return null;
2069 }
2070
2071 return !$indexInfo[0]->Non_unique;
2072 }
2073
2074 /**
2075 * Helper for Database::insert().
2076 *
2077 * @param array $options
2078 * @return string
2079 */
2080 protected function makeInsertOptions( $options ) {
2081 return implode( ' ', $options );
2082 }
2083
2084 public function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
2085 # No rows to insert, easy just return now
2086 if ( !count( $a ) ) {
2087 return true;
2088 }
2089
2090 $table = $this->tableName( $table );
2091
2092 if ( !is_array( $options ) ) {
2093 $options = [ $options ];
2094 }
2095
2096 $options = $this->makeInsertOptions( $options );
2097
2098 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
2099 $multi = true;
2100 $keys = array_keys( $a[0] );
2101 } else {
2102 $multi = false;
2103 $keys = array_keys( $a );
2104 }
2105
2106 $sql = 'INSERT ' . $options .
2107 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
2108
2109 if ( $multi ) {
2110 $first = true;
2111 foreach ( $a as $row ) {
2112 if ( $first ) {
2113 $first = false;
2114 } else {
2115 $sql .= ',';
2116 }
2117 $sql .= '(' . $this->makeList( $row ) . ')';
2118 }
2119 } else {
2120 $sql .= '(' . $this->makeList( $a ) . ')';
2121 }
2122
2123 $this->query( $sql, $fname );
2124
2125 return true;
2126 }
2127
2128 /**
2129 * Make UPDATE options array for Database::makeUpdateOptions
2130 *
2131 * @param array $options
2132 * @return array
2133 */
2134 protected function makeUpdateOptionsArray( $options ) {
2135 if ( !is_array( $options ) ) {
2136 $options = [ $options ];
2137 }
2138
2139 $opts = [];
2140
2141 if ( in_array( 'IGNORE', $options ) ) {
2142 $opts[] = 'IGNORE';
2143 }
2144
2145 return $opts;
2146 }
2147
2148 /**
2149 * Make UPDATE options for the Database::update function
2150 *
2151 * @param array $options The options passed to Database::update
2152 * @return string
2153 */
2154 protected function makeUpdateOptions( $options ) {
2155 $opts = $this->makeUpdateOptionsArray( $options );
2156
2157 return implode( ' ', $opts );
2158 }
2159
2160 public function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
2161 $table = $this->tableName( $table );
2162 $opts = $this->makeUpdateOptions( $options );
2163 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self::LIST_SET );
2164
2165 if ( $conds !== [] && $conds !== '*' ) {
2166 $sql .= " WHERE " . $this->makeList( $conds, self::LIST_AND );
2167 }
2168
2169 $this->query( $sql, $fname );
2170
2171 return true;
2172 }
2173
2174 public function makeList( $a, $mode = self::LIST_COMMA ) {
2175 if ( !is_array( $a ) ) {
2176 throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
2177 }
2178
2179 $first = true;
2180 $list = '';
2181
2182 foreach ( $a as $field => $value ) {
2183 if ( !$first ) {
2184 if ( $mode == self::LIST_AND ) {
2185 $list .= ' AND ';
2186 } elseif ( $mode == self::LIST_OR ) {
2187 $list .= ' OR ';
2188 } else {
2189 $list .= ',';
2190 }
2191 } else {
2192 $first = false;
2193 }
2194
2195 if ( ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_numeric( $field ) ) {
2196 $list .= "($value)";
2197 } elseif ( $mode == self::LIST_SET && is_numeric( $field ) ) {
2198 $list .= "$value";
2199 } elseif (
2200 ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_array( $value )
2201 ) {
2202 // Remove null from array to be handled separately if found
2203 $includeNull = false;
2204 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2205 $includeNull = true;
2206 unset( $value[$nullKey] );
2207 }
2208 if ( count( $value ) == 0 && !$includeNull ) {
2209 throw new InvalidArgumentException(
2210 __METHOD__ . ": empty input for field $field" );
2211 } elseif ( count( $value ) == 0 ) {
2212 // only check if $field is null
2213 $list .= "$field IS NULL";
2214 } else {
2215 // IN clause contains at least one valid element
2216 if ( $includeNull ) {
2217 // Group subconditions to ensure correct precedence
2218 $list .= '(';
2219 }
2220 if ( count( $value ) == 1 ) {
2221 // Special-case single values, as IN isn't terribly efficient
2222 // Don't necessarily assume the single key is 0; we don't
2223 // enforce linear numeric ordering on other arrays here.
2224 $value = array_values( $value )[0];
2225 $list .= $field . " = " . $this->addQuotes( $value );
2226 } else {
2227 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2228 }
2229 // if null present in array, append IS NULL
2230 if ( $includeNull ) {
2231 $list .= " OR $field IS NULL)";
2232 }
2233 }
2234 } elseif ( $value === null ) {
2235 if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
2236 $list .= "$field IS ";
2237 } elseif ( $mode == self::LIST_SET ) {
2238 $list .= "$field = ";
2239 }
2240 $list .= 'NULL';
2241 } else {
2242 if (
2243 $mode == self::LIST_AND || $mode == self::LIST_OR || $mode == self::LIST_SET
2244 ) {
2245 $list .= "$field = ";
2246 }
2247 $list .= $mode == self::LIST_NAMES ? $value : $this->addQuotes( $value );
2248 }
2249 }
2250
2251 return $list;
2252 }
2253
2254 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2255 $conds = [];
2256
2257 foreach ( $data as $base => $sub ) {
2258 if ( count( $sub ) ) {
2259 $conds[] = $this->makeList(
2260 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
2261 self::LIST_AND );
2262 }
2263 }
2264
2265 if ( $conds ) {
2266 return $this->makeList( $conds, self::LIST_OR );
2267 } else {
2268 // Nothing to search for...
2269 return false;
2270 }
2271 }
2272
2273 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2274 return $valuename;
2275 }
2276
2277 public function bitNot( $field ) {
2278 return "(~$field)";
2279 }
2280
2281 public function bitAnd( $fieldLeft, $fieldRight ) {
2282 return "($fieldLeft & $fieldRight)";
2283 }
2284
2285 public function bitOr( $fieldLeft, $fieldRight ) {
2286 return "($fieldLeft | $fieldRight)";
2287 }
2288
2289 public function buildConcat( $stringList ) {
2290 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2291 }
2292
2293 public function buildGroupConcatField(
2294 $delim, $table, $field, $conds = '', $join_conds = []
2295 ) {
2296 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2297
2298 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
2299 }
2300
2301 public function buildSubstring( $input, $startPosition, $length = null ) {
2302 $this->assertBuildSubstringParams( $startPosition, $length );
2303 $functionBody = "$input FROM $startPosition";
2304 if ( $length !== null ) {
2305 $functionBody .= " FOR $length";
2306 }
2307 return 'SUBSTRING(' . $functionBody . ')';
2308 }
2309
2310 /**
2311 * Check type and bounds for parameters to self::buildSubstring()
2312 *
2313 * All supported databases have substring functions that behave the same for
2314 * positive $startPosition and non-negative $length, but behaviors differ when
2315 * given 0 or negative $startPosition or negative $length. The simplest
2316 * solution to that is to just forbid those values.
2317 *
2318 * @param int $startPosition
2319 * @param int|null $length
2320 * @since 1.31
2321 */
2322 protected function assertBuildSubstringParams( $startPosition, $length ) {
2323 if ( !is_int( $startPosition ) || $startPosition <= 0 ) {
2324 throw new InvalidArgumentException(
2325 '$startPosition must be a positive integer'
2326 );
2327 }
2328 if ( !( is_int( $length ) && $length >= 0 || $length === null ) ) {
2329 throw new InvalidArgumentException(
2330 '$length must be null or an integer greater than or equal to 0'
2331 );
2332 }
2333 }
2334
2335 public function buildStringCast( $field ) {
2336 // In theory this should work for any standards-compliant
2337 // SQL implementation, although it may not be the best way to do it.
2338 return "CAST( $field AS CHARACTER )";
2339 }
2340
2341 public function buildIntegerCast( $field ) {
2342 return 'CAST( ' . $field . ' AS INTEGER )';
2343 }
2344
2345 public function buildSelectSubquery(
2346 $table, $vars, $conds = '', $fname = __METHOD__,
2347 $options = [], $join_conds = []
2348 ) {
2349 return new Subquery(
2350 $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2351 );
2352 }
2353
2354 public function databasesAreIndependent() {
2355 return false;
2356 }
2357
2358 final public function selectDB( $db ) {
2359 $this->selectDomain( new DatabaseDomain(
2360 $db,
2361 $this->currentDomain->getSchema(),
2362 $this->currentDomain->getTablePrefix()
2363 ) );
2364
2365 return true;
2366 }
2367
2368 final public function selectDomain( $domain ) {
2369 $this->doSelectDomain( DatabaseDomain::newFromId( $domain ) );
2370 }
2371
2372 /**
2373 * @param DatabaseDomain $domain
2374 * @throws DBConnectionError
2375 * @throws DBError
2376 * @since 1.32
2377 */
2378 protected function doSelectDomain( DatabaseDomain $domain ) {
2379 $this->currentDomain = $domain;
2380 }
2381
2382 public function getDBname() {
2383 return $this->currentDomain->getDatabase();
2384 }
2385
2386 public function getServer() {
2387 return $this->server;
2388 }
2389
2390 public function tableName( $name, $format = 'quoted' ) {
2391 if ( $name instanceof Subquery ) {
2392 throw new DBUnexpectedError(
2393 $this,
2394 __METHOD__ . ': got Subquery instance when expecting a string'
2395 );
2396 }
2397
2398 # Skip the entire process when we have a string quoted on both ends.
2399 # Note that we check the end so that we will still quote any use of
2400 # use of `database`.table. But won't break things if someone wants
2401 # to query a database table with a dot in the name.
2402 if ( $this->isQuotedIdentifier( $name ) ) {
2403 return $name;
2404 }
2405
2406 # Lets test for any bits of text that should never show up in a table
2407 # name. Basically anything like JOIN or ON which are actually part of
2408 # SQL queries, but may end up inside of the table value to combine
2409 # sql. Such as how the API is doing.
2410 # Note that we use a whitespace test rather than a \b test to avoid
2411 # any remote case where a word like on may be inside of a table name
2412 # surrounded by symbols which may be considered word breaks.
2413 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2414 $this->queryLogger->warning(
2415 __METHOD__ . ": use of subqueries is not supported this way",
2416 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
2417 );
2418
2419 return $name;
2420 }
2421
2422 # Split database and table into proper variables.
2423 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2424
2425 # Quote $table and apply the prefix if not quoted.
2426 # $tableName might be empty if this is called from Database::replaceVars()
2427 $tableName = "{$prefix}{$table}";
2428 if ( $format === 'quoted'
2429 && !$this->isQuotedIdentifier( $tableName )
2430 && $tableName !== ''
2431 ) {
2432 $tableName = $this->addIdentifierQuotes( $tableName );
2433 }
2434
2435 # Quote $schema and $database and merge them with the table name if needed
2436 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2437 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2438
2439 return $tableName;
2440 }
2441
2442 /**
2443 * Get the table components needed for a query given the currently selected database
2444 *
2445 * @param string $name Table name in the form of db.schema.table, db.table, or table
2446 * @return array (DB name or "" for default, schema name, table prefix, table name)
2447 */
2448 protected function qualifiedTableComponents( $name ) {
2449 # We reverse the explode so that database.table and table both output the correct table.
2450 $dbDetails = explode( '.', $name, 3 );
2451 if ( count( $dbDetails ) == 3 ) {
2452 list( $database, $schema, $table ) = $dbDetails;
2453 # We don't want any prefix added in this case
2454 $prefix = '';
2455 } elseif ( count( $dbDetails ) == 2 ) {
2456 list( $database, $table ) = $dbDetails;
2457 # We don't want any prefix added in this case
2458 $prefix = '';
2459 # In dbs that support it, $database may actually be the schema
2460 # but that doesn't affect any of the functionality here
2461 $schema = '';
2462 } else {
2463 list( $table ) = $dbDetails;
2464 if ( isset( $this->tableAliases[$table] ) ) {
2465 $database = $this->tableAliases[$table]['dbname'];
2466 $schema = is_string( $this->tableAliases[$table]['schema'] )
2467 ? $this->tableAliases[$table]['schema']
2468 : $this->relationSchemaQualifier();
2469 $prefix = is_string( $this->tableAliases[$table]['prefix'] )
2470 ? $this->tableAliases[$table]['prefix']
2471 : $this->tablePrefix();
2472 } else {
2473 $database = '';
2474 $schema = $this->relationSchemaQualifier(); # Default schema
2475 $prefix = $this->tablePrefix(); # Default prefix
2476 }
2477 }
2478
2479 return [ $database, $schema, $prefix, $table ];
2480 }
2481
2482 /**
2483 * @param string|null $namespace Database or schema
2484 * @param string $relation Name of table, view, sequence, etc...
2485 * @param string $format One of (raw, quoted)
2486 * @return string Relation name with quoted and merged $namespace as needed
2487 */
2488 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2489 if ( strlen( $namespace ) ) {
2490 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2491 $namespace = $this->addIdentifierQuotes( $namespace );
2492 }
2493 $relation = $namespace . '.' . $relation;
2494 }
2495
2496 return $relation;
2497 }
2498
2499 public function tableNames() {
2500 $inArray = func_get_args();
2501 $retVal = [];
2502
2503 foreach ( $inArray as $name ) {
2504 $retVal[$name] = $this->tableName( $name );
2505 }
2506
2507 return $retVal;
2508 }
2509
2510 public function tableNamesN() {
2511 $inArray = func_get_args();
2512 $retVal = [];
2513
2514 foreach ( $inArray as $name ) {
2515 $retVal[] = $this->tableName( $name );
2516 }
2517
2518 return $retVal;
2519 }
2520
2521 /**
2522 * Get an aliased table name
2523 *
2524 * This returns strings like "tableName AS newTableName" for aliased tables
2525 * and "(SELECT * from tableA) newTablename" for subqueries (e.g. derived tables)
2526 *
2527 * @see Database::tableName()
2528 * @param string|Subquery $table Table name or object with a 'sql' field
2529 * @param string|bool $alias Table alias (optional)
2530 * @return string SQL name for aliased table. Will not alias a table to its own name
2531 */
2532 protected function tableNameWithAlias( $table, $alias = false ) {
2533 if ( is_string( $table ) ) {
2534 $quotedTable = $this->tableName( $table );
2535 } elseif ( $table instanceof Subquery ) {
2536 $quotedTable = (string)$table;
2537 } else {
2538 throw new InvalidArgumentException( "Table must be a string or Subquery" );
2539 }
2540
2541 if ( $alias === false || $alias === $table ) {
2542 if ( $table instanceof Subquery ) {
2543 throw new InvalidArgumentException( "Subquery table missing alias" );
2544 }
2545
2546 return $quotedTable;
2547 } else {
2548 return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2549 }
2550 }
2551
2552 /**
2553 * Gets an array of aliased table names
2554 *
2555 * @param array $tables [ [alias] => table ]
2556 * @return string[] See tableNameWithAlias()
2557 */
2558 protected function tableNamesWithAlias( $tables ) {
2559 $retval = [];
2560 foreach ( $tables as $alias => $table ) {
2561 if ( is_numeric( $alias ) ) {
2562 $alias = $table;
2563 }
2564 $retval[] = $this->tableNameWithAlias( $table, $alias );
2565 }
2566
2567 return $retval;
2568 }
2569
2570 /**
2571 * Get an aliased field name
2572 * e.g. fieldName AS newFieldName
2573 *
2574 * @param string $name Field name
2575 * @param string|bool $alias Alias (optional)
2576 * @return string SQL name for aliased field. Will not alias a field to its own name
2577 */
2578 protected function fieldNameWithAlias( $name, $alias = false ) {
2579 if ( !$alias || (string)$alias === (string)$name ) {
2580 return $name;
2581 } else {
2582 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2583 }
2584 }
2585
2586 /**
2587 * Gets an array of aliased field names
2588 *
2589 * @param array $fields [ [alias] => field ]
2590 * @return string[] See fieldNameWithAlias()
2591 */
2592 protected function fieldNamesWithAlias( $fields ) {
2593 $retval = [];
2594 foreach ( $fields as $alias => $field ) {
2595 if ( is_numeric( $alias ) ) {
2596 $alias = $field;
2597 }
2598 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2599 }
2600
2601 return $retval;
2602 }
2603
2604 /**
2605 * Get the aliased table name clause for a FROM clause
2606 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2607 *
2608 * @param array $tables ( [alias] => table )
2609 * @param array $use_index Same as for select()
2610 * @param array $ignore_index Same as for select()
2611 * @param array $join_conds Same as for select()
2612 * @return string
2613 */
2614 protected function tableNamesWithIndexClauseOrJOIN(
2615 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2616 ) {
2617 $ret = [];
2618 $retJOIN = [];
2619 $use_index = (array)$use_index;
2620 $ignore_index = (array)$ignore_index;
2621 $join_conds = (array)$join_conds;
2622
2623 foreach ( $tables as $alias => $table ) {
2624 if ( !is_string( $alias ) ) {
2625 // No alias? Set it equal to the table name
2626 $alias = $table;
2627 }
2628
2629 if ( is_array( $table ) ) {
2630 // A parenthesized group
2631 if ( count( $table ) > 1 ) {
2632 $joinedTable = '(' .
2633 $this->tableNamesWithIndexClauseOrJOIN(
2634 $table, $use_index, $ignore_index, $join_conds ) . ')';
2635 } else {
2636 // Degenerate case
2637 $innerTable = reset( $table );
2638 $innerAlias = key( $table );
2639 $joinedTable = $this->tableNameWithAlias(
2640 $innerTable,
2641 is_string( $innerAlias ) ? $innerAlias : $innerTable
2642 );
2643 }
2644 } else {
2645 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2646 }
2647
2648 // Is there a JOIN clause for this table?
2649 if ( isset( $join_conds[$alias] ) ) {
2650 list( $joinType, $conds ) = $join_conds[$alias];
2651 $tableClause = $joinType;
2652 $tableClause .= ' ' . $joinedTable;
2653 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2654 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2655 if ( $use != '' ) {
2656 $tableClause .= ' ' . $use;
2657 }
2658 }
2659 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2660 $ignore = $this->ignoreIndexClause(
2661 implode( ',', (array)$ignore_index[$alias] ) );
2662 if ( $ignore != '' ) {
2663 $tableClause .= ' ' . $ignore;
2664 }
2665 }
2666 $on = $this->makeList( (array)$conds, self::LIST_AND );
2667 if ( $on != '' ) {
2668 $tableClause .= ' ON (' . $on . ')';
2669 }
2670
2671 $retJOIN[] = $tableClause;
2672 } elseif ( isset( $use_index[$alias] ) ) {
2673 // Is there an INDEX clause for this table?
2674 $tableClause = $joinedTable;
2675 $tableClause .= ' ' . $this->useIndexClause(
2676 implode( ',', (array)$use_index[$alias] )
2677 );
2678
2679 $ret[] = $tableClause;
2680 } elseif ( isset( $ignore_index[$alias] ) ) {
2681 // Is there an INDEX clause for this table?
2682 $tableClause = $joinedTable;
2683 $tableClause .= ' ' . $this->ignoreIndexClause(
2684 implode( ',', (array)$ignore_index[$alias] )
2685 );
2686
2687 $ret[] = $tableClause;
2688 } else {
2689 $tableClause = $joinedTable;
2690
2691 $ret[] = $tableClause;
2692 }
2693 }
2694
2695 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2696 $implicitJoins = implode( ',', $ret );
2697 $explicitJoins = implode( ' ', $retJOIN );
2698
2699 // Compile our final table clause
2700 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2701 }
2702
2703 /**
2704 * Allows for index remapping in queries where this is not consistent across DBMS
2705 *
2706 * @param string $index
2707 * @return string
2708 */
2709 protected function indexName( $index ) {
2710 return $this->indexAliases[$index] ?? $index;
2711 }
2712
2713 public function addQuotes( $s ) {
2714 if ( $s instanceof Blob ) {
2715 $s = $s->fetch();
2716 }
2717 if ( $s === null ) {
2718 return 'NULL';
2719 } elseif ( is_bool( $s ) ) {
2720 return (int)$s;
2721 } else {
2722 # This will also quote numeric values. This should be harmless,
2723 # and protects against weird problems that occur when they really
2724 # _are_ strings such as article titles and string->number->string
2725 # conversion is not 1:1.
2726 return "'" . $this->strencode( $s ) . "'";
2727 }
2728 }
2729
2730 public function addIdentifierQuotes( $s ) {
2731 return '"' . str_replace( '"', '""', $s ) . '"';
2732 }
2733
2734 /**
2735 * Returns if the given identifier looks quoted or not according to
2736 * the database convention for quoting identifiers .
2737 *
2738 * @note Do not use this to determine if untrusted input is safe.
2739 * A malicious user can trick this function.
2740 * @param string $name
2741 * @return bool
2742 */
2743 public function isQuotedIdentifier( $name ) {
2744 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2745 }
2746
2747 /**
2748 * @param string $s
2749 * @param string $escapeChar
2750 * @return string
2751 */
2752 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2753 return str_replace( [ $escapeChar, '%', '_' ],
2754 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2755 $s );
2756 }
2757
2758 public function buildLike( $param, ...$params ) {
2759 if ( is_array( $param ) ) {
2760 $params = $param;
2761 } else {
2762 $params = func_get_args();
2763 }
2764
2765 $s = '';
2766
2767 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2768 // may escape backslashes, creating problems of double escaping. The `
2769 // character has good cross-DBMS compatibility, avoiding special operators
2770 // in MS SQL like ^ and %
2771 $escapeChar = '`';
2772
2773 foreach ( $params as $value ) {
2774 if ( $value instanceof LikeMatch ) {
2775 $s .= $value->toString();
2776 } else {
2777 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2778 }
2779 }
2780
2781 return ' LIKE ' .
2782 $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2783 }
2784
2785 public function anyChar() {
2786 return new LikeMatch( '_' );
2787 }
2788
2789 public function anyString() {
2790 return new LikeMatch( '%' );
2791 }
2792
2793 public function nextSequenceValue( $seqName ) {
2794 return null;
2795 }
2796
2797 /**
2798 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2799 * is only needed because a) MySQL must be as efficient as possible due to
2800 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2801 * which index to pick. Anyway, other databases might have different
2802 * indexes on a given table. So don't bother overriding this unless you're
2803 * MySQL.
2804 * @param string $index
2805 * @return string
2806 */
2807 public function useIndexClause( $index ) {
2808 return '';
2809 }
2810
2811 /**
2812 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2813 * is only needed because a) MySQL must be as efficient as possible due to
2814 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2815 * which index to pick. Anyway, other databases might have different
2816 * indexes on a given table. So don't bother overriding this unless you're
2817 * MySQL.
2818 * @param string $index
2819 * @return string
2820 */
2821 public function ignoreIndexClause( $index ) {
2822 return '';
2823 }
2824
2825 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2826 if ( count( $rows ) == 0 ) {
2827 return;
2828 }
2829
2830 $uniqueIndexes = (array)$uniqueIndexes;
2831 // Single row case
2832 if ( !is_array( reset( $rows ) ) ) {
2833 $rows = [ $rows ];
2834 }
2835
2836 try {
2837 $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
2838 $affectedRowCount = 0;
2839 foreach ( $rows as $row ) {
2840 // Delete rows which collide with this one
2841 $indexWhereClauses = [];
2842 foreach ( $uniqueIndexes as $index ) {
2843 $indexColumns = (array)$index;
2844 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2845 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2846 throw new DBUnexpectedError(
2847 $this,
2848 'New record does not provide all values for unique key (' .
2849 implode( ', ', $indexColumns ) . ')'
2850 );
2851 } elseif ( in_array( null, $indexRowValues, true ) ) {
2852 throw new DBUnexpectedError(
2853 $this,
2854 'New record has a null value for unique key (' .
2855 implode( ', ', $indexColumns ) . ')'
2856 );
2857 }
2858 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND );
2859 }
2860
2861 if ( $indexWhereClauses ) {
2862 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR ), $fname );
2863 $affectedRowCount += $this->affectedRows();
2864 }
2865
2866 // Now insert the row
2867 $this->insert( $table, $row, $fname );
2868 $affectedRowCount += $this->affectedRows();
2869 }
2870 $this->endAtomic( $fname );
2871 $this->affectedRowCount = $affectedRowCount;
2872 } catch ( Exception $e ) {
2873 $this->cancelAtomic( $fname );
2874 throw $e;
2875 }
2876 }
2877
2878 /**
2879 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2880 * statement.
2881 *
2882 * @param string $table Table name
2883 * @param array|string $rows Row(s) to insert
2884 * @param string $fname Caller function name
2885 */
2886 protected function nativeReplace( $table, $rows, $fname ) {
2887 $table = $this->tableName( $table );
2888
2889 # Single row case
2890 if ( !is_array( reset( $rows ) ) ) {
2891 $rows = [ $rows ];
2892 }
2893
2894 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2895 $first = true;
2896
2897 foreach ( $rows as $row ) {
2898 if ( $first ) {
2899 $first = false;
2900 } else {
2901 $sql .= ',';
2902 }
2903
2904 $sql .= '(' . $this->makeList( $row ) . ')';
2905 }
2906
2907 $this->query( $sql, $fname );
2908 }
2909
2910 public function upsert( $table, array $rows, $uniqueIndexes, array $set,
2911 $fname = __METHOD__
2912 ) {
2913 if ( $rows === [] ) {
2914 return true; // nothing to do
2915 }
2916
2917 $uniqueIndexes = (array)$uniqueIndexes;
2918 if ( !is_array( reset( $rows ) ) ) {
2919 $rows = [ $rows ];
2920 }
2921
2922 if ( count( $uniqueIndexes ) ) {
2923 $clauses = []; // list WHERE clauses that each identify a single row
2924 foreach ( $rows as $row ) {
2925 foreach ( $uniqueIndexes as $index ) {
2926 $index = is_array( $index ) ? $index : [ $index ]; // columns
2927 $rowKey = []; // unique key to this row
2928 foreach ( $index as $column ) {
2929 $rowKey[$column] = $row[$column];
2930 }
2931 $clauses[] = $this->makeList( $rowKey, self::LIST_AND );
2932 }
2933 }
2934 $where = [ $this->makeList( $clauses, self::LIST_OR ) ];
2935 } else {
2936 $where = false;
2937 }
2938
2939 $affectedRowCount = 0;
2940 try {
2941 $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
2942 # Update any existing conflicting row(s)
2943 if ( $where !== false ) {
2944 $this->update( $table, $set, $where, $fname );
2945 $affectedRowCount += $this->affectedRows();
2946 }
2947 # Now insert any non-conflicting row(s)
2948 $this->insert( $table, $rows, $fname, [ 'IGNORE' ] );
2949 $affectedRowCount += $this->affectedRows();
2950 $this->endAtomic( $fname );
2951 $this->affectedRowCount = $affectedRowCount;
2952 } catch ( Exception $e ) {
2953 $this->cancelAtomic( $fname );
2954 throw $e;
2955 }
2956
2957 return true;
2958 }
2959
2960 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2961 $fname = __METHOD__
2962 ) {
2963 if ( !$conds ) {
2964 throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
2965 }
2966
2967 $delTable = $this->tableName( $delTable );
2968 $joinTable = $this->tableName( $joinTable );
2969 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2970 if ( $conds != '*' ) {
2971 $sql .= 'WHERE ' . $this->makeList( $conds, self::LIST_AND );
2972 }
2973 $sql .= ')';
2974
2975 $this->query( $sql, $fname );
2976 }
2977
2978 public function textFieldSize( $table, $field ) {
2979 $table = $this->tableName( $table );
2980 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\"";
2981 $res = $this->query( $sql, __METHOD__ );
2982 $row = $this->fetchObject( $res );
2983
2984 $m = [];
2985
2986 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2987 $size = $m[1];
2988 } else {
2989 $size = -1;
2990 }
2991
2992 return $size;
2993 }
2994
2995 public function delete( $table, $conds, $fname = __METHOD__ ) {
2996 if ( !$conds ) {
2997 throw new DBUnexpectedError( $this, __METHOD__ . ' called with no conditions' );
2998 }
2999
3000 $table = $this->tableName( $table );
3001 $sql = "DELETE FROM $table";
3002
3003 if ( $conds != '*' ) {
3004 if ( is_array( $conds ) ) {
3005 $conds = $this->makeList( $conds, self::LIST_AND );
3006 }
3007 $sql .= ' WHERE ' . $conds;
3008 }
3009
3010 $this->query( $sql, $fname );
3011
3012 return true;
3013 }
3014
3015 final public function insertSelect(
3016 $destTable, $srcTable, $varMap, $conds,
3017 $fname = __METHOD__, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3018 ) {
3019 static $hints = [ 'NO_AUTO_COLUMNS' ];
3020
3021 $insertOptions = (array)$insertOptions;
3022 $selectOptions = (array)$selectOptions;
3023
3024 if ( $this->cliMode && $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
3025 // For massive migrations with downtime, we don't want to select everything
3026 // into memory and OOM, so do all this native on the server side if possible.
3027 $this->nativeInsertSelect(
3028 $destTable,
3029 $srcTable,
3030 $varMap,
3031 $conds,
3032 $fname,
3033 array_diff( $insertOptions, $hints ),
3034 $selectOptions,
3035 $selectJoinConds
3036 );
3037 } else {
3038 $this->nonNativeInsertSelect(
3039 $destTable,
3040 $srcTable,
3041 $varMap,
3042 $conds,
3043 $fname,
3044 array_diff( $insertOptions, $hints ),
3045 $selectOptions,
3046 $selectJoinConds
3047 );
3048 }
3049
3050 return true;
3051 }
3052
3053 /**
3054 * @param array $insertOptions INSERT options
3055 * @param array $selectOptions SELECT options
3056 * @return bool Whether an INSERT SELECT with these options will be replication safe
3057 * @since 1.31
3058 */
3059 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
3060 return true;
3061 }
3062
3063 /**
3064 * Implementation of insertSelect() based on select() and insert()
3065 *
3066 * @see IDatabase::insertSelect()
3067 * @since 1.30
3068 * @param string $destTable
3069 * @param string|array $srcTable
3070 * @param array $varMap
3071 * @param array $conds
3072 * @param string $fname
3073 * @param array $insertOptions
3074 * @param array $selectOptions
3075 * @param array $selectJoinConds
3076 */
3077 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3078 $fname = __METHOD__,
3079 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3080 ) {
3081 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
3082 // on only the master (without needing row-based-replication). It also makes it easy to
3083 // know how big the INSERT is going to be.
3084 $fields = [];
3085 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
3086 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
3087 }
3088 $selectOptions[] = 'FOR UPDATE';
3089 $res = $this->select(
3090 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
3091 );
3092 if ( !$res ) {
3093 return;
3094 }
3095
3096 try {
3097 $affectedRowCount = 0;
3098 $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
3099 $rows = [];
3100 $ok = true;
3101 foreach ( $res as $row ) {
3102 $rows[] = (array)$row;
3103
3104 // Avoid inserts that are too huge
3105 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize ) {
3106 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
3107 if ( !$ok ) {
3108 break;
3109 }
3110 $affectedRowCount += $this->affectedRows();
3111 $rows = [];
3112 }
3113 }
3114 if ( $rows && $ok ) {
3115 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
3116 if ( $ok ) {
3117 $affectedRowCount += $this->affectedRows();
3118 }
3119 }
3120 if ( $ok ) {
3121 $this->endAtomic( $fname );
3122 $this->affectedRowCount = $affectedRowCount;
3123 } else {
3124 $this->cancelAtomic( $fname );
3125 }
3126 } catch ( Exception $e ) {
3127 $this->cancelAtomic( $fname );
3128 throw $e;
3129 }
3130 }
3131
3132 /**
3133 * Native server-side implementation of insertSelect() for situations where
3134 * we don't want to select everything into memory
3135 *
3136 * @see IDatabase::insertSelect()
3137 * @param string $destTable
3138 * @param string|array $srcTable
3139 * @param array $varMap
3140 * @param array $conds
3141 * @param string $fname
3142 * @param array $insertOptions
3143 * @param array $selectOptions
3144 * @param array $selectJoinConds
3145 */
3146 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3147 $fname = __METHOD__,
3148 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3149 ) {
3150 $destTable = $this->tableName( $destTable );
3151
3152 if ( !is_array( $insertOptions ) ) {
3153 $insertOptions = [ $insertOptions ];
3154 }
3155
3156 $insertOptions = $this->makeInsertOptions( $insertOptions );
3157
3158 $selectSql = $this->selectSQLText(
3159 $srcTable,
3160 array_values( $varMap ),
3161 $conds,
3162 $fname,
3163 $selectOptions,
3164 $selectJoinConds
3165 );
3166
3167 $sql = "INSERT $insertOptions" .
3168 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
3169 $selectSql;
3170
3171 $this->query( $sql, $fname );
3172 }
3173
3174 public function limitResult( $sql, $limit, $offset = false ) {
3175 if ( !is_numeric( $limit ) ) {
3176 throw new DBUnexpectedError(
3177 $this,
3178 "Invalid non-numeric limit passed to " . __METHOD__
3179 );
3180 }
3181 // This version works in MySQL and SQLite. It will very likely need to be
3182 // overridden for most other RDBMS subclasses.
3183 return "$sql LIMIT "
3184 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
3185 . "{$limit} ";
3186 }
3187
3188 public function unionSupportsOrderAndLimit() {
3189 return true; // True for almost every DB supported
3190 }
3191
3192 public function unionQueries( $sqls, $all ) {
3193 $glue = $all ? ') UNION ALL (' : ') UNION (';
3194
3195 return '(' . implode( $glue, $sqls ) . ')';
3196 }
3197
3198 public function unionConditionPermutations(
3199 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__,
3200 $options = [], $join_conds = []
3201 ) {
3202 // First, build the Cartesian product of $permute_conds
3203 $conds = [ [] ];
3204 foreach ( $permute_conds as $field => $values ) {
3205 if ( !$values ) {
3206 // Skip empty $values
3207 continue;
3208 }
3209 $values = array_unique( $values ); // For sanity
3210 $newConds = [];
3211 foreach ( $conds as $cond ) {
3212 foreach ( $values as $value ) {
3213 $cond[$field] = $value;
3214 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
3215 }
3216 }
3217 $conds = $newConds;
3218 }
3219
3220 $extra_conds = $extra_conds === '' ? [] : (array)$extra_conds;
3221
3222 // If there's just one condition and no subordering, hand off to
3223 // selectSQLText directly.
3224 if ( count( $conds ) === 1 &&
3225 ( !isset( $options['INNER ORDER BY'] ) || !$this->unionSupportsOrderAndLimit() )
3226 ) {
3227 return $this->selectSQLText(
3228 $table, $vars, $conds[0] + $extra_conds, $fname, $options, $join_conds
3229 );
3230 }
3231
3232 // Otherwise, we need to pull out the order and limit to apply after
3233 // the union. Then build the SQL queries for each set of conditions in
3234 // $conds. Then union them together (using UNION ALL, because the
3235 // product *should* already be distinct).
3236 $orderBy = $this->makeOrderBy( $options );
3237 $limit = $options['LIMIT'] ?? null;
3238 $offset = $options['OFFSET'] ?? false;
3239 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
3240 if ( !$this->unionSupportsOrderAndLimit() ) {
3241 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
3242 } else {
3243 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
3244 $options['ORDER BY'] = $options['INNER ORDER BY'];
3245 }
3246 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
3247 // We need to increase the limit by the offset rather than
3248 // using the offset directly, otherwise it'll skip incorrectly
3249 // in the subqueries.
3250 $options['LIMIT'] = $limit + $offset;
3251 unset( $options['OFFSET'] );
3252 }
3253 }
3254
3255 $sqls = [];
3256 foreach ( $conds as $cond ) {
3257 $sqls[] = $this->selectSQLText(
3258 $table, $vars, $cond + $extra_conds, $fname, $options, $join_conds
3259 );
3260 }
3261 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
3262 if ( $limit !== null ) {
3263 $sql = $this->limitResult( $sql, $limit, $offset );
3264 }
3265
3266 return $sql;
3267 }
3268
3269 public function conditional( $cond, $trueVal, $falseVal ) {
3270 if ( is_array( $cond ) ) {
3271 $cond = $this->makeList( $cond, self::LIST_AND );
3272 }
3273
3274 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3275 }
3276
3277 public function strreplace( $orig, $old, $new ) {
3278 return "REPLACE({$orig}, {$old}, {$new})";
3279 }
3280
3281 public function getServerUptime() {
3282 return 0;
3283 }
3284
3285 public function wasDeadlock() {
3286 return false;
3287 }
3288
3289 public function wasLockTimeout() {
3290 return false;
3291 }
3292
3293 public function wasConnectionLoss() {
3294 return $this->wasConnectionError( $this->lastErrno() );
3295 }
3296
3297 public function wasReadOnlyError() {
3298 return false;
3299 }
3300
3301 public function wasErrorReissuable() {
3302 return (
3303 $this->wasDeadlock() ||
3304 $this->wasLockTimeout() ||
3305 $this->wasConnectionLoss()
3306 );
3307 }
3308
3309 /**
3310 * Do not use this method outside of Database/DBError classes
3311 *
3312 * @param int|string $errno
3313 * @return bool Whether the given query error was a connection drop
3314 */
3315 public function wasConnectionError( $errno ) {
3316 return false;
3317 }
3318
3319 /**
3320 * @return bool Whether it is known that the last query error only caused statement rollback
3321 * @note This is for backwards compatibility for callers catching DBError exceptions in
3322 * order to ignore problems like duplicate key errors or foriegn key violations
3323 * @since 1.31
3324 */
3325 protected function wasKnownStatementRollbackError() {
3326 return false; // don't know; it could have caused a transaction rollback
3327 }
3328
3329 public function deadlockLoop() {
3330 $args = func_get_args();
3331 $function = array_shift( $args );
3332 $tries = self::$DEADLOCK_TRIES;
3333
3334 $this->begin( __METHOD__ );
3335
3336 $retVal = null;
3337 /** @var Exception $e */
3338 $e = null;
3339 do {
3340 try {
3341 $retVal = $function( ...$args );
3342 break;
3343 } catch ( DBQueryError $e ) {
3344 if ( $this->wasDeadlock() ) {
3345 // Retry after a randomized delay
3346 usleep( mt_rand( self::$DEADLOCK_DELAY_MIN, self::$DEADLOCK_DELAY_MAX ) );
3347 } else {
3348 // Throw the error back up
3349 throw $e;
3350 }
3351 }
3352 } while ( --$tries > 0 );
3353
3354 if ( $tries <= 0 ) {
3355 // Too many deadlocks; give up
3356 $this->rollback( __METHOD__ );
3357 throw $e;
3358 } else {
3359 $this->commit( __METHOD__ );
3360
3361 return $retVal;
3362 }
3363 }
3364
3365 public function masterPosWait( DBMasterPos $pos, $timeout ) {
3366 # Real waits are implemented in the subclass.
3367 return 0;
3368 }
3369
3370 public function getReplicaPos() {
3371 # Stub
3372 return false;
3373 }
3374
3375 public function getMasterPos() {
3376 # Stub
3377 return false;
3378 }
3379
3380 public function serverIsReadOnly() {
3381 return false;
3382 }
3383
3384 final public function onTransactionResolution( callable $callback, $fname = __METHOD__ ) {
3385 if ( !$this->trxLevel() ) {
3386 throw new DBUnexpectedError( $this, "No transaction is active" );
3387 }
3388 $this->trxEndCallbacks[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3389 }
3390
3391 final public function onTransactionCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
3392 if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
3393 // Start an implicit transaction similar to how query() does
3394 $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
3395 $this->trxAutomatic = true;
3396 }
3397
3398 $this->trxIdleCallbacks[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3399 if ( !$this->trxLevel() ) {
3400 $this->runOnTransactionIdleCallbacks( self::TRIGGER_IDLE );
3401 }
3402 }
3403
3404 final public function onTransactionIdle( callable $callback, $fname = __METHOD__ ) {
3405 $this->onTransactionCommitOrIdle( $callback, $fname );
3406 }
3407
3408 final public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
3409 if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
3410 // Start an implicit transaction similar to how query() does
3411 $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
3412 $this->trxAutomatic = true;
3413 }
3414
3415 if ( $this->trxLevel() ) {
3416 $this->trxPreCommitCallbacks[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3417 } else {
3418 // No transaction is active nor will start implicitly, so make one for this callback
3419 $this->startAtomic( __METHOD__, self::ATOMIC_CANCELABLE );
3420 try {
3421 $callback( $this );
3422 $this->endAtomic( __METHOD__ );
3423 } catch ( Exception $e ) {
3424 $this->cancelAtomic( __METHOD__ );
3425 throw $e;
3426 }
3427 }
3428 }
3429
3430 final public function onAtomicSectionCancel( callable $callback, $fname = __METHOD__ ) {
3431 if ( !$this->trxLevel() || !$this->trxAtomicLevels ) {
3432 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3433 }
3434 $this->trxSectionCancelCallbacks[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3435 }
3436
3437 /**
3438 * @return AtomicSectionIdentifier|null ID of the topmost atomic section level
3439 */
3440 private function currentAtomicSectionId() {
3441 if ( $this->trxLevel() && $this->trxAtomicLevels ) {
3442 $levelInfo = end( $this->trxAtomicLevels );
3443
3444 return $levelInfo[1];
3445 }
3446
3447 return null;
3448 }
3449
3450 /**
3451 * Hoist callback ownership for callbacks in a section to a parent section.
3452 * All callbacks should have an owner that is present in trxAtomicLevels.
3453 * @param AtomicSectionIdentifier $old
3454 * @param AtomicSectionIdentifier $new
3455 */
3456 private function reassignCallbacksForSection(
3457 AtomicSectionIdentifier $old, AtomicSectionIdentifier $new
3458 ) {
3459 foreach ( $this->trxPreCommitCallbacks as $key => $info ) {
3460 if ( $info[2] === $old ) {
3461 $this->trxPreCommitCallbacks[$key][2] = $new;
3462 }
3463 }
3464 foreach ( $this->trxIdleCallbacks as $key => $info ) {
3465 if ( $info[2] === $old ) {
3466 $this->trxIdleCallbacks[$key][2] = $new;
3467 }
3468 }
3469 foreach ( $this->trxEndCallbacks as $key => $info ) {
3470 if ( $info[2] === $old ) {
3471 $this->trxEndCallbacks[$key][2] = $new;
3472 }
3473 }
3474 foreach ( $this->trxSectionCancelCallbacks as $key => $info ) {
3475 if ( $info[2] === $old ) {
3476 $this->trxSectionCancelCallbacks[$key][2] = $new;
3477 }
3478 }
3479 }
3480
3481 /**
3482 * Update callbacks that were owned by cancelled atomic sections.
3483 *
3484 * Callbacks for "on commit" should never be run if they're owned by a
3485 * section that won't be committed.
3486 *
3487 * Callbacks for "on resolution" need to reflect that the section was
3488 * rolled back, even if the transaction as a whole commits successfully.
3489 *
3490 * Callbacks for "on section cancel" should already have been consumed,
3491 * but errors during the cancellation itself can prevent that while still
3492 * destroying the section. Hoist any such callbacks to the new top section,
3493 * which we assume will itself have to be cancelled or rolled back to
3494 * resolve the error.
3495 *
3496 * @param AtomicSectionIdentifier[] $sectionIds ID of an actual savepoint
3497 * @param AtomicSectionIdentifier|null $newSectionId New top section ID.
3498 * @throws UnexpectedValueException
3499 */
3500 private function modifyCallbacksForCancel(
3501 array $sectionIds, AtomicSectionIdentifier $newSectionId = null
3502 ) {
3503 // Cancel the "on commit" callbacks owned by this savepoint
3504 $this->trxIdleCallbacks = array_filter(
3505 $this->trxIdleCallbacks,
3506 function ( $entry ) use ( $sectionIds ) {
3507 return !in_array( $entry[2], $sectionIds, true );
3508 }
3509 );
3510 $this->trxPreCommitCallbacks = array_filter(
3511 $this->trxPreCommitCallbacks,
3512 function ( $entry ) use ( $sectionIds ) {
3513 return !in_array( $entry[2], $sectionIds, true );
3514 }
3515 );
3516 // Make "on resolution" callbacks owned by this savepoint to perceive a rollback
3517 foreach ( $this->trxEndCallbacks as $key => $entry ) {
3518 if ( in_array( $entry[2], $sectionIds, true ) ) {
3519 $callback = $entry[0];
3520 $this->trxEndCallbacks[$key][0] = function () use ( $callback ) {
3521 // @phan-suppress-next-line PhanInfiniteRecursion No recursion at all here, phan is confused
3522 return $callback( self::TRIGGER_ROLLBACK, $this );
3523 };
3524 // This "on resolution" callback no longer belongs to a section.
3525 $this->trxEndCallbacks[$key][2] = null;
3526 }
3527 }
3528 // Hoist callback ownership for section cancel callbacks to the new top section
3529 foreach ( $this->trxSectionCancelCallbacks as $key => $entry ) {
3530 if ( in_array( $entry[2], $sectionIds, true ) ) {
3531 $this->trxSectionCancelCallbacks[$key][2] = $newSectionId;
3532 }
3533 }
3534 }
3535
3536 final public function setTransactionListener( $name, callable $callback = null ) {
3537 if ( $callback ) {
3538 $this->trxRecurringCallbacks[$name] = $callback;
3539 } else {
3540 unset( $this->trxRecurringCallbacks[$name] );
3541 }
3542 }
3543
3544 /**
3545 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
3546 *
3547 * This method should not be used outside of Database/LoadBalancer
3548 *
3549 * @param bool $suppress
3550 * @since 1.28
3551 */
3552 final public function setTrxEndCallbackSuppression( $suppress ) {
3553 $this->trxEndCallbacksSuppressed = $suppress;
3554 }
3555
3556 /**
3557 * Actually consume and run any "on transaction idle/resolution" callbacks.
3558 *
3559 * This method should not be used outside of Database/LoadBalancer
3560 *
3561 * @param int $trigger IDatabase::TRIGGER_* constant
3562 * @return int Number of callbacks attempted
3563 * @since 1.20
3564 * @throws Exception
3565 */
3566 public function runOnTransactionIdleCallbacks( $trigger ) {
3567 if ( $this->trxLevel() ) { // sanity
3568 throw new DBUnexpectedError( $this, __METHOD__ . ': a transaction is still open' );
3569 }
3570
3571 if ( $this->trxEndCallbacksSuppressed ) {
3572 return 0;
3573 }
3574
3575 $count = 0;
3576 $autoTrx = $this->getFlag( self::DBO_TRX ); // automatic begin() enabled?
3577 /** @var Exception $e */
3578 $e = null; // first exception
3579 do { // callbacks may add callbacks :)
3580 $callbacks = array_merge(
3581 $this->trxIdleCallbacks,
3582 $this->trxEndCallbacks // include "transaction resolution" callbacks
3583 );
3584 $this->trxIdleCallbacks = []; // consumed (and recursion guard)
3585 $this->trxEndCallbacks = []; // consumed (recursion guard)
3586
3587 // Only run trxSectionCancelCallbacks on rollback, not commit.
3588 // But always consume them.
3589 if ( $trigger === self::TRIGGER_ROLLBACK ) {
3590 $callbacks = array_merge( $callbacks, $this->trxSectionCancelCallbacks );
3591 }
3592 $this->trxSectionCancelCallbacks = []; // consumed (recursion guard)
3593
3594 foreach ( $callbacks as $callback ) {
3595 ++$count;
3596 list( $phpCallback ) = $callback;
3597 $this->clearFlag( self::DBO_TRX ); // make each query its own transaction
3598 try {
3599 // @phan-suppress-next-line PhanParamTooManyCallable
3600 call_user_func( $phpCallback, $trigger, $this );
3601 } catch ( Exception $ex ) {
3602 call_user_func( $this->errorLogger, $ex );
3603 $e = $e ?: $ex;
3604 // Some callbacks may use startAtomic/endAtomic, so make sure
3605 // their transactions are ended so other callbacks don't fail
3606 if ( $this->trxLevel() ) {
3607 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
3608 }
3609 } finally {
3610 if ( $autoTrx ) {
3611 $this->setFlag( self::DBO_TRX ); // restore automatic begin()
3612 } else {
3613 $this->clearFlag( self::DBO_TRX ); // restore auto-commit
3614 }
3615 }
3616 }
3617 } while ( count( $this->trxIdleCallbacks ) );
3618
3619 if ( $e instanceof Exception ) {
3620 throw $e; // re-throw any first exception
3621 }
3622
3623 return $count;
3624 }
3625
3626 /**
3627 * Actually consume and run any "on transaction pre-commit" callbacks.
3628 *
3629 * This method should not be used outside of Database/LoadBalancer
3630 *
3631 * @since 1.22
3632 * @return int Number of callbacks attempted
3633 * @throws Exception
3634 */
3635 public function runOnTransactionPreCommitCallbacks() {
3636 $count = 0;
3637
3638 $e = null; // first exception
3639 do { // callbacks may add callbacks :)
3640 $callbacks = $this->trxPreCommitCallbacks;
3641 $this->trxPreCommitCallbacks = []; // consumed (and recursion guard)
3642 foreach ( $callbacks as $callback ) {
3643 try {
3644 ++$count;
3645 list( $phpCallback ) = $callback;
3646 $phpCallback( $this );
3647 } catch ( Exception $ex ) {
3648 ( $this->errorLogger )( $ex );
3649 $e = $e ?: $ex;
3650 }
3651 }
3652 } while ( count( $this->trxPreCommitCallbacks ) );
3653
3654 if ( $e instanceof Exception ) {
3655 throw $e; // re-throw any first exception
3656 }
3657
3658 return $count;
3659 }
3660
3661 /**
3662 * Actually run any "atomic section cancel" callbacks.
3663 *
3664 * @param int $trigger IDatabase::TRIGGER_* constant
3665 * @param AtomicSectionIdentifier[]|null $sectionIds Section IDs to cancel,
3666 * null on transaction rollback
3667 */
3668 private function runOnAtomicSectionCancelCallbacks(
3669 $trigger, array $sectionIds = null
3670 ) {
3671 /** @var Exception|Throwable $e */
3672 $e = null; // first exception
3673
3674 $notCancelled = [];
3675 do {
3676 $callbacks = $this->trxSectionCancelCallbacks;
3677 $this->trxSectionCancelCallbacks = []; // consumed (recursion guard)
3678 foreach ( $callbacks as $entry ) {
3679 if ( $sectionIds === null || in_array( $entry[2], $sectionIds, true ) ) {
3680 try {
3681 $entry[0]( $trigger, $this );
3682 } catch ( Exception $ex ) {
3683 ( $this->errorLogger )( $ex );
3684 $e = $e ?: $ex;
3685 } catch ( Throwable $ex ) {
3686 // @todo: Log?
3687 $e = $e ?: $ex;
3688 }
3689 } else {
3690 $notCancelled[] = $entry;
3691 }
3692 }
3693 } while ( count( $this->trxSectionCancelCallbacks ) );
3694 $this->trxSectionCancelCallbacks = $notCancelled;
3695
3696 if ( $e !== null ) {
3697 throw $e; // re-throw any first Exception/Throwable
3698 }
3699 }
3700
3701 /**
3702 * Actually run any "transaction listener" callbacks.
3703 *
3704 * This method should not be used outside of Database/LoadBalancer
3705 *
3706 * @param int $trigger IDatabase::TRIGGER_* constant
3707 * @throws Exception
3708 * @since 1.20
3709 */
3710 public function runTransactionListenerCallbacks( $trigger ) {
3711 if ( $this->trxEndCallbacksSuppressed ) {
3712 return;
3713 }
3714
3715 /** @var Exception $e */
3716 $e = null; // first exception
3717
3718 foreach ( $this->trxRecurringCallbacks as $phpCallback ) {
3719 try {
3720 $phpCallback( $trigger, $this );
3721 } catch ( Exception $ex ) {
3722 ( $this->errorLogger )( $ex );
3723 $e = $e ?: $ex;
3724 }
3725 }
3726
3727 if ( $e instanceof Exception ) {
3728 throw $e; // re-throw any first exception
3729 }
3730 }
3731
3732 /**
3733 * Create a savepoint
3734 *
3735 * This is used internally to implement atomic sections. It should not be
3736 * used otherwise.
3737 *
3738 * @since 1.31
3739 * @param string $identifier Identifier for the savepoint
3740 * @param string $fname Calling function name
3741 */
3742 protected function doSavepoint( $identifier, $fname ) {
3743 $this->query( 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3744 }
3745
3746 /**
3747 * Release a savepoint
3748 *
3749 * This is used internally to implement atomic sections. It should not be
3750 * used otherwise.
3751 *
3752 * @since 1.31
3753 * @param string $identifier Identifier for the savepoint
3754 * @param string $fname Calling function name
3755 */
3756 protected function doReleaseSavepoint( $identifier, $fname ) {
3757 $this->query( 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3758 }
3759
3760 /**
3761 * Rollback to a savepoint
3762 *
3763 * This is used internally to implement atomic sections. It should not be
3764 * used otherwise.
3765 *
3766 * @since 1.31
3767 * @param string $identifier Identifier for the savepoint
3768 * @param string $fname Calling function name
3769 */
3770 protected function doRollbackToSavepoint( $identifier, $fname ) {
3771 $this->query( 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3772 }
3773
3774 /**
3775 * @param string $fname
3776 * @return string
3777 */
3778 private function nextSavepointId( $fname ) {
3779 $savepointId = self::$SAVEPOINT_PREFIX . ++$this->trxAtomicCounter;
3780 if ( strlen( $savepointId ) > 30 ) {
3781 // 30 == Oracle's identifier length limit (pre 12c)
3782 // With a 22 character prefix, that puts the highest number at 99999999.
3783 throw new DBUnexpectedError(
3784 $this,
3785 'There have been an excessively large number of atomic sections in a transaction'
3786 . " started by $this->trxFname (at $fname)"
3787 );
3788 }
3789
3790 return $savepointId;
3791 }
3792
3793 final public function startAtomic(
3794 $fname = __METHOD__, $cancelable = self::ATOMIC_NOT_CANCELABLE
3795 ) {
3796 $savepointId = $cancelable === self::ATOMIC_CANCELABLE ? self::$NOT_APPLICABLE : null;
3797
3798 if ( !$this->trxLevel() ) {
3799 $this->begin( $fname, self::TRANSACTION_INTERNAL ); // sets trxAutomatic
3800 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3801 // in all changes being in one transaction to keep requests transactional.
3802 if ( $this->getFlag( self::DBO_TRX ) ) {
3803 // Since writes could happen in between the topmost atomic sections as part
3804 // of the transaction, those sections will need savepoints.
3805 $savepointId = $this->nextSavepointId( $fname );
3806 $this->doSavepoint( $savepointId, $fname );
3807 } else {
3808 $this->trxAutomaticAtomic = true;
3809 }
3810 } elseif ( $cancelable === self::ATOMIC_CANCELABLE ) {
3811 $savepointId = $this->nextSavepointId( $fname );
3812 $this->doSavepoint( $savepointId, $fname );
3813 }
3814
3815 $sectionId = new AtomicSectionIdentifier;
3816 $this->trxAtomicLevels[] = [ $fname, $sectionId, $savepointId ];
3817 $this->queryLogger->debug( 'startAtomic: entering level ' .
3818 ( count( $this->trxAtomicLevels ) - 1 ) . " ($fname)" );
3819
3820 return $sectionId;
3821 }
3822
3823 final public function endAtomic( $fname = __METHOD__ ) {
3824 if ( !$this->trxLevel() || !$this->trxAtomicLevels ) {
3825 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3826 }
3827
3828 // Check if the current section matches $fname
3829 $pos = count( $this->trxAtomicLevels ) - 1;
3830 list( $savedFname, $sectionId, $savepointId ) = $this->trxAtomicLevels[$pos];
3831 $this->queryLogger->debug( "endAtomic: leaving level $pos ($fname)" );
3832
3833 if ( $savedFname !== $fname ) {
3834 throw new DBUnexpectedError(
3835 $this,
3836 "Invalid atomic section ended (got $fname but expected $savedFname)"
3837 );
3838 }
3839
3840 // Remove the last section (no need to re-index the array)
3841 array_pop( $this->trxAtomicLevels );
3842
3843 if ( !$this->trxAtomicLevels && $this->trxAutomaticAtomic ) {
3844 $this->commit( $fname, self::FLUSHING_INTERNAL );
3845 } elseif ( $savepointId !== null && $savepointId !== self::$NOT_APPLICABLE ) {
3846 $this->doReleaseSavepoint( $savepointId, $fname );
3847 }
3848
3849 // Hoist callback ownership for callbacks in the section that just ended;
3850 // all callbacks should have an owner that is present in trxAtomicLevels.
3851 $currentSectionId = $this->currentAtomicSectionId();
3852 if ( $currentSectionId ) {
3853 $this->reassignCallbacksForSection( $sectionId, $currentSectionId );
3854 }
3855 }
3856
3857 final public function cancelAtomic(
3858 $fname = __METHOD__, AtomicSectionIdentifier $sectionId = null
3859 ) {
3860 if ( !$this->trxLevel() || !$this->trxAtomicLevels ) {
3861 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3862 }
3863
3864 $excisedIds = [];
3865 $newTopSection = $this->currentAtomicSectionId();
3866 try {
3867 $excisedFnames = [];
3868 if ( $sectionId !== null ) {
3869 // Find the (last) section with the given $sectionId
3870 $pos = -1;
3871 foreach ( $this->trxAtomicLevels as $i => list( $asFname, $asId, $spId ) ) {
3872 if ( $asId === $sectionId ) {
3873 $pos = $i;
3874 }
3875 }
3876 if ( $pos < 0 ) {
3877 throw new DBUnexpectedError( $this, "Atomic section not found (for $fname)" );
3878 }
3879 // Remove all descendant sections and re-index the array
3880 $len = count( $this->trxAtomicLevels );
3881 for ( $i = $pos + 1; $i < $len; ++$i ) {
3882 $excisedFnames[] = $this->trxAtomicLevels[$i][0];
3883 $excisedIds[] = $this->trxAtomicLevels[$i][1];
3884 }
3885 $this->trxAtomicLevels = array_slice( $this->trxAtomicLevels, 0, $pos + 1 );
3886 $newTopSection = $this->currentAtomicSectionId();
3887 }
3888
3889 // Check if the current section matches $fname
3890 $pos = count( $this->trxAtomicLevels ) - 1;
3891 list( $savedFname, $savedSectionId, $savepointId ) = $this->trxAtomicLevels[$pos];
3892
3893 if ( $excisedFnames ) {
3894 $this->queryLogger->debug( "cancelAtomic: canceling level $pos ($savedFname) " .
3895 "and descendants " . implode( ', ', $excisedFnames ) );
3896 } else {
3897 $this->queryLogger->debug( "cancelAtomic: canceling level $pos ($savedFname)" );
3898 }
3899
3900 if ( $savedFname !== $fname ) {
3901 throw new DBUnexpectedError(
3902 $this,
3903 "Invalid atomic section ended (got $fname but expected $savedFname)"
3904 );
3905 }
3906
3907 // Remove the last section (no need to re-index the array)
3908 array_pop( $this->trxAtomicLevels );
3909 $excisedIds[] = $savedSectionId;
3910 $newTopSection = $this->currentAtomicSectionId();
3911
3912 if ( $savepointId !== null ) {
3913 // Rollback the transaction to the state just before this atomic section
3914 if ( $savepointId === self::$NOT_APPLICABLE ) {
3915 $this->rollback( $fname, self::FLUSHING_INTERNAL );
3916 // Note: rollback() will run trxSectionCancelCallbacks
3917 } else {
3918 $this->doRollbackToSavepoint( $savepointId, $fname );
3919 $this->trxStatus = self::STATUS_TRX_OK; // no exception; recovered
3920 $this->trxStatusIgnoredCause = null;
3921
3922 // Run trxSectionCancelCallbacks now.
3923 $this->runOnAtomicSectionCancelCallbacks( self::TRIGGER_CANCEL, $excisedIds );
3924 }
3925 } elseif ( $this->trxStatus > self::STATUS_TRX_ERROR ) {
3926 // Put the transaction into an error state if it's not already in one
3927 $this->trxStatus = self::STATUS_TRX_ERROR;
3928 $this->trxStatusCause = new DBUnexpectedError(
3929 $this,
3930 "Uncancelable atomic section canceled (got $fname)"
3931 );
3932 }
3933 } finally {
3934 // Fix up callbacks owned by the sections that were just cancelled.
3935 // All callbacks should have an owner that is present in trxAtomicLevels.
3936 $this->modifyCallbacksForCancel( $excisedIds, $newTopSection );
3937 }
3938
3939 $this->affectedRowCount = 0; // for the sake of consistency
3940 }
3941
3942 final public function doAtomicSection(
3943 $fname, callable $callback, $cancelable = self::ATOMIC_NOT_CANCELABLE
3944 ) {
3945 $sectionId = $this->startAtomic( $fname, $cancelable );
3946 try {
3947 $res = $callback( $this, $fname );
3948 } catch ( Exception $e ) {
3949 $this->cancelAtomic( $fname, $sectionId );
3950
3951 throw $e;
3952 }
3953 $this->endAtomic( $fname );
3954
3955 return $res;
3956 }
3957
3958 final public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
3959 static $modes = [ self::TRANSACTION_EXPLICIT, self::TRANSACTION_INTERNAL ];
3960 if ( !in_array( $mode, $modes, true ) ) {
3961 throw new DBUnexpectedError( $this, "$fname: invalid mode parameter '$mode'" );
3962 }
3963
3964 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3965 if ( $this->trxLevel() ) {
3966 if ( $this->trxAtomicLevels ) {
3967 $levels = $this->flatAtomicSectionList();
3968 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open";
3969 throw new DBUnexpectedError( $this, $msg );
3970 } elseif ( !$this->trxAutomatic ) {
3971 $msg = "$fname: Explicit transaction already active (from {$this->trxFname})";
3972 throw new DBUnexpectedError( $this, $msg );
3973 } else {
3974 $msg = "$fname: Implicit transaction already active (from {$this->trxFname})";
3975 throw new DBUnexpectedError( $this, $msg );
3976 }
3977 } elseif ( $this->getFlag( self::DBO_TRX ) && $mode !== self::TRANSACTION_INTERNAL ) {
3978 $msg = "$fname: Implicit transaction expected (DBO_TRX set)";
3979 throw new DBUnexpectedError( $this, $msg );
3980 }
3981
3982 $this->assertHasConnectionHandle();
3983
3984 $this->doBegin( $fname );
3985 $this->trxShortId = sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3986 $this->trxStatus = self::STATUS_TRX_OK;
3987 $this->trxStatusIgnoredCause = null;
3988 $this->trxAtomicCounter = 0;
3989 $this->trxTimestamp = microtime( true );
3990 $this->trxFname = $fname;
3991 $this->trxDoneWrites = false;
3992 $this->trxAutomaticAtomic = false;
3993 $this->trxAtomicLevels = [];
3994 $this->trxWriteDuration = 0.0;
3995 $this->trxWriteQueryCount = 0;
3996 $this->trxWriteAffectedRows = 0;
3997 $this->trxWriteAdjDuration = 0.0;
3998 $this->trxWriteAdjQueryCount = 0;
3999 $this->trxWriteCallers = [];
4000 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
4001 // Get an estimate of the replication lag before any such queries.
4002 $this->trxReplicaLag = null; // clear cached value first
4003 $this->trxReplicaLag = $this->getApproximateLagStatus()['lag'];
4004 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
4005 // caller will think its OK to muck around with the transaction just because startAtomic()
4006 // has not yet completed (e.g. setting trxAtomicLevels).
4007 $this->trxAutomatic = ( $mode === self::TRANSACTION_INTERNAL );
4008 }
4009
4010 /**
4011 * Issues the BEGIN command to the database server.
4012 *
4013 * @see Database::begin()
4014 * @param string $fname
4015 * @throws DBError
4016 */
4017 protected function doBegin( $fname ) {
4018 $this->query( 'BEGIN', $fname );
4019 }
4020
4021 final public function commit( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
4022 static $modes = [ self::FLUSHING_ONE, self::FLUSHING_ALL_PEERS, self::FLUSHING_INTERNAL ];
4023 if ( !in_array( $flush, $modes, true ) ) {
4024 throw new DBUnexpectedError( $this, "$fname: invalid flush parameter '$flush'" );
4025 }
4026
4027 if ( $this->trxLevel() && $this->trxAtomicLevels ) {
4028 // There are still atomic sections open; this cannot be ignored
4029 $levels = $this->flatAtomicSectionList();
4030 throw new DBUnexpectedError(
4031 $this,
4032 "$fname: Got COMMIT while atomic sections $levels are still open"
4033 );
4034 }
4035
4036 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
4037 if ( !$this->trxLevel() ) {
4038 return; // nothing to do
4039 } elseif ( !$this->trxAutomatic ) {
4040 throw new DBUnexpectedError(
4041 $this,
4042 "$fname: Flushing an explicit transaction, getting out of sync"
4043 );
4044 }
4045 } elseif ( !$this->trxLevel() ) {
4046 $this->queryLogger->error(
4047 "$fname: No transaction to commit, something got out of sync" );
4048 return; // nothing to do
4049 } elseif ( $this->trxAutomatic ) {
4050 throw new DBUnexpectedError(
4051 $this,
4052 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)"
4053 );
4054 }
4055
4056 $this->assertHasConnectionHandle();
4057
4058 $this->runOnTransactionPreCommitCallbacks();
4059
4060 $writeTime = $this->pendingWriteQueryDuration( self::ESTIMATE_DB_APPLY );
4061 $this->doCommit( $fname );
4062 $oldTrxShortId = $this->consumeTrxShortId();
4063 $this->trxStatus = self::STATUS_TRX_NONE;
4064
4065 if ( $this->trxDoneWrites ) {
4066 $this->lastWriteTime = microtime( true );
4067 $this->trxProfiler->transactionWritingOut(
4068 $this->server,
4069 $this->getDomainID(),
4070 $oldTrxShortId,
4071 $writeTime,
4072 $this->trxWriteAffectedRows
4073 );
4074 }
4075
4076 // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4077 if ( $flush !== self::FLUSHING_ALL_PEERS ) {
4078 $this->runOnTransactionIdleCallbacks( self::TRIGGER_COMMIT );
4079 $this->runTransactionListenerCallbacks( self::TRIGGER_COMMIT );
4080 }
4081 }
4082
4083 /**
4084 * Issues the COMMIT command to the database server.
4085 *
4086 * @see Database::commit()
4087 * @param string $fname
4088 * @throws DBError
4089 */
4090 protected function doCommit( $fname ) {
4091 if ( $this->trxLevel() ) {
4092 $this->query( 'COMMIT', $fname );
4093 }
4094 }
4095
4096 final public function rollback( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
4097 $trxActive = $this->trxLevel();
4098
4099 if ( $flush !== self::FLUSHING_INTERNAL
4100 && $flush !== self::FLUSHING_ALL_PEERS
4101 && $this->getFlag( self::DBO_TRX )
4102 ) {
4103 throw new DBUnexpectedError(
4104 $this,
4105 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)"
4106 );
4107 }
4108
4109 if ( $trxActive ) {
4110 $this->assertHasConnectionHandle();
4111
4112 $this->doRollback( $fname );
4113 $oldTrxShortId = $this->consumeTrxShortId();
4114 $this->trxStatus = self::STATUS_TRX_NONE;
4115 $this->trxAtomicLevels = [];
4116 // Estimate the RTT via a query now that trxStatus is OK
4117 $writeTime = $this->pingAndCalculateLastTrxApplyTime();
4118
4119 if ( $this->trxDoneWrites ) {
4120 $this->trxProfiler->transactionWritingOut(
4121 $this->server,
4122 $this->getDomainID(),
4123 $oldTrxShortId,
4124 $writeTime,
4125 $this->trxWriteAffectedRows
4126 );
4127 }
4128 }
4129
4130 // Clear any commit-dependant callbacks. They might even be present
4131 // only due to transaction rounds, with no SQL transaction being active
4132 $this->trxIdleCallbacks = [];
4133 $this->trxPreCommitCallbacks = [];
4134
4135 // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4136 if ( $trxActive && $flush !== self::FLUSHING_ALL_PEERS ) {
4137 try {
4138 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
4139 } catch ( Exception $e ) {
4140 // already logged; finish and let LoadBalancer move on during mass-rollback
4141 }
4142 try {
4143 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
4144 } catch ( Exception $e ) {
4145 // already logged; let LoadBalancer move on during mass-rollback
4146 }
4147
4148 $this->affectedRowCount = 0; // for the sake of consistency
4149 }
4150 }
4151
4152 /**
4153 * Issues the ROLLBACK command to the database server.
4154 *
4155 * @see Database::rollback()
4156 * @param string $fname
4157 * @throws DBError
4158 */
4159 protected function doRollback( $fname ) {
4160 if ( $this->trxLevel() ) {
4161 # Disconnects cause rollback anyway, so ignore those errors
4162 $ignoreErrors = true;
4163 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
4164 }
4165 }
4166
4167 public function flushSnapshot( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
4168 if ( $this->explicitTrxActive() ) {
4169 // Committing this transaction would break callers that assume it is still open
4170 throw new DBUnexpectedError(
4171 $this,
4172 "$fname: Cannot flush snapshot; " .
4173 "explicit transaction '{$this->trxFname}' is still open"
4174 );
4175 } elseif ( $this->writesOrCallbacksPending() ) {
4176 // This only flushes transactions to clear snapshots, not to write data
4177 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4178 throw new DBUnexpectedError(
4179 $this,
4180 "$fname: Cannot flush snapshot; " .
4181 "writes from transaction {$this->trxFname} are still pending ($fnames)"
4182 );
4183 } elseif (
4184 $this->trxLevel() &&
4185 $this->getTransactionRoundId() &&
4186 $flush !== self::FLUSHING_INTERNAL &&
4187 $flush !== self::FLUSHING_ALL_PEERS
4188 ) {
4189 $this->queryLogger->warning(
4190 "$fname: Expected mass snapshot flush of all peer transactions " .
4191 "in the explicit transactions round '{$this->getTransactionRoundId()}'",
4192 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
4193 );
4194 }
4195
4196 $this->commit( $fname, self::FLUSHING_INTERNAL );
4197 }
4198
4199 public function explicitTrxActive() {
4200 return $this->trxLevel() && ( $this->trxAtomicLevels || !$this->trxAutomatic );
4201 }
4202
4203 public function duplicateTableStructure(
4204 $oldName, $newName, $temporary = false, $fname = __METHOD__
4205 ) {
4206 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
4207 }
4208
4209 public function listTables( $prefix = null, $fname = __METHOD__ ) {
4210 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
4211 }
4212
4213 public function listViews( $prefix = null, $fname = __METHOD__ ) {
4214 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
4215 }
4216
4217 public function timestamp( $ts = 0 ) {
4218 $t = new ConvertibleTimestamp( $ts );
4219 // Let errors bubble up to avoid putting garbage in the DB
4220 return $t->getTimestamp( TS_MW );
4221 }
4222
4223 public function timestampOrNull( $ts = null ) {
4224 if ( is_null( $ts ) ) {
4225 return null;
4226 } else {
4227 return $this->timestamp( $ts );
4228 }
4229 }
4230
4231 public function affectedRows() {
4232 return ( $this->affectedRowCount === null )
4233 ? $this->fetchAffectedRowCount() // default to driver value
4234 : $this->affectedRowCount;
4235 }
4236
4237 /**
4238 * @return int Number of retrieved rows according to the driver
4239 */
4240 abstract protected function fetchAffectedRowCount();
4241
4242 /**
4243 * Take a query result and wrap it in an iterable result wrapper if necessary.
4244 * Booleans are passed through as-is to indicate success/failure of write queries.
4245 *
4246 * Once upon a time, Database::query() returned a bare MySQL result
4247 * resource, and it was necessary to call this function to convert it to
4248 * a wrapper. Nowadays, raw database objects are never exposed to external
4249 * callers, so this is unnecessary in external code.
4250 *
4251 * @param bool|IResultWrapper|resource $result
4252 * @return bool|IResultWrapper
4253 */
4254 protected function resultObject( $result ) {
4255 if ( !$result ) {
4256 return false; // failed query
4257 } elseif ( $result instanceof IResultWrapper ) {
4258 return $result;
4259 } elseif ( $result === true ) {
4260 return $result; // succesful write query
4261 } else {
4262 return new ResultWrapper( $this, $result );
4263 }
4264 }
4265
4266 public function ping( &$rtt = null ) {
4267 // Avoid hitting the server if it was hit recently
4268 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing ) < self::$PING_TTL ) {
4269 if ( !func_num_args() || $this->lastRoundTripEstimate > 0 ) {
4270 $rtt = $this->lastRoundTripEstimate;
4271 return true; // don't care about $rtt
4272 }
4273 }
4274
4275 // This will reconnect if possible or return false if not
4276 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_SILENCE_ERRORS;
4277 $ok = ( $this->query( self::$PING_QUERY, __METHOD__, $flags ) !== false );
4278 if ( $ok ) {
4279 $rtt = $this->lastRoundTripEstimate;
4280 }
4281
4282 return $ok;
4283 }
4284
4285 /**
4286 * Close any existing (dead) database connection and open a new connection
4287 *
4288 * @param string $fname
4289 * @return bool True if new connection is opened successfully, false if error
4290 */
4291 protected function replaceLostConnection( $fname ) {
4292 $this->closeConnection();
4293 $this->conn = null;
4294
4295 $this->handleSessionLossPreconnect();
4296
4297 try {
4298 $this->open(
4299 $this->server,
4300 $this->user,
4301 $this->password,
4302 $this->currentDomain->getDatabase(),
4303 $this->currentDomain->getSchema(),
4304 $this->tablePrefix()
4305 );
4306 $this->lastPing = microtime( true );
4307 $ok = true;
4308
4309 $this->connLogger->warning(
4310 $fname . ': lost connection to {dbserver}; reconnected',
4311 [
4312 'dbserver' => $this->getServer(),
4313 'trace' => ( new RuntimeException() )->getTraceAsString()
4314 ]
4315 );
4316 } catch ( DBConnectionError $e ) {
4317 $ok = false;
4318
4319 $this->connLogger->error(
4320 $fname . ': lost connection to {dbserver} permanently',
4321 [ 'dbserver' => $this->getServer() ]
4322 );
4323 }
4324
4325 $this->handleSessionLossPostconnect();
4326
4327 return $ok;
4328 }
4329
4330 public function getSessionLagStatus() {
4331 return $this->getRecordedTransactionLagStatus() ?: $this->getApproximateLagStatus();
4332 }
4333
4334 /**
4335 * Get the replica DB lag when the current transaction started
4336 *
4337 * This is useful when transactions might use snapshot isolation
4338 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
4339 * is this lag plus transaction duration. If they don't, it is still
4340 * safe to be pessimistic. This returns null if there is no transaction.
4341 *
4342 * This returns null if the lag status for this transaction was not yet recorded.
4343 *
4344 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
4345 * @since 1.27
4346 */
4347 final protected function getRecordedTransactionLagStatus() {
4348 return ( $this->trxLevel() && $this->trxReplicaLag !== null )
4349 ? [ 'lag' => $this->trxReplicaLag, 'since' => $this->trxTimestamp() ]
4350 : null;
4351 }
4352
4353 /**
4354 * Get a replica DB lag estimate for this server
4355 *
4356 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
4357 * @since 1.27
4358 */
4359 protected function getApproximateLagStatus() {
4360 return [
4361 'lag' => $this->getLBInfo( 'replica' ) ? $this->getLag() : 0,
4362 'since' => microtime( true )
4363 ];
4364 }
4365
4366 /**
4367 * Merge the result of getSessionLagStatus() for several DBs
4368 * using the most pessimistic values to estimate the lag of
4369 * any data derived from them in combination
4370 *
4371 * This is information is useful for caching modules
4372 *
4373 * @see WANObjectCache::set()
4374 * @see WANObjectCache::getWithSetCallback()
4375 *
4376 * @param IDatabase $db1
4377 * @param IDatabase|null $db2 [optional]
4378 * @return array Map of values:
4379 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
4380 * - since: oldest UNIX timestamp of any of the DB lag estimates
4381 * - pending: whether any of the DBs have uncommitted changes
4382 * @throws DBError
4383 * @since 1.27
4384 */
4385 public static function getCacheSetOptions( IDatabase $db1, IDatabase $db2 = null ) {
4386 $res = [ 'lag' => 0, 'since' => INF, 'pending' => false ];
4387 foreach ( func_get_args() as $db ) {
4388 /** @var IDatabase $db */
4389 $status = $db->getSessionLagStatus();
4390 if ( $status['lag'] === false ) {
4391 $res['lag'] = false;
4392 } elseif ( $res['lag'] !== false ) {
4393 $res['lag'] = max( $res['lag'], $status['lag'] );
4394 }
4395 $res['since'] = min( $res['since'], $status['since'] );
4396 $res['pending'] = $res['pending'] ?: $db->writesPending();
4397 }
4398
4399 return $res;
4400 }
4401
4402 public function getLag() {
4403 if ( $this->getLBInfo( 'master' ) ) {
4404 return 0; // this is the master
4405 } elseif ( $this->getLBInfo( 'is static' ) ) {
4406 return 0; // static dataset
4407 }
4408
4409 return $this->doGetLag();
4410 }
4411
4412 protected function doGetLag() {
4413 return 0;
4414 }
4415
4416 public function maxListLen() {
4417 return 0;
4418 }
4419
4420 public function encodeBlob( $b ) {
4421 return $b;
4422 }
4423
4424 public function decodeBlob( $b ) {
4425 if ( $b instanceof Blob ) {
4426 $b = $b->fetch();
4427 }
4428 return $b;
4429 }
4430
4431 public function setSessionOptions( array $options ) {
4432 }
4433
4434 public function sourceFile(
4435 $filename,
4436 callable $lineCallback = null,
4437 callable $resultCallback = null,
4438 $fname = false,
4439 callable $inputCallback = null
4440 ) {
4441 AtEase::suppressWarnings();
4442 $fp = fopen( $filename, 'r' );
4443 AtEase::restoreWarnings();
4444
4445 if ( $fp === false ) {
4446 throw new RuntimeException( "Could not open \"{$filename}\"" );
4447 }
4448
4449 if ( !$fname ) {
4450 $fname = __METHOD__ . "( $filename )";
4451 }
4452
4453 try {
4454 $error = $this->sourceStream(
4455 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
4456 } catch ( Exception $e ) {
4457 fclose( $fp );
4458 throw $e;
4459 }
4460
4461 fclose( $fp );
4462
4463 return $error;
4464 }
4465
4466 public function setSchemaVars( $vars ) {
4467 $this->schemaVars = is_array( $vars ) ? $vars : null;
4468 }
4469
4470 public function sourceStream(
4471 $fp,
4472 callable $lineCallback = null,
4473 callable $resultCallback = null,
4474 $fname = __METHOD__,
4475 callable $inputCallback = null
4476 ) {
4477 $delimiterReset = new ScopedCallback(
4478 function ( $delimiter ) {
4479 $this->delimiter = $delimiter;
4480 },
4481 [ $this->delimiter ]
4482 );
4483 $cmd = '';
4484
4485 while ( !feof( $fp ) ) {
4486 if ( $lineCallback ) {
4487 call_user_func( $lineCallback );
4488 }
4489
4490 $line = trim( fgets( $fp ) );
4491
4492 if ( $line == '' ) {
4493 continue;
4494 }
4495
4496 if ( $line[0] == '-' && $line[1] == '-' ) {
4497 continue;
4498 }
4499
4500 if ( $cmd != '' ) {
4501 $cmd .= ' ';
4502 }
4503
4504 $done = $this->streamStatementEnd( $cmd, $line );
4505
4506 $cmd .= "$line\n";
4507
4508 if ( $done || feof( $fp ) ) {
4509 $cmd = $this->replaceVars( $cmd );
4510
4511 if ( $inputCallback ) {
4512 $callbackResult = $inputCallback( $cmd );
4513
4514 if ( is_string( $callbackResult ) || !$callbackResult ) {
4515 $cmd = $callbackResult;
4516 }
4517 }
4518
4519 if ( $cmd ) {
4520 $res = $this->query( $cmd, $fname );
4521
4522 if ( $resultCallback ) {
4523 $resultCallback( $res, $this );
4524 }
4525
4526 if ( $res === false ) {
4527 $err = $this->lastError();
4528
4529 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4530 }
4531 }
4532 $cmd = '';
4533 }
4534 }
4535
4536 ScopedCallback::consume( $delimiterReset );
4537 return true;
4538 }
4539
4540 /**
4541 * Called by sourceStream() to check if we've reached a statement end
4542 *
4543 * @param string &$sql SQL assembled so far
4544 * @param string &$newLine New line about to be added to $sql
4545 * @return bool Whether $newLine contains end of the statement
4546 */
4547 public function streamStatementEnd( &$sql, &$newLine ) {
4548 if ( $this->delimiter ) {
4549 $prev = $newLine;
4550 $newLine = preg_replace(
4551 '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
4552 if ( $newLine != $prev ) {
4553 return true;
4554 }
4555 }
4556
4557 return false;
4558 }
4559
4560 /**
4561 * Database independent variable replacement. Replaces a set of variables
4562 * in an SQL statement with their contents as given by $this->getSchemaVars().
4563 *
4564 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4565 *
4566 * - '{$var}' should be used for text and is passed through the database's
4567 * addQuotes method.
4568 * - `{$var}` should be used for identifiers (e.g. table and database names).
4569 * It is passed through the database's addIdentifierQuotes method which
4570 * can be overridden if the database uses something other than backticks.
4571 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4572 * database's tableName method.
4573 * - / *i* / passes the name that follows through the database's indexName method.
4574 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4575 * its use should be avoided. In 1.24 and older, string encoding was applied.
4576 *
4577 * @param string $ins SQL statement to replace variables in
4578 * @return string The new SQL statement with variables replaced
4579 */
4580 protected function replaceVars( $ins ) {
4581 $vars = $this->getSchemaVars();
4582 return preg_replace_callback(
4583 '!
4584 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4585 \'\{\$ (\w+) }\' | # 3. addQuotes
4586 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4587 /\*\$ (\w+) \*/ # 5. leave unencoded
4588 !x',
4589 function ( $m ) use ( $vars ) {
4590 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4591 // check for both nonexistent keys *and* the empty string.
4592 if ( isset( $m[1] ) && $m[1] !== '' ) {
4593 if ( $m[1] === 'i' ) {
4594 return $this->indexName( $m[2] );
4595 } else {
4596 return $this->tableName( $m[2] );
4597 }
4598 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4599 return $this->addQuotes( $vars[$m[3]] );
4600 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4601 return $this->addIdentifierQuotes( $vars[$m[4]] );
4602 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4603 return $vars[$m[5]];
4604 } else {
4605 return $m[0];
4606 }
4607 },
4608 $ins
4609 );
4610 }
4611
4612 /**
4613 * Get schema variables. If none have been set via setSchemaVars(), then
4614 * use some defaults from the current object.
4615 *
4616 * @return array
4617 */
4618 protected function getSchemaVars() {
4619 return $this->schemaVars ?? $this->getDefaultSchemaVars();
4620 }
4621
4622 /**
4623 * Get schema variables to use if none have been set via setSchemaVars().
4624 *
4625 * Override this in derived classes to provide variables for tables.sql
4626 * and SQL patch files.
4627 *
4628 * @return array
4629 */
4630 protected function getDefaultSchemaVars() {
4631 return [];
4632 }
4633
4634 public function lockIsFree( $lockName, $method ) {
4635 // RDBMs methods for checking named locks may or may not count this thread itself.
4636 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
4637 // the behavior choosen by the interface for this method.
4638 return !isset( $this->sessionNamedLocks[$lockName] );
4639 }
4640
4641 public function lock( $lockName, $method, $timeout = 5 ) {
4642 $this->sessionNamedLocks[$lockName] = 1;
4643
4644 return true;
4645 }
4646
4647 public function unlock( $lockName, $method ) {
4648 unset( $this->sessionNamedLocks[$lockName] );
4649
4650 return true;
4651 }
4652
4653 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
4654 if ( $this->writesOrCallbacksPending() ) {
4655 // This only flushes transactions to clear snapshots, not to write data
4656 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4657 throw new DBUnexpectedError(
4658 $this,
4659 "$fname: Cannot flush pre-lock snapshot; " .
4660 "writes from transaction {$this->trxFname} are still pending ($fnames)"
4661 );
4662 }
4663
4664 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
4665 return null;
4666 }
4667
4668 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
4669 if ( $this->trxLevel() ) {
4670 // There is a good chance an exception was thrown, causing any early return
4671 // from the caller. Let any error handler get a chance to issue rollback().
4672 // If there isn't one, let the error bubble up and trigger server-side rollback.
4673 $this->onTransactionResolution(
4674 function () use ( $lockKey, $fname ) {
4675 $this->unlock( $lockKey, $fname );
4676 },
4677 $fname
4678 );
4679 } else {
4680 $this->unlock( $lockKey, $fname );
4681 }
4682 } );
4683
4684 $this->commit( $fname, self::FLUSHING_INTERNAL );
4685
4686 return $unlocker;
4687 }
4688
4689 public function namedLocksEnqueue() {
4690 return false;
4691 }
4692
4693 public function tableLocksHaveTransactionScope() {
4694 return true;
4695 }
4696
4697 final public function lockTables( array $read, array $write, $method ) {
4698 if ( $this->writesOrCallbacksPending() ) {
4699 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending" );
4700 }
4701
4702 if ( $this->tableLocksHaveTransactionScope() ) {
4703 $this->startAtomic( $method );
4704 }
4705
4706 return $this->doLockTables( $read, $write, $method );
4707 }
4708
4709 /**
4710 * Helper function for lockTables() that handles the actual table locking
4711 *
4712 * @param array $read Array of tables to lock for read access
4713 * @param array $write Array of tables to lock for write access
4714 * @param string $method Name of caller
4715 * @return true
4716 */
4717 protected function doLockTables( array $read, array $write, $method ) {
4718 return true;
4719 }
4720
4721 final public function unlockTables( $method ) {
4722 if ( $this->tableLocksHaveTransactionScope() ) {
4723 $this->endAtomic( $method );
4724
4725 return true; // locks released on COMMIT/ROLLBACK
4726 }
4727
4728 return $this->doUnlockTables( $method );
4729 }
4730
4731 /**
4732 * Helper function for unlockTables() that handles the actual table unlocking
4733 *
4734 * @param string $method Name of caller
4735 * @return true
4736 */
4737 protected function doUnlockTables( $method ) {
4738 return true;
4739 }
4740
4741 /**
4742 * Delete a table
4743 * @param string $tableName
4744 * @param string $fName
4745 * @return bool|IResultWrapper
4746 * @since 1.18
4747 */
4748 public function dropTable( $tableName, $fName = __METHOD__ ) {
4749 if ( !$this->tableExists( $tableName, $fName ) ) {
4750 return false;
4751 }
4752 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
4753
4754 return $this->query( $sql, $fName );
4755 }
4756
4757 public function getInfinity() {
4758 return 'infinity';
4759 }
4760
4761 public function encodeExpiry( $expiry ) {
4762 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4763 ? $this->getInfinity()
4764 : $this->timestamp( $expiry );
4765 }
4766
4767 public function decodeExpiry( $expiry, $format = TS_MW ) {
4768 if ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() ) {
4769 return 'infinity';
4770 }
4771
4772 return ConvertibleTimestamp::convert( $format, $expiry );
4773 }
4774
4775 public function setBigSelects( $value = true ) {
4776 // no-op
4777 }
4778
4779 public function isReadOnly() {
4780 return ( $this->getReadOnlyReason() !== false );
4781 }
4782
4783 /**
4784 * @return string|bool Reason this DB is read-only or false if it is not
4785 */
4786 protected function getReadOnlyReason() {
4787 $reason = $this->getLBInfo( 'readOnlyReason' );
4788 if ( is_string( $reason ) ) {
4789 return $reason;
4790 } elseif ( $this->getLBInfo( 'replica' ) ) {
4791 return "Server is configured in the role of a read-only replica database.";
4792 }
4793
4794 return false;
4795 }
4796
4797 public function setTableAliases( array $aliases ) {
4798 $this->tableAliases = $aliases;
4799 }
4800
4801 public function setIndexAliases( array $aliases ) {
4802 $this->indexAliases = $aliases;
4803 }
4804
4805 /**
4806 * @param int $field
4807 * @param int $flags
4808 * @return bool
4809 * @since 1.34
4810 */
4811 final protected function fieldHasBit( $field, $flags ) {
4812 return ( ( $field & $flags ) === $flags );
4813 }
4814
4815 /**
4816 * Get the underlying binding connection handle
4817 *
4818 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
4819 * This catches broken callers than catch and ignore disconnection exceptions.
4820 * Unlike checking isOpen(), this is safe to call inside of open().
4821 *
4822 * @return mixed
4823 * @throws DBUnexpectedError
4824 * @since 1.26
4825 */
4826 protected function getBindingHandle() {
4827 if ( !$this->conn ) {
4828 throw new DBUnexpectedError(
4829 $this,
4830 'DB connection was already closed or the connection dropped'
4831 );
4832 }
4833
4834 return $this->conn;
4835 }
4836
4837 public function __toString() {
4838 // spl_object_id is PHP >= 7.2
4839 $id = function_exists( 'spl_object_id' )
4840 ? spl_object_id( $this )
4841 : spl_object_hash( $this );
4842
4843 $description = $this->getType() . ' object #' . $id;
4844 if ( is_resource( $this->conn ) ) {
4845 $description .= ' (' . (string)$this->conn . ')'; // "resource id #<ID>"
4846 } elseif ( is_object( $this->conn ) ) {
4847 // spl_object_id is PHP >= 7.2
4848 $handleId = function_exists( 'spl_object_id' )
4849 ? spl_object_id( $this->conn )
4850 : spl_object_hash( $this->conn );
4851 $description .= " (handle id #$handleId)";
4852 }
4853
4854 return $description;
4855 }
4856
4857 /**
4858 * Make sure that copies do not share the same client binding handle
4859 * @throws DBConnectionError
4860 */
4861 public function __clone() {
4862 $this->connLogger->warning(
4863 "Cloning " . static::class . " is not recommended; forking connection",
4864 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
4865 );
4866
4867 if ( $this->isOpen() ) {
4868 // Open a new connection resource without messing with the old one
4869 $this->conn = null;
4870 $this->trxEndCallbacks = []; // don't copy
4871 $this->trxSectionCancelCallbacks = []; // don't copy
4872 $this->handleSessionLossPreconnect(); // no trx or locks anymore
4873 $this->open(
4874 $this->server,
4875 $this->user,
4876 $this->password,
4877 $this->currentDomain->getDatabase(),
4878 $this->currentDomain->getSchema(),
4879 $this->tablePrefix()
4880 );
4881 $this->lastPing = microtime( true );
4882 }
4883 }
4884
4885 /**
4886 * Called by serialize. Throw an exception when DB connection is serialized.
4887 * This causes problems on some database engines because the connection is
4888 * not restored on unserialize.
4889 */
4890 public function __sleep() {
4891 throw new RuntimeException( 'Database serialization may cause problems, since ' .
4892 'the connection is not restored on wakeup' );
4893 }
4894
4895 /**
4896 * Run a few simple sanity checks and close dangling connections
4897 */
4898 public function __destruct() {
4899 if ( $this->trxLevel() && $this->trxDoneWrites ) {
4900 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})" );
4901 }
4902
4903 $danglingWriters = $this->pendingWriteAndCallbackCallers();
4904 if ( $danglingWriters ) {
4905 $fnames = implode( ', ', $danglingWriters );
4906 trigger_error( "DB transaction writes or callbacks still pending ($fnames)" );
4907 }
4908
4909 if ( $this->conn ) {
4910 // Avoid connection leaks for sanity. Normally, resources close at script completion.
4911 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4912 AtEase::suppressWarnings();
4913 $this->closeConnection();
4914 AtEase::restoreWarnings();
4915 $this->conn = null;
4916 }
4917 }
4918 }
4919
4920 /**
4921 * @deprecated since 1.28
4922 */
4923 class_alias( Database::class, 'DatabaseBase' );
4924
4925 /**
4926 * @deprecated since 1.29
4927 */
4928 class_alias( Database::class, 'Database' );