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