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