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