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