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