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