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