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