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