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