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