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