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