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