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