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