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