rdbms: make LoadBalancer::getConnection() ignore CONN_TRX_AUTO when unusable
[lhc/web/wiklou.git] / includes / libs / rdbms / database / Database.php
1 <?php
2 /**
3 * @defgroup Database Database
4 *
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup Database
25 */
26 namespace Wikimedia\Rdbms;
27
28 use Psr\Log\LoggerAwareInterface;
29 use Psr\Log\LoggerInterface;
30 use Psr\Log\NullLogger;
31 use Wikimedia\ScopedCallback;
32 use Wikimedia\Timestamp\ConvertibleTimestamp;
33 use Wikimedia;
34 use BagOStuff;
35 use HashBagOStuff;
36 use InvalidArgumentException;
37 use Exception;
38 use RuntimeException;
39
40 /**
41 * Relational database abstraction object
42 *
43 * @ingroup Database
44 * @since 1.28
45 */
46 abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAwareInterface {
47 /** Number of times to re-try an operation in case of deadlock */
48 const DEADLOCK_TRIES = 4;
49 /** Minimum time to wait before retry, in microseconds */
50 const DEADLOCK_DELAY_MIN = 500000;
51 /** Maximum time to wait before retry */
52 const DEADLOCK_DELAY_MAX = 1500000;
53
54 /** How long before it is worth doing a dummy query to test the connection */
55 const PING_TTL = 1.0;
56 const PING_QUERY = 'SELECT 1 AS ping';
57
58 const TINY_WRITE_SEC = 0.010;
59 const SLOW_WRITE_SEC = 0.500;
60 const SMALL_WRITE_ROWS = 100;
61
62 /** @var string Whether lock granularity is on the level of the entire database */
63 const ATTR_DB_LEVEL_LOCKING = 'db-level-locking';
64
65 /** @var string SQL query */
66 protected $lastQuery = '';
67 /** @var float|bool UNIX timestamp of last write query */
68 protected $lastWriteTime = false;
69 /** @var string|bool */
70 protected $phpError = false;
71 /** @var string */
72 protected $server;
73 /** @var string */
74 protected $user;
75 /** @var string */
76 protected $password;
77 /** @var string */
78 protected $dbName;
79 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
80 protected $tableAliases = [];
81 /** @var bool Whether this PHP instance is for a CLI script */
82 protected $cliMode;
83 /** @var string Agent name for query profiling */
84 protected $agent;
85
86 /** @var BagOStuff APC cache */
87 protected $srvCache;
88 /** @var LoggerInterface */
89 protected $connLogger;
90 /** @var LoggerInterface */
91 protected $queryLogger;
92 /** @var callback Error logging callback */
93 protected $errorLogger;
94
95 /** @var resource|null Database connection */
96 protected $conn = null;
97 /** @var bool */
98 protected $opened = false;
99
100 /** @var array[] List of (callable, method name) */
101 protected $trxIdleCallbacks = [];
102 /** @var array[] List of (callable, method name) */
103 protected $trxPreCommitCallbacks = [];
104 /** @var array[] List of (callable, method name) */
105 protected $trxEndCallbacks = [];
106 /** @var callable[] Map of (name => callable) */
107 protected $trxRecurringCallbacks = [];
108 /** @var bool Whether to suppress triggering of transaction end callbacks */
109 protected $trxEndCallbacksSuppressed = false;
110
111 /** @var string */
112 protected $tablePrefix = '';
113 /** @var string */
114 protected $schema = '';
115 /** @var int */
116 protected $flags;
117 /** @var array */
118 protected $lbInfo = [];
119 /** @var array|bool */
120 protected $schemaVars = false;
121 /** @var array */
122 protected $sessionVars = [];
123 /** @var array|null */
124 protected $preparedArgs;
125 /** @var string|bool|null Stashed value of html_errors INI setting */
126 protected $htmlErrors;
127 /** @var string */
128 protected $delimiter = ';';
129 /** @var DatabaseDomain */
130 protected $currentDomain;
131 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
132 protected $affectedRowCount;
133
134 /**
135 * Either 1 if a transaction is active or 0 otherwise.
136 * The other Trx fields may not be meaningfull if this is 0.
137 *
138 * @var int
139 */
140 protected $trxLevel = 0;
141 /**
142 * Either a short hexidecimal string if a transaction is active or ""
143 *
144 * @var string
145 * @see Database::trxLevel
146 */
147 protected $trxShortId = '';
148 /**
149 * The UNIX time that the transaction started. Callers can assume that if
150 * snapshot isolation is used, then the data is *at least* up to date to that
151 * point (possibly more up-to-date since the first SELECT defines the snapshot).
152 *
153 * @var float|null
154 * @see Database::trxLevel
155 */
156 private $trxTimestamp = null;
157 /** @var float Lag estimate at the time of BEGIN */
158 private $trxReplicaLag = null;
159 /**
160 * Remembers the function name given for starting the most recent transaction via begin().
161 * Used to provide additional context for error reporting.
162 *
163 * @var string
164 * @see Database::trxLevel
165 */
166 private $trxFname = null;
167 /**
168 * Record if possible write queries were done in the last transaction started
169 *
170 * @var bool
171 * @see Database::trxLevel
172 */
173 private $trxDoneWrites = false;
174 /**
175 * Record if the current transaction was started implicitly due to DBO_TRX being set.
176 *
177 * @var bool
178 * @see Database::trxLevel
179 */
180 private $trxAutomatic = false;
181 /**
182 * Array of levels of atomicity within transactions
183 *
184 * @var array
185 */
186 private $trxAtomicLevels = [];
187 /**
188 * Record if the current transaction was started implicitly by Database::startAtomic
189 *
190 * @var bool
191 */
192 private $trxAutomaticAtomic = false;
193 /**
194 * Track the write query callers of the current transaction
195 *
196 * @var string[]
197 */
198 private $trxWriteCallers = [];
199 /**
200 * @var float Seconds spent in write queries for the current transaction
201 */
202 private $trxWriteDuration = 0.0;
203 /**
204 * @var int Number of write queries for the current transaction
205 */
206 private $trxWriteQueryCount = 0;
207 /**
208 * @var int Number of rows affected by write queries for the current transaction
209 */
210 private $trxWriteAffectedRows = 0;
211 /**
212 * @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries
213 */
214 private $trxWriteAdjDuration = 0.0;
215 /**
216 * @var int Number of write queries counted in trxWriteAdjDuration
217 */
218 private $trxWriteAdjQueryCount = 0;
219 /**
220 * @var float RTT time estimate
221 */
222 private $rttEstimate = 0.0;
223
224 /** @var array Map of (name => 1) for locks obtained via lock() */
225 private $namedLocksHeld = [];
226 /** @var array Map of (table name => 1) for TEMPORARY tables */
227 protected $sessionTempTables = [];
228
229 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
230 private $lazyMasterHandle;
231
232 /** @var float UNIX timestamp */
233 protected $lastPing = 0.0;
234
235 /** @var int[] Prior flags member variable values */
236 private $priorFlags = [];
237
238 /** @var object|string Class name or object With profileIn/profileOut methods */
239 protected $profiler;
240 /** @var TransactionProfiler */
241 protected $trxProfiler;
242
243 /** @var int */
244 protected $nonNativeInsertSelectBatchSize = 10000;
245
246 /**
247 * Constructor and database handle and attempt to connect to the DB server
248 *
249 * IDatabase classes should not be constructed directly in external
250 * code. Database::factory() should be used instead.
251 *
252 * @param array $params Parameters passed from Database::factory()
253 */
254 function __construct( array $params ) {
255 $server = $params['host'];
256 $user = $params['user'];
257 $password = $params['password'];
258 $dbName = $params['dbname'];
259
260 $this->schema = $params['schema'];
261 $this->tablePrefix = $params['tablePrefix'];
262
263 $this->cliMode = $params['cliMode'];
264 // Agent name is added to SQL queries in a comment, so make sure it can't break out
265 $this->agent = str_replace( '/', '-', $params['agent'] );
266
267 $this->flags = $params['flags'];
268 if ( $this->flags & self::DBO_DEFAULT ) {
269 if ( $this->cliMode ) {
270 $this->flags &= ~self::DBO_TRX;
271 } else {
272 $this->flags |= self::DBO_TRX;
273 }
274 }
275
276 $this->sessionVars = $params['variables'];
277
278 $this->srvCache = isset( $params['srvCache'] )
279 ? $params['srvCache']
280 : new HashBagOStuff();
281
282 $this->profiler = $params['profiler'];
283 $this->trxProfiler = $params['trxProfiler'];
284 $this->connLogger = $params['connLogger'];
285 $this->queryLogger = $params['queryLogger'];
286 $this->errorLogger = $params['errorLogger'];
287
288 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
289 $this->nonNativeInsertSelectBatchSize = $params['nonNativeInsertSelectBatchSize'];
290 }
291
292 // Set initial dummy domain until open() sets the final DB/prefix
293 $this->currentDomain = DatabaseDomain::newUnspecified();
294
295 if ( $user ) {
296 $this->open( $server, $user, $password, $dbName );
297 } elseif ( $this->requiresDatabaseUser() ) {
298 throw new InvalidArgumentException( "No database user provided." );
299 }
300
301 // Set the domain object after open() sets the relevant fields
302 if ( $this->dbName != '' ) {
303 // Domains with server scope but a table prefix are not used by IDatabase classes
304 $this->currentDomain = new DatabaseDomain( $this->dbName, null, $this->tablePrefix );
305 }
306 }
307
308 /**
309 * Construct a Database subclass instance given a database type and parameters
310 *
311 * This also connects to the database immediately upon object construction
312 *
313 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
314 * @param array $p Parameter map with keys:
315 * - host : The hostname of the DB server
316 * - user : The name of the database user the client operates under
317 * - password : The password for the database user
318 * - dbname : The name of the database to use where queries do not specify one.
319 * The database must exist or an error might be thrown. Setting this to the empty string
320 * will avoid any such errors and make the handle have no implicit database scope. This is
321 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
322 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
323 * in which user names and such are defined, e.g. users are database-specific in Postgres.
324 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
325 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
326 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
327 * recognized in queries. This can be used in place of schemas for handle site farms.
328 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
329 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
330 * flag in place UNLESS this this database simply acts as a key/value store.
331 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
332 * 'mysqli' driver; the old one 'mysql' has been removed.
333 * - variables: Optional map of session variables to set after connecting. This can be
334 * used to adjust lock timeouts or encoding modes and the like.
335 * - connLogger: Optional PSR-3 logger interface instance.
336 * - queryLogger: Optional PSR-3 logger interface instance.
337 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
338 * These will be called in query(), using a simplified version of the SQL that also
339 * includes the agent as a SQL comment.
340 * - trxProfiler: Optional TransactionProfiler instance.
341 * - errorLogger: Optional callback that takes an Exception and logs it.
342 * - cliMode: Whether to consider the execution context that of a CLI script.
343 * - agent: Optional name used to identify the end-user in query profiling/logging.
344 * - srvCache: Optional BagOStuff instance to an APC-style cache.
345 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
346 * @return Database|null If the database driver or extension cannot be found
347 * @throws InvalidArgumentException If the database driver or extension cannot be found
348 * @since 1.18
349 */
350 final public static function factory( $dbType, $p = [] ) {
351 $class = self::getClass( $dbType, isset( $p['driver'] ) ? $p['driver'] : null );
352
353 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase::class ) ) {
354 // Resolve some defaults for b/c
355 $p['host'] = isset( $p['host'] ) ? $p['host'] : false;
356 $p['user'] = isset( $p['user'] ) ? $p['user'] : false;
357 $p['password'] = isset( $p['password'] ) ? $p['password'] : false;
358 $p['dbname'] = isset( $p['dbname'] ) ? $p['dbname'] : false;
359 $p['flags'] = isset( $p['flags'] ) ? $p['flags'] : 0;
360 $p['variables'] = isset( $p['variables'] ) ? $p['variables'] : [];
361 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : '';
362 $p['schema'] = isset( $p['schema'] ) ? $p['schema'] : '';
363 $p['cliMode'] = isset( $p['cliMode'] )
364 ? $p['cliMode']
365 : ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' );
366 $p['agent'] = isset( $p['agent'] ) ? $p['agent'] : '';
367 if ( !isset( $p['connLogger'] ) ) {
368 $p['connLogger'] = new NullLogger();
369 }
370 if ( !isset( $p['queryLogger'] ) ) {
371 $p['queryLogger'] = new NullLogger();
372 }
373 $p['profiler'] = isset( $p['profiler'] ) ? $p['profiler'] : null;
374 if ( !isset( $p['trxProfiler'] ) ) {
375 $p['trxProfiler'] = new TransactionProfiler();
376 }
377 if ( !isset( $p['errorLogger'] ) ) {
378 $p['errorLogger'] = function ( Exception $e ) {
379 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
380 };
381 }
382
383 $conn = new $class( $p );
384 } else {
385 $conn = null;
386 }
387
388 return $conn;
389 }
390
391 /**
392 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
393 * @param string|null $driver Optional name of a specific DB client driver
394 * @return array Map of (Database::ATTRIBUTE_* constant => value) for all such constants
395 * @throws InvalidArgumentException
396 * @since 1.31
397 */
398 final public static function attributesFromType( $dbType, $driver = null ) {
399 static $defaults = [ self::ATTR_DB_LEVEL_LOCKING => false ];
400
401 $class = self::getClass( $dbType, $driver );
402
403 return call_user_func( [ $class, 'getAttributes' ] ) + $defaults;
404 }
405
406 /**
407 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
408 * @param string|null $driver Optional name of a specific DB client driver
409 * @return string Database subclass name to use
410 * @throws InvalidArgumentException
411 */
412 private static function getClass( $dbType, $driver = null ) {
413 // For database types with built-in support, the below maps type to IDatabase
414 // implementations. For types with multipe driver implementations (PHP extensions),
415 // an array can be used, keyed by extension name. In case of an array, the
416 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
417 // we auto-detect the first available driver. For types without built-in support,
418 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
419 static $builtinTypes = [
420 'mssql' => DatabaseMssql::class,
421 'mysql' => [ 'mysqli' => DatabaseMysqli::class ],
422 'sqlite' => DatabaseSqlite::class,
423 'postgres' => DatabasePostgres::class,
424 ];
425
426 $dbType = strtolower( $dbType );
427 $class = false;
428
429 if ( isset( $builtinTypes[$dbType] ) ) {
430 $possibleDrivers = $builtinTypes[$dbType];
431 if ( is_string( $possibleDrivers ) ) {
432 $class = $possibleDrivers;
433 } else {
434 if ( (string)$driver !== '' ) {
435 if ( !isset( $possibleDrivers[$driver] ) ) {
436 throw new InvalidArgumentException( __METHOD__ .
437 " type '$dbType' does not support driver '{$driver}'" );
438 } else {
439 $class = $possibleDrivers[$driver];
440 }
441 } else {
442 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
443 if ( extension_loaded( $posDriver ) ) {
444 $class = $possibleClass;
445 break;
446 }
447 }
448 }
449 }
450 } else {
451 $class = 'Database' . ucfirst( $dbType );
452 }
453
454 if ( $class === false ) {
455 throw new InvalidArgumentException( __METHOD__ .
456 " no viable database extension found for type '$dbType'" );
457 }
458
459 return $class;
460 }
461
462 /**
463 * @return array Map of (Database::ATTRIBUTE_* constant => value
464 * @since 1.31
465 */
466 protected static function getAttributes() {
467 return [];
468 }
469
470 /**
471 * Set the PSR-3 logger interface to use for query logging. (The logger
472 * interfaces for connection logging and error logging can be set with the
473 * constructor.)
474 *
475 * @param LoggerInterface $logger
476 */
477 public function setLogger( LoggerInterface $logger ) {
478 $this->queryLogger = $logger;
479 }
480
481 public function getServerInfo() {
482 return $this->getServerVersion();
483 }
484
485 public function bufferResults( $buffer = null ) {
486 $res = !$this->getFlag( self::DBO_NOBUFFER );
487 if ( $buffer !== null ) {
488 $buffer
489 ? $this->clearFlag( self::DBO_NOBUFFER )
490 : $this->setFlag( self::DBO_NOBUFFER );
491 }
492
493 return $res;
494 }
495
496 /**
497 * Turns on (false) or off (true) the automatic generation and sending
498 * of a "we're sorry, but there has been a database error" page on
499 * database errors. Default is on (false). When turned off, the
500 * code should use lastErrno() and lastError() to handle the
501 * situation as appropriate.
502 *
503 * Do not use this function outside of the Database classes.
504 *
505 * @param null|bool $ignoreErrors
506 * @return bool The previous value of the flag.
507 */
508 protected function ignoreErrors( $ignoreErrors = null ) {
509 $res = $this->getFlag( self::DBO_IGNORE );
510 if ( $ignoreErrors !== null ) {
511 // setFlag()/clearFlag() do not allow DBO_IGNORE changes for sanity
512 if ( $ignoreErrors ) {
513 $this->flags |= self::DBO_IGNORE;
514 } else {
515 $this->flags &= ~self::DBO_IGNORE;
516 }
517 }
518
519 return $res;
520 }
521
522 public function trxLevel() {
523 return $this->trxLevel;
524 }
525
526 public function trxTimestamp() {
527 return $this->trxLevel ? $this->trxTimestamp : null;
528 }
529
530 public function tablePrefix( $prefix = null ) {
531 $old = $this->tablePrefix;
532 if ( $prefix !== null ) {
533 $this->tablePrefix = $prefix;
534 $this->currentDomain = ( $this->dbName != '' )
535 ? new DatabaseDomain( $this->dbName, null, $this->tablePrefix )
536 : DatabaseDomain::newUnspecified();
537 }
538
539 return $old;
540 }
541
542 public function dbSchema( $schema = null ) {
543 $old = $this->schema;
544 if ( $schema !== null ) {
545 $this->schema = $schema;
546 }
547
548 return $old;
549 }
550
551 public function getLBInfo( $name = null ) {
552 if ( is_null( $name ) ) {
553 return $this->lbInfo;
554 } else {
555 if ( array_key_exists( $name, $this->lbInfo ) ) {
556 return $this->lbInfo[$name];
557 } else {
558 return null;
559 }
560 }
561 }
562
563 public function setLBInfo( $name, $value = null ) {
564 if ( is_null( $value ) ) {
565 $this->lbInfo = $name;
566 } else {
567 $this->lbInfo[$name] = $value;
568 }
569 }
570
571 public function setLazyMasterHandle( IDatabase $conn ) {
572 $this->lazyMasterHandle = $conn;
573 }
574
575 /**
576 * @return IDatabase|null
577 * @see setLazyMasterHandle()
578 * @since 1.27
579 */
580 protected function getLazyMasterHandle() {
581 return $this->lazyMasterHandle;
582 }
583
584 public function implicitGroupby() {
585 return true;
586 }
587
588 public function implicitOrderby() {
589 return true;
590 }
591
592 public function lastQuery() {
593 return $this->lastQuery;
594 }
595
596 public function doneWrites() {
597 return (bool)$this->lastWriteTime;
598 }
599
600 public function lastDoneWrites() {
601 return $this->lastWriteTime ?: false;
602 }
603
604 public function writesPending() {
605 return $this->trxLevel && $this->trxDoneWrites;
606 }
607
608 public function writesOrCallbacksPending() {
609 return $this->trxLevel && (
610 $this->trxDoneWrites || $this->trxIdleCallbacks || $this->trxPreCommitCallbacks
611 );
612 }
613
614 public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL ) {
615 if ( !$this->trxLevel ) {
616 return false;
617 } elseif ( !$this->trxDoneWrites ) {
618 return 0.0;
619 }
620
621 switch ( $type ) {
622 case self::ESTIMATE_DB_APPLY:
623 $this->ping( $rtt );
624 $rttAdjTotal = $this->trxWriteAdjQueryCount * $rtt;
625 $applyTime = max( $this->trxWriteAdjDuration - $rttAdjTotal, 0 );
626 // For omitted queries, make them count as something at least
627 $omitted = $this->trxWriteQueryCount - $this->trxWriteAdjQueryCount;
628 $applyTime += self::TINY_WRITE_SEC * $omitted;
629
630 return $applyTime;
631 default: // everything
632 return $this->trxWriteDuration;
633 }
634 }
635
636 public function pendingWriteCallers() {
637 return $this->trxLevel ? $this->trxWriteCallers : [];
638 }
639
640 public function pendingWriteRowsAffected() {
641 return $this->trxWriteAffectedRows;
642 }
643
644 /**
645 * Get the list of method names that have pending write queries or callbacks
646 * for this transaction
647 *
648 * @return array
649 */
650 protected function pendingWriteAndCallbackCallers() {
651 if ( !$this->trxLevel ) {
652 return [];
653 }
654
655 $fnames = $this->trxWriteCallers;
656 foreach ( [
657 $this->trxIdleCallbacks,
658 $this->trxPreCommitCallbacks,
659 $this->trxEndCallbacks
660 ] as $callbacks ) {
661 foreach ( $callbacks as $callback ) {
662 $fnames[] = $callback[1];
663 }
664 }
665
666 return $fnames;
667 }
668
669 public function isOpen() {
670 return $this->opened;
671 }
672
673 public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
674 if ( ( $flag & self::DBO_IGNORE ) ) {
675 throw new \UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
676 }
677
678 if ( $remember === self::REMEMBER_PRIOR ) {
679 array_push( $this->priorFlags, $this->flags );
680 }
681 $this->flags |= $flag;
682 }
683
684 public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
685 if ( ( $flag & self::DBO_IGNORE ) ) {
686 throw new \UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
687 }
688
689 if ( $remember === self::REMEMBER_PRIOR ) {
690 array_push( $this->priorFlags, $this->flags );
691 }
692 $this->flags &= ~$flag;
693 }
694
695 public function restoreFlags( $state = self::RESTORE_PRIOR ) {
696 if ( !$this->priorFlags ) {
697 return;
698 }
699
700 if ( $state === self::RESTORE_INITIAL ) {
701 $this->flags = reset( $this->priorFlags );
702 $this->priorFlags = [];
703 } else {
704 $this->flags = array_pop( $this->priorFlags );
705 }
706 }
707
708 public function getFlag( $flag ) {
709 return !!( $this->flags & $flag );
710 }
711
712 /**
713 * @param string $name Class field name
714 * @return mixed
715 * @deprecated Since 1.28
716 */
717 public function getProperty( $name ) {
718 return $this->$name;
719 }
720
721 public function getDomainID() {
722 return $this->currentDomain->getId();
723 }
724
725 final public function getWikiID() {
726 return $this->getDomainID();
727 }
728
729 /**
730 * Get information about an index into an object
731 * @param string $table Table name
732 * @param string $index Index name
733 * @param string $fname Calling function name
734 * @return mixed Database-specific index description class or false if the index does not exist
735 */
736 abstract function indexInfo( $table, $index, $fname = __METHOD__ );
737
738 /**
739 * Wrapper for addslashes()
740 *
741 * @param string $s String to be slashed.
742 * @return string Slashed string.
743 */
744 abstract function strencode( $s );
745
746 /**
747 * Set a custom error handler for logging errors during database connection
748 */
749 protected function installErrorHandler() {
750 $this->phpError = false;
751 $this->htmlErrors = ini_set( 'html_errors', '0' );
752 set_error_handler( [ $this, 'connectionErrorLogger' ] );
753 }
754
755 /**
756 * Restore the previous error handler and return the last PHP error for this DB
757 *
758 * @return bool|string
759 */
760 protected function restoreErrorHandler() {
761 restore_error_handler();
762 if ( $this->htmlErrors !== false ) {
763 ini_set( 'html_errors', $this->htmlErrors );
764 }
765
766 return $this->getLastPHPError();
767 }
768
769 /**
770 * @return string|bool Last PHP error for this DB (typically connection errors)
771 */
772 protected function getLastPHPError() {
773 if ( $this->phpError ) {
774 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->phpError );
775 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
776
777 return $error;
778 }
779
780 return false;
781 }
782
783 /**
784 * Error handler for logging errors during database connection
785 * This method should not be used outside of Database classes
786 *
787 * @param int $errno
788 * @param string $errstr
789 */
790 public function connectionErrorLogger( $errno, $errstr ) {
791 $this->phpError = $errstr;
792 }
793
794 /**
795 * Create a log context to pass to PSR-3 logger functions.
796 *
797 * @param array $extras Additional data to add to context
798 * @return array
799 */
800 protected function getLogContext( array $extras = [] ) {
801 return array_merge(
802 [
803 'db_server' => $this->server,
804 'db_name' => $this->dbName,
805 'db_user' => $this->user,
806 ],
807 $extras
808 );
809 }
810
811 public function close() {
812 if ( $this->conn ) {
813 if ( $this->trxLevel() ) {
814 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
815 }
816
817 $closed = $this->closeConnection();
818 $this->conn = false;
819 } elseif (
820 $this->trxIdleCallbacks ||
821 $this->trxPreCommitCallbacks ||
822 $this->trxEndCallbacks
823 ) { // sanity
824 throw new RuntimeException( "Transaction callbacks still pending." );
825 } else {
826 $closed = true;
827 }
828 $this->opened = false;
829
830 return $closed;
831 }
832
833 /**
834 * Make sure isOpen() returns true as a sanity check
835 *
836 * @throws DBUnexpectedError
837 */
838 protected function assertOpen() {
839 if ( !$this->isOpen() ) {
840 throw new DBUnexpectedError( $this, "DB connection was already closed." );
841 }
842 }
843
844 /**
845 * Closes underlying database connection
846 * @since 1.20
847 * @return bool Whether connection was closed successfully
848 */
849 abstract protected function closeConnection();
850
851 public function reportConnectionError( $error = 'Unknown error' ) {
852 $myError = $this->lastError();
853 if ( $myError ) {
854 $error = $myError;
855 }
856
857 # New method
858 throw new DBConnectionError( $this, $error );
859 }
860
861 /**
862 * The DBMS-dependent part of query()
863 *
864 * @param string $sql SQL query.
865 * @return ResultWrapper|bool Result object to feed to fetchObject,
866 * fetchRow, ...; or false on failure
867 */
868 abstract protected function doQuery( $sql );
869
870 /**
871 * Determine whether a query writes to the DB.
872 * Should return true if unsure.
873 *
874 * @param string $sql
875 * @return bool
876 */
877 protected function isWriteQuery( $sql ) {
878 return !preg_match(
879 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
880 }
881
882 /**
883 * @param string $sql
884 * @return string|null
885 */
886 protected function getQueryVerb( $sql ) {
887 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ? strtoupper( $m[1] ) : null;
888 }
889
890 /**
891 * Determine whether a SQL statement is sensitive to isolation level.
892 * A SQL statement is considered transactable if its result could vary
893 * depending on the transaction isolation level. Operational commands
894 * such as 'SET' and 'SHOW' are not considered to be transactable.
895 *
896 * @param string $sql
897 * @return bool
898 */
899 protected function isTransactableQuery( $sql ) {
900 return !in_array(
901 $this->getQueryVerb( $sql ),
902 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
903 true
904 );
905 }
906
907 /**
908 * @param string $sql A SQL query
909 * @return bool Whether $sql is SQL for TEMPORARY table operation
910 */
911 protected function registerTempTableOperation( $sql ) {
912 if ( preg_match(
913 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
914 $sql,
915 $matches
916 ) ) {
917 $this->sessionTempTables[$matches[1]] = 1;
918
919 return true;
920 } elseif ( preg_match(
921 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
922 $sql,
923 $matches
924 ) ) {
925 $isTemp = isset( $this->sessionTempTables[$matches[1]] );
926 unset( $this->sessionTempTables[$matches[1]] );
927
928 return $isTemp;
929 } elseif ( preg_match(
930 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
931 $sql,
932 $matches
933 ) ) {
934 return isset( $this->sessionTempTables[$matches[1]] );
935 } elseif ( preg_match(
936 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
937 $sql,
938 $matches
939 ) ) {
940 return isset( $this->sessionTempTables[$matches[1]] );
941 }
942
943 return false;
944 }
945
946 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
947 $priorWritesPending = $this->writesOrCallbacksPending();
948 $this->lastQuery = $sql;
949
950 $isWrite = $this->isWriteQuery( $sql );
951 if ( $isWrite ) {
952 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
953 } else {
954 $isNonTempWrite = false;
955 }
956
957 if ( $isWrite ) {
958 if ( $this->getLBInfo( 'replica' ) === true ) {
959 throw new DBError(
960 $this,
961 'Write operations are not allowed on replica database connections.'
962 );
963 }
964 # In theory, non-persistent writes are allowed in read-only mode, but due to things
965 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
966 $reason = $this->getReadOnlyReason();
967 if ( $reason !== false ) {
968 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
969 }
970 # Set a flag indicating that writes have been done
971 $this->lastWriteTime = microtime( true );
972 }
973
974 # Add trace comment to the begin of the sql string, right after the operator.
975 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
976 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
977
978 # Start implicit transactions that wrap the request if DBO_TRX is enabled
979 if ( !$this->trxLevel && $this->getFlag( self::DBO_TRX )
980 && $this->isTransactableQuery( $sql )
981 ) {
982 $this->begin( __METHOD__ . " ($fname)", self::TRANSACTION_INTERNAL );
983 $this->trxAutomatic = true;
984 }
985
986 # Keep track of whether the transaction has write queries pending
987 if ( $this->trxLevel && !$this->trxDoneWrites && $isWrite ) {
988 $this->trxDoneWrites = true;
989 $this->trxProfiler->transactionWritingIn(
990 $this->server, $this->dbName, $this->trxShortId );
991 }
992
993 if ( $this->getFlag( self::DBO_DEBUG ) ) {
994 $this->queryLogger->debug( "{$this->dbName} {$commentedSql}" );
995 }
996
997 # Avoid fatals if close() was called
998 $this->assertOpen();
999
1000 # Send the query to the server
1001 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1002
1003 # Try reconnecting if the connection was lost
1004 if ( false === $ret && $this->wasErrorReissuable() ) {
1005 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1006 # Stash the last error values before anything might clear them
1007 $lastError = $this->lastError();
1008 $lastErrno = $this->lastErrno();
1009 # Update state tracking to reflect transaction loss due to disconnection
1010 $this->handleSessionLoss();
1011 if ( $this->reconnect() ) {
1012 $msg = __METHOD__ . ': lost connection to {dbserver}; reconnected';
1013 $params = [ 'dbserver' => $this->getServer() ];
1014 $this->connLogger->warning( $msg, $params );
1015 $this->queryLogger->warning( $msg, $params +
1016 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ] );
1017
1018 if ( !$recoverable ) {
1019 # Callers may catch the exception and continue to use the DB
1020 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
1021 } else {
1022 # Should be safe to silently retry the query
1023 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1024 }
1025 } else {
1026 $msg = __METHOD__ . ': lost connection to {dbserver} permanently';
1027 $this->connLogger->error( $msg, [ 'dbserver' => $this->getServer() ] );
1028 }
1029 }
1030
1031 if ( false === $ret ) {
1032 # Deadlocks cause the entire transaction to abort, not just the statement.
1033 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1034 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
1035 if ( $this->wasDeadlock() ) {
1036 if ( $this->explicitTrxActive() || $priorWritesPending ) {
1037 $tempIgnore = false; // not recoverable
1038 }
1039 # Update state tracking to reflect transaction loss
1040 $this->handleSessionLoss();
1041 }
1042
1043 $this->reportQueryError(
1044 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1045 }
1046
1047 $res = $this->resultObject( $ret );
1048
1049 return $res;
1050 }
1051
1052 /**
1053 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1054 *
1055 * @param string $sql Original SQL query
1056 * @param string $commentedSql SQL query with debugging/trace comment
1057 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1058 * @param string $fname Name of the calling function
1059 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1060 * object for a successful read query, or false on failure
1061 */
1062 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1063 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1064 # generalizeSQL() will probably cut down the query to reasonable
1065 # logging size most of the time. The substr is really just a sanity check.
1066 if ( $isMaster ) {
1067 $queryProf = 'query-m: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
1068 } else {
1069 $queryProf = 'query: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
1070 }
1071
1072 # Include query transaction state
1073 $queryProf .= $this->trxShortId ? " [TRX#{$this->trxShortId}]" : "";
1074
1075 $startTime = microtime( true );
1076 if ( $this->profiler ) {
1077 call_user_func( [ $this->profiler, 'profileIn' ], $queryProf );
1078 }
1079 $this->affectedRowCount = null;
1080 $ret = $this->doQuery( $commentedSql );
1081 $this->affectedRowCount = $this->affectedRows();
1082 if ( $this->profiler ) {
1083 call_user_func( [ $this->profiler, 'profileOut' ], $queryProf );
1084 }
1085 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1086
1087 unset( $queryProfSection ); // profile out (if set)
1088
1089 if ( $ret !== false ) {
1090 $this->lastPing = $startTime;
1091 if ( $isWrite && $this->trxLevel ) {
1092 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1093 $this->trxWriteCallers[] = $fname;
1094 }
1095 }
1096
1097 if ( $sql === self::PING_QUERY ) {
1098 $this->rttEstimate = $queryRuntime;
1099 }
1100
1101 $this->trxProfiler->recordQueryCompletion(
1102 $queryProf, $startTime, $isWrite, $this->affectedRows()
1103 );
1104 $this->queryLogger->debug( $sql, [
1105 'method' => $fname,
1106 'master' => $isMaster,
1107 'runtime' => $queryRuntime,
1108 ] );
1109
1110 return $ret;
1111 }
1112
1113 /**
1114 * Update the estimated run-time of a query, not counting large row lock times
1115 *
1116 * LoadBalancer can be set to rollback transactions that will create huge replication
1117 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1118 * queries, like inserting a row can take a long time due to row locking. This method
1119 * uses some simple heuristics to discount those cases.
1120 *
1121 * @param string $sql A SQL write query
1122 * @param float $runtime Total runtime, including RTT
1123 * @param int $affected Affected row count
1124 */
1125 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1126 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1127 $indicativeOfReplicaRuntime = true;
1128 if ( $runtime > self::SLOW_WRITE_SEC ) {
1129 $verb = $this->getQueryVerb( $sql );
1130 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1131 if ( $verb === 'INSERT' ) {
1132 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS;
1133 } elseif ( $verb === 'REPLACE' ) {
1134 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS / 2;
1135 }
1136 }
1137
1138 $this->trxWriteDuration += $runtime;
1139 $this->trxWriteQueryCount += 1;
1140 $this->trxWriteAffectedRows += $affected;
1141 if ( $indicativeOfReplicaRuntime ) {
1142 $this->trxWriteAdjDuration += $runtime;
1143 $this->trxWriteAdjQueryCount += 1;
1144 }
1145 }
1146
1147 /**
1148 * Determine whether or not it is safe to retry queries after a database
1149 * connection is lost
1150 *
1151 * @param string $sql SQL query
1152 * @param bool $priorWritesPending Whether there is a transaction open with
1153 * possible write queries or transaction pre-commit/idle callbacks
1154 * waiting on it to finish.
1155 * @return bool True if it is safe to retry the query, false otherwise
1156 */
1157 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1158 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1159 # Dropped connections also mean that named locks are automatically released.
1160 # Only allow error suppression in autocommit mode or when the lost transaction
1161 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1162 if ( $this->namedLocksHeld ) {
1163 return false; // possible critical section violation
1164 } elseif ( $sql === 'COMMIT' ) {
1165 return !$priorWritesPending; // nothing written anyway? (T127428)
1166 } elseif ( $sql === 'ROLLBACK' ) {
1167 return true; // transaction lost...which is also what was requested :)
1168 } elseif ( $this->explicitTrxActive() ) {
1169 return false; // don't drop atomocity
1170 } elseif ( $priorWritesPending ) {
1171 return false; // prior writes lost from implicit transaction
1172 }
1173
1174 return true;
1175 }
1176
1177 /**
1178 * Clean things up after transaction loss due to disconnection
1179 *
1180 * @return null|Exception
1181 */
1182 private function handleSessionLoss() {
1183 $this->trxLevel = 0;
1184 $this->trxIdleCallbacks = []; // T67263
1185 $this->trxPreCommitCallbacks = []; // T67263
1186 $this->sessionTempTables = [];
1187 $this->namedLocksHeld = [];
1188 try {
1189 // Handle callbacks in trxEndCallbacks
1190 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
1191 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
1192 return null;
1193 } catch ( Exception $e ) {
1194 // Already logged; move on...
1195 return $e;
1196 }
1197 }
1198
1199 /**
1200 * Checks whether the cause of the error is detected to be a timeout.
1201 *
1202 * It returns false by default, and not all engines support detecting this yet.
1203 * If this returns false, it will be treated as a generic query error.
1204 *
1205 * @param string $error Error text
1206 * @param int $errno Error number
1207 * @return bool
1208 */
1209 protected function wasQueryTimeout( $error, $errno ) {
1210 return false;
1211 }
1212
1213 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1214 if ( $this->ignoreErrors() || $tempIgnore ) {
1215 $this->queryLogger->debug( "SQL ERROR (ignored): $error\n" );
1216 } else {
1217 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1218 $this->queryLogger->error(
1219 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1220 $this->getLogContext( [
1221 'method' => __METHOD__,
1222 'errno' => $errno,
1223 'error' => $error,
1224 'sql1line' => $sql1line,
1225 'fname' => $fname,
1226 ] )
1227 );
1228 $this->queryLogger->debug( "SQL ERROR: " . $error . "\n" );
1229 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1230 if ( $wasQueryTimeout ) {
1231 throw new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1232 } else {
1233 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1234 }
1235 }
1236 }
1237
1238 public function freeResult( $res ) {
1239 }
1240
1241 public function selectField(
1242 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1243 ) {
1244 if ( $var === '*' ) { // sanity
1245 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1246 }
1247
1248 if ( !is_array( $options ) ) {
1249 $options = [ $options ];
1250 }
1251
1252 $options['LIMIT'] = 1;
1253
1254 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1255 if ( $res === false || !$this->numRows( $res ) ) {
1256 return false;
1257 }
1258
1259 $row = $this->fetchRow( $res );
1260
1261 if ( $row !== false ) {
1262 return reset( $row );
1263 } else {
1264 return false;
1265 }
1266 }
1267
1268 public function selectFieldValues(
1269 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1270 ) {
1271 if ( $var === '*' ) { // sanity
1272 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1273 } elseif ( !is_string( $var ) ) { // sanity
1274 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1275 }
1276
1277 if ( !is_array( $options ) ) {
1278 $options = [ $options ];
1279 }
1280
1281 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1282 if ( $res === false ) {
1283 return false;
1284 }
1285
1286 $values = [];
1287 foreach ( $res as $row ) {
1288 $values[] = $row->$var;
1289 }
1290
1291 return $values;
1292 }
1293
1294 /**
1295 * Returns an optional USE INDEX clause to go after the table, and a
1296 * string to go at the end of the query.
1297 *
1298 * @param array $options Associative array of options to be turned into
1299 * an SQL query, valid keys are listed in the function.
1300 * @return array
1301 * @see Database::select()
1302 */
1303 protected function makeSelectOptions( $options ) {
1304 $preLimitTail = $postLimitTail = '';
1305 $startOpts = '';
1306
1307 $noKeyOptions = [];
1308
1309 foreach ( $options as $key => $option ) {
1310 if ( is_numeric( $key ) ) {
1311 $noKeyOptions[$option] = true;
1312 }
1313 }
1314
1315 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1316
1317 $preLimitTail .= $this->makeOrderBy( $options );
1318
1319 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1320 $postLimitTail .= ' FOR UPDATE';
1321 }
1322
1323 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1324 $postLimitTail .= ' LOCK IN SHARE MODE';
1325 }
1326
1327 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1328 $startOpts .= 'DISTINCT';
1329 }
1330
1331 # Various MySQL extensions
1332 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1333 $startOpts .= ' /*! STRAIGHT_JOIN */';
1334 }
1335
1336 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1337 $startOpts .= ' HIGH_PRIORITY';
1338 }
1339
1340 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1341 $startOpts .= ' SQL_BIG_RESULT';
1342 }
1343
1344 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1345 $startOpts .= ' SQL_BUFFER_RESULT';
1346 }
1347
1348 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1349 $startOpts .= ' SQL_SMALL_RESULT';
1350 }
1351
1352 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1353 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1354 }
1355
1356 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1357 $startOpts .= ' SQL_CACHE';
1358 }
1359
1360 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1361 $startOpts .= ' SQL_NO_CACHE';
1362 }
1363
1364 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1365 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1366 } else {
1367 $useIndex = '';
1368 }
1369 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1370 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1371 } else {
1372 $ignoreIndex = '';
1373 }
1374
1375 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1376 }
1377
1378 /**
1379 * Returns an optional GROUP BY with an optional HAVING
1380 *
1381 * @param array $options Associative array of options
1382 * @return string
1383 * @see Database::select()
1384 * @since 1.21
1385 */
1386 protected function makeGroupByWithHaving( $options ) {
1387 $sql = '';
1388 if ( isset( $options['GROUP BY'] ) ) {
1389 $gb = is_array( $options['GROUP BY'] )
1390 ? implode( ',', $options['GROUP BY'] )
1391 : $options['GROUP BY'];
1392 $sql .= ' GROUP BY ' . $gb;
1393 }
1394 if ( isset( $options['HAVING'] ) ) {
1395 $having = is_array( $options['HAVING'] )
1396 ? $this->makeList( $options['HAVING'], self::LIST_AND )
1397 : $options['HAVING'];
1398 $sql .= ' HAVING ' . $having;
1399 }
1400
1401 return $sql;
1402 }
1403
1404 /**
1405 * Returns an optional ORDER BY
1406 *
1407 * @param array $options Associative array of options
1408 * @return string
1409 * @see Database::select()
1410 * @since 1.21
1411 */
1412 protected function makeOrderBy( $options ) {
1413 if ( isset( $options['ORDER BY'] ) ) {
1414 $ob = is_array( $options['ORDER BY'] )
1415 ? implode( ',', $options['ORDER BY'] )
1416 : $options['ORDER BY'];
1417
1418 return ' ORDER BY ' . $ob;
1419 }
1420
1421 return '';
1422 }
1423
1424 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1425 $options = [], $join_conds = [] ) {
1426 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1427
1428 return $this->query( $sql, $fname );
1429 }
1430
1431 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1432 $options = [], $join_conds = []
1433 ) {
1434 if ( is_array( $vars ) ) {
1435 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1436 }
1437
1438 $options = (array)$options;
1439 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1440 ? $options['USE INDEX']
1441 : [];
1442 $ignoreIndexes = (
1443 isset( $options['IGNORE INDEX'] ) &&
1444 is_array( $options['IGNORE INDEX'] )
1445 )
1446 ? $options['IGNORE INDEX']
1447 : [];
1448
1449 if ( is_array( $table ) ) {
1450 $from = ' FROM ' .
1451 $this->tableNamesWithIndexClauseOrJOIN(
1452 $table, $useIndexes, $ignoreIndexes, $join_conds );
1453 } elseif ( $table != '' ) {
1454 $from = ' FROM ' .
1455 $this->tableNamesWithIndexClauseOrJOIN(
1456 [ $table ], $useIndexes, $ignoreIndexes, [] );
1457 } else {
1458 $from = '';
1459 }
1460
1461 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1462 $this->makeSelectOptions( $options );
1463
1464 if ( !empty( $conds ) ) {
1465 if ( is_array( $conds ) ) {
1466 $conds = $this->makeList( $conds, self::LIST_AND );
1467 }
1468 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1469 "WHERE $conds $preLimitTail";
1470 } else {
1471 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1472 }
1473
1474 if ( isset( $options['LIMIT'] ) ) {
1475 $sql = $this->limitResult( $sql, $options['LIMIT'],
1476 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1477 }
1478 $sql = "$sql $postLimitTail";
1479
1480 if ( isset( $options['EXPLAIN'] ) ) {
1481 $sql = 'EXPLAIN ' . $sql;
1482 }
1483
1484 return $sql;
1485 }
1486
1487 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1488 $options = [], $join_conds = []
1489 ) {
1490 $options = (array)$options;
1491 $options['LIMIT'] = 1;
1492 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1493
1494 if ( $res === false ) {
1495 return false;
1496 }
1497
1498 if ( !$this->numRows( $res ) ) {
1499 return false;
1500 }
1501
1502 $obj = $this->fetchObject( $res );
1503
1504 return $obj;
1505 }
1506
1507 public function estimateRowCount(
1508 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = []
1509 ) {
1510 $rows = 0;
1511 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1512
1513 if ( $res ) {
1514 $row = $this->fetchRow( $res );
1515 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1516 }
1517
1518 return $rows;
1519 }
1520
1521 public function selectRowCount(
1522 $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1523 ) {
1524 $rows = 0;
1525 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1526 // The identifier quotes is primarily for MSSQL.
1527 $rowCountCol = $this->addIdentifierQuotes( "rowcount" );
1528 $tableName = $this->addIdentifierQuotes( "tmp_count" );
1529 $res = $this->query( "SELECT COUNT(*) AS $rowCountCol FROM ($sql) $tableName", $fname );
1530
1531 if ( $res ) {
1532 $row = $this->fetchRow( $res );
1533 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1534 }
1535
1536 return $rows;
1537 }
1538
1539 /**
1540 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1541 * It's only slightly flawed. Don't use for anything important.
1542 *
1543 * @param string $sql A SQL Query
1544 *
1545 * @return string
1546 */
1547 protected static function generalizeSQL( $sql ) {
1548 # This does the same as the regexp below would do, but in such a way
1549 # as to avoid crashing php on some large strings.
1550 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1551
1552 $sql = str_replace( "\\\\", '', $sql );
1553 $sql = str_replace( "\\'", '', $sql );
1554 $sql = str_replace( "\\\"", '', $sql );
1555 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1556 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1557
1558 # All newlines, tabs, etc replaced by single space
1559 $sql = preg_replace( '/\s+/', ' ', $sql );
1560
1561 # All numbers => N,
1562 # except the ones surrounded by characters, e.g. l10n
1563 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1564 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1565
1566 return $sql;
1567 }
1568
1569 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1570 $info = $this->fieldInfo( $table, $field );
1571
1572 return (bool)$info;
1573 }
1574
1575 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1576 if ( !$this->tableExists( $table ) ) {
1577 return null;
1578 }
1579
1580 $info = $this->indexInfo( $table, $index, $fname );
1581 if ( is_null( $info ) ) {
1582 return null;
1583 } else {
1584 return $info !== false;
1585 }
1586 }
1587
1588 public function tableExists( $table, $fname = __METHOD__ ) {
1589 $tableRaw = $this->tableName( $table, 'raw' );
1590 if ( isset( $this->sessionTempTables[$tableRaw] ) ) {
1591 return true; // already known to exist
1592 }
1593
1594 $table = $this->tableName( $table );
1595 $ignoreErrors = true;
1596 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1597
1598 return (bool)$res;
1599 }
1600
1601 public function indexUnique( $table, $index ) {
1602 $indexInfo = $this->indexInfo( $table, $index );
1603
1604 if ( !$indexInfo ) {
1605 return null;
1606 }
1607
1608 return !$indexInfo[0]->Non_unique;
1609 }
1610
1611 /**
1612 * Helper for Database::insert().
1613 *
1614 * @param array $options
1615 * @return string
1616 */
1617 protected function makeInsertOptions( $options ) {
1618 return implode( ' ', $options );
1619 }
1620
1621 public function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
1622 # No rows to insert, easy just return now
1623 if ( !count( $a ) ) {
1624 return true;
1625 }
1626
1627 $table = $this->tableName( $table );
1628
1629 if ( !is_array( $options ) ) {
1630 $options = [ $options ];
1631 }
1632
1633 $fh = null;
1634 if ( isset( $options['fileHandle'] ) ) {
1635 $fh = $options['fileHandle'];
1636 }
1637 $options = $this->makeInsertOptions( $options );
1638
1639 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1640 $multi = true;
1641 $keys = array_keys( $a[0] );
1642 } else {
1643 $multi = false;
1644 $keys = array_keys( $a );
1645 }
1646
1647 $sql = 'INSERT ' . $options .
1648 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1649
1650 if ( $multi ) {
1651 $first = true;
1652 foreach ( $a as $row ) {
1653 if ( $first ) {
1654 $first = false;
1655 } else {
1656 $sql .= ',';
1657 }
1658 $sql .= '(' . $this->makeList( $row ) . ')';
1659 }
1660 } else {
1661 $sql .= '(' . $this->makeList( $a ) . ')';
1662 }
1663
1664 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1665 return false;
1666 } elseif ( $fh !== null ) {
1667 return true;
1668 }
1669
1670 return (bool)$this->query( $sql, $fname );
1671 }
1672
1673 /**
1674 * Make UPDATE options array for Database::makeUpdateOptions
1675 *
1676 * @param array $options
1677 * @return array
1678 */
1679 protected function makeUpdateOptionsArray( $options ) {
1680 if ( !is_array( $options ) ) {
1681 $options = [ $options ];
1682 }
1683
1684 $opts = [];
1685
1686 if ( in_array( 'IGNORE', $options ) ) {
1687 $opts[] = 'IGNORE';
1688 }
1689
1690 return $opts;
1691 }
1692
1693 /**
1694 * Make UPDATE options for the Database::update function
1695 *
1696 * @param array $options The options passed to Database::update
1697 * @return string
1698 */
1699 protected function makeUpdateOptions( $options ) {
1700 $opts = $this->makeUpdateOptionsArray( $options );
1701
1702 return implode( ' ', $opts );
1703 }
1704
1705 public function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
1706 $table = $this->tableName( $table );
1707 $opts = $this->makeUpdateOptions( $options );
1708 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self::LIST_SET );
1709
1710 if ( $conds !== [] && $conds !== '*' ) {
1711 $sql .= " WHERE " . $this->makeList( $conds, self::LIST_AND );
1712 }
1713
1714 return (bool)$this->query( $sql, $fname );
1715 }
1716
1717 public function makeList( $a, $mode = self::LIST_COMMA ) {
1718 if ( !is_array( $a ) ) {
1719 throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
1720 }
1721
1722 $first = true;
1723 $list = '';
1724
1725 foreach ( $a as $field => $value ) {
1726 if ( !$first ) {
1727 if ( $mode == self::LIST_AND ) {
1728 $list .= ' AND ';
1729 } elseif ( $mode == self::LIST_OR ) {
1730 $list .= ' OR ';
1731 } else {
1732 $list .= ',';
1733 }
1734 } else {
1735 $first = false;
1736 }
1737
1738 if ( ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_numeric( $field ) ) {
1739 $list .= "($value)";
1740 } elseif ( $mode == self::LIST_SET && is_numeric( $field ) ) {
1741 $list .= "$value";
1742 } elseif (
1743 ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_array( $value )
1744 ) {
1745 // Remove null from array to be handled separately if found
1746 $includeNull = false;
1747 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1748 $includeNull = true;
1749 unset( $value[$nullKey] );
1750 }
1751 if ( count( $value ) == 0 && !$includeNull ) {
1752 throw new InvalidArgumentException(
1753 __METHOD__ . ": empty input for field $field" );
1754 } elseif ( count( $value ) == 0 ) {
1755 // only check if $field is null
1756 $list .= "$field IS NULL";
1757 } else {
1758 // IN clause contains at least one valid element
1759 if ( $includeNull ) {
1760 // Group subconditions to ensure correct precedence
1761 $list .= '(';
1762 }
1763 if ( count( $value ) == 1 ) {
1764 // Special-case single values, as IN isn't terribly efficient
1765 // Don't necessarily assume the single key is 0; we don't
1766 // enforce linear numeric ordering on other arrays here.
1767 $value = array_values( $value )[0];
1768 $list .= $field . " = " . $this->addQuotes( $value );
1769 } else {
1770 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1771 }
1772 // if null present in array, append IS NULL
1773 if ( $includeNull ) {
1774 $list .= " OR $field IS NULL)";
1775 }
1776 }
1777 } elseif ( $value === null ) {
1778 if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
1779 $list .= "$field IS ";
1780 } elseif ( $mode == self::LIST_SET ) {
1781 $list .= "$field = ";
1782 }
1783 $list .= 'NULL';
1784 } else {
1785 if (
1786 $mode == self::LIST_AND || $mode == self::LIST_OR || $mode == self::LIST_SET
1787 ) {
1788 $list .= "$field = ";
1789 }
1790 $list .= $mode == self::LIST_NAMES ? $value : $this->addQuotes( $value );
1791 }
1792 }
1793
1794 return $list;
1795 }
1796
1797 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1798 $conds = [];
1799
1800 foreach ( $data as $base => $sub ) {
1801 if ( count( $sub ) ) {
1802 $conds[] = $this->makeList(
1803 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1804 self::LIST_AND );
1805 }
1806 }
1807
1808 if ( $conds ) {
1809 return $this->makeList( $conds, self::LIST_OR );
1810 } else {
1811 // Nothing to search for...
1812 return false;
1813 }
1814 }
1815
1816 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1817 return $valuename;
1818 }
1819
1820 public function bitNot( $field ) {
1821 return "(~$field)";
1822 }
1823
1824 public function bitAnd( $fieldLeft, $fieldRight ) {
1825 return "($fieldLeft & $fieldRight)";
1826 }
1827
1828 public function bitOr( $fieldLeft, $fieldRight ) {
1829 return "($fieldLeft | $fieldRight)";
1830 }
1831
1832 public function buildConcat( $stringList ) {
1833 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1834 }
1835
1836 public function buildGroupConcatField(
1837 $delim, $table, $field, $conds = '', $join_conds = []
1838 ) {
1839 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1840
1841 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1842 }
1843
1844 public function buildStringCast( $field ) {
1845 return $field;
1846 }
1847
1848 public function databasesAreIndependent() {
1849 return false;
1850 }
1851
1852 public function selectDB( $db ) {
1853 # Stub. Shouldn't cause serious problems if it's not overridden, but
1854 # if your database engine supports a concept similar to MySQL's
1855 # databases you may as well.
1856 $this->dbName = $db;
1857
1858 return true;
1859 }
1860
1861 public function getDBname() {
1862 return $this->dbName;
1863 }
1864
1865 public function getServer() {
1866 return $this->server;
1867 }
1868
1869 public function tableName( $name, $format = 'quoted' ) {
1870 # Skip the entire process when we have a string quoted on both ends.
1871 # Note that we check the end so that we will still quote any use of
1872 # use of `database`.table. But won't break things if someone wants
1873 # to query a database table with a dot in the name.
1874 if ( $this->isQuotedIdentifier( $name ) ) {
1875 return $name;
1876 }
1877
1878 # Lets test for any bits of text that should never show up in a table
1879 # name. Basically anything like JOIN or ON which are actually part of
1880 # SQL queries, but may end up inside of the table value to combine
1881 # sql. Such as how the API is doing.
1882 # Note that we use a whitespace test rather than a \b test to avoid
1883 # any remote case where a word like on may be inside of a table name
1884 # surrounded by symbols which may be considered word breaks.
1885 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1886 return $name;
1887 }
1888
1889 # Split database and table into proper variables.
1890 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
1891
1892 # Quote $table and apply the prefix if not quoted.
1893 # $tableName might be empty if this is called from Database::replaceVars()
1894 $tableName = "{$prefix}{$table}";
1895 if ( $format === 'quoted'
1896 && !$this->isQuotedIdentifier( $tableName )
1897 && $tableName !== ''
1898 ) {
1899 $tableName = $this->addIdentifierQuotes( $tableName );
1900 }
1901
1902 # Quote $schema and $database and merge them with the table name if needed
1903 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1904 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1905
1906 return $tableName;
1907 }
1908
1909 /**
1910 * Get the table components needed for a query given the currently selected database
1911 *
1912 * @param string $name Table name in the form of db.schema.table, db.table, or table
1913 * @return array (DB name or "" for default, schema name, table prefix, table name)
1914 */
1915 protected function qualifiedTableComponents( $name ) {
1916 # We reverse the explode so that database.table and table both output the correct table.
1917 $dbDetails = explode( '.', $name, 3 );
1918 if ( count( $dbDetails ) == 3 ) {
1919 list( $database, $schema, $table ) = $dbDetails;
1920 # We don't want any prefix added in this case
1921 $prefix = '';
1922 } elseif ( count( $dbDetails ) == 2 ) {
1923 list( $database, $table ) = $dbDetails;
1924 # We don't want any prefix added in this case
1925 $prefix = '';
1926 # In dbs that support it, $database may actually be the schema
1927 # but that doesn't affect any of the functionality here
1928 $schema = '';
1929 } else {
1930 list( $table ) = $dbDetails;
1931 if ( isset( $this->tableAliases[$table] ) ) {
1932 $database = $this->tableAliases[$table]['dbname'];
1933 $schema = is_string( $this->tableAliases[$table]['schema'] )
1934 ? $this->tableAliases[$table]['schema']
1935 : $this->schema;
1936 $prefix = is_string( $this->tableAliases[$table]['prefix'] )
1937 ? $this->tableAliases[$table]['prefix']
1938 : $this->tablePrefix;
1939 } else {
1940 $database = '';
1941 $schema = $this->schema; # Default schema
1942 $prefix = $this->tablePrefix; # Default prefix
1943 }
1944 }
1945
1946 return [ $database, $schema, $prefix, $table ];
1947 }
1948
1949 /**
1950 * @param string|null $namespace Database or schema
1951 * @param string $relation Name of table, view, sequence, etc...
1952 * @param string $format One of (raw, quoted)
1953 * @return string Relation name with quoted and merged $namespace as needed
1954 */
1955 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
1956 if ( strlen( $namespace ) ) {
1957 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
1958 $namespace = $this->addIdentifierQuotes( $namespace );
1959 }
1960 $relation = $namespace . '.' . $relation;
1961 }
1962
1963 return $relation;
1964 }
1965
1966 public function tableNames() {
1967 $inArray = func_get_args();
1968 $retVal = [];
1969
1970 foreach ( $inArray as $name ) {
1971 $retVal[$name] = $this->tableName( $name );
1972 }
1973
1974 return $retVal;
1975 }
1976
1977 public function tableNamesN() {
1978 $inArray = func_get_args();
1979 $retVal = [];
1980
1981 foreach ( $inArray as $name ) {
1982 $retVal[] = $this->tableName( $name );
1983 }
1984
1985 return $retVal;
1986 }
1987
1988 /**
1989 * Get an aliased table name
1990 * e.g. tableName AS newTableName
1991 *
1992 * @param string $name Table name, see tableName()
1993 * @param string|bool $alias Alias (optional)
1994 * @return string SQL name for aliased table. Will not alias a table to its own name
1995 */
1996 protected function tableNameWithAlias( $name, $alias = false ) {
1997 if ( !$alias || $alias == $name ) {
1998 return $this->tableName( $name );
1999 } else {
2000 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2001 }
2002 }
2003
2004 /**
2005 * Gets an array of aliased table names
2006 *
2007 * @param array $tables [ [alias] => table ]
2008 * @return string[] See tableNameWithAlias()
2009 */
2010 protected function tableNamesWithAlias( $tables ) {
2011 $retval = [];
2012 foreach ( $tables as $alias => $table ) {
2013 if ( is_numeric( $alias ) ) {
2014 $alias = $table;
2015 }
2016 $retval[] = $this->tableNameWithAlias( $table, $alias );
2017 }
2018
2019 return $retval;
2020 }
2021
2022 /**
2023 * Get an aliased field name
2024 * e.g. fieldName AS newFieldName
2025 *
2026 * @param string $name Field name
2027 * @param string|bool $alias Alias (optional)
2028 * @return string SQL name for aliased field. Will not alias a field to its own name
2029 */
2030 protected function fieldNameWithAlias( $name, $alias = false ) {
2031 if ( !$alias || (string)$alias === (string)$name ) {
2032 return $name;
2033 } else {
2034 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2035 }
2036 }
2037
2038 /**
2039 * Gets an array of aliased field names
2040 *
2041 * @param array $fields [ [alias] => field ]
2042 * @return string[] See fieldNameWithAlias()
2043 */
2044 protected function fieldNamesWithAlias( $fields ) {
2045 $retval = [];
2046 foreach ( $fields as $alias => $field ) {
2047 if ( is_numeric( $alias ) ) {
2048 $alias = $field;
2049 }
2050 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2051 }
2052
2053 return $retval;
2054 }
2055
2056 /**
2057 * Get the aliased table name clause for a FROM clause
2058 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2059 *
2060 * @param array $tables ( [alias] => table )
2061 * @param array $use_index Same as for select()
2062 * @param array $ignore_index Same as for select()
2063 * @param array $join_conds Same as for select()
2064 * @return string
2065 */
2066 protected function tableNamesWithIndexClauseOrJOIN(
2067 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2068 ) {
2069 $ret = [];
2070 $retJOIN = [];
2071 $use_index = (array)$use_index;
2072 $ignore_index = (array)$ignore_index;
2073 $join_conds = (array)$join_conds;
2074
2075 foreach ( $tables as $alias => $table ) {
2076 if ( !is_string( $alias ) ) {
2077 // No alias? Set it equal to the table name
2078 $alias = $table;
2079 }
2080
2081 if ( is_array( $table ) ) {
2082 // A parenthesized group
2083 if ( count( $table ) > 1 ) {
2084 $joinedTable = '('
2085 . $this->tableNamesWithIndexClauseOrJOIN( $table, $use_index, $ignore_index, $join_conds )
2086 . ')';
2087 } else {
2088 // Degenerate case
2089 $innerTable = reset( $table );
2090 $innerAlias = key( $table );
2091 $joinedTable = $this->tableNameWithAlias(
2092 $innerTable,
2093 is_string( $innerAlias ) ? $innerAlias : $innerTable
2094 );
2095 }
2096 } else {
2097 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2098 }
2099
2100 // Is there a JOIN clause for this table?
2101 if ( isset( $join_conds[$alias] ) ) {
2102 list( $joinType, $conds ) = $join_conds[$alias];
2103 $tableClause = $joinType;
2104 $tableClause .= ' ' . $joinedTable;
2105 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2106 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2107 if ( $use != '' ) {
2108 $tableClause .= ' ' . $use;
2109 }
2110 }
2111 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2112 $ignore = $this->ignoreIndexClause(
2113 implode( ',', (array)$ignore_index[$alias] ) );
2114 if ( $ignore != '' ) {
2115 $tableClause .= ' ' . $ignore;
2116 }
2117 }
2118 $on = $this->makeList( (array)$conds, self::LIST_AND );
2119 if ( $on != '' ) {
2120 $tableClause .= ' ON (' . $on . ')';
2121 }
2122
2123 $retJOIN[] = $tableClause;
2124 } elseif ( isset( $use_index[$alias] ) ) {
2125 // Is there an INDEX clause for this table?
2126 $tableClause = $joinedTable;
2127 $tableClause .= ' ' . $this->useIndexClause(
2128 implode( ',', (array)$use_index[$alias] )
2129 );
2130
2131 $ret[] = $tableClause;
2132 } elseif ( isset( $ignore_index[$alias] ) ) {
2133 // Is there an INDEX clause for this table?
2134 $tableClause = $joinedTable;
2135 $tableClause .= ' ' . $this->ignoreIndexClause(
2136 implode( ',', (array)$ignore_index[$alias] )
2137 );
2138
2139 $ret[] = $tableClause;
2140 } else {
2141 $tableClause = $joinedTable;
2142
2143 $ret[] = $tableClause;
2144 }
2145 }
2146
2147 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2148 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
2149 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
2150
2151 // Compile our final table clause
2152 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2153 }
2154
2155 /**
2156 * Allows for index remapping in queries where this is not consistent across DBMS
2157 *
2158 * @param string $index
2159 * @return string
2160 */
2161 protected function indexName( $index ) {
2162 return $index;
2163 }
2164
2165 public function addQuotes( $s ) {
2166 if ( $s instanceof Blob ) {
2167 $s = $s->fetch();
2168 }
2169 if ( $s === null ) {
2170 return 'NULL';
2171 } elseif ( is_bool( $s ) ) {
2172 return (int)$s;
2173 } else {
2174 # This will also quote numeric values. This should be harmless,
2175 # and protects against weird problems that occur when they really
2176 # _are_ strings such as article titles and string->number->string
2177 # conversion is not 1:1.
2178 return "'" . $this->strencode( $s ) . "'";
2179 }
2180 }
2181
2182 /**
2183 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2184 * MySQL uses `backticks` while basically everything else uses double quotes.
2185 * Since MySQL is the odd one out here the double quotes are our generic
2186 * and we implement backticks in DatabaseMysqlBase.
2187 *
2188 * @param string $s
2189 * @return string
2190 */
2191 public function addIdentifierQuotes( $s ) {
2192 return '"' . str_replace( '"', '""', $s ) . '"';
2193 }
2194
2195 /**
2196 * Returns if the given identifier looks quoted or not according to
2197 * the database convention for quoting identifiers .
2198 *
2199 * @note Do not use this to determine if untrusted input is safe.
2200 * A malicious user can trick this function.
2201 * @param string $name
2202 * @return bool
2203 */
2204 public function isQuotedIdentifier( $name ) {
2205 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2206 }
2207
2208 /**
2209 * @param string $s
2210 * @param string $escapeChar
2211 * @return string
2212 */
2213 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2214 return str_replace( [ $escapeChar, '%', '_' ],
2215 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2216 $s );
2217 }
2218
2219 public function buildLike() {
2220 $params = func_get_args();
2221
2222 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2223 $params = $params[0];
2224 }
2225
2226 $s = '';
2227
2228 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2229 // may escape backslashes, creating problems of double escaping. The `
2230 // character has good cross-DBMS compatibility, avoiding special operators
2231 // in MS SQL like ^ and %
2232 $escapeChar = '`';
2233
2234 foreach ( $params as $value ) {
2235 if ( $value instanceof LikeMatch ) {
2236 $s .= $value->toString();
2237 } else {
2238 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2239 }
2240 }
2241
2242 return ' LIKE ' . $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2243 }
2244
2245 public function anyChar() {
2246 return new LikeMatch( '_' );
2247 }
2248
2249 public function anyString() {
2250 return new LikeMatch( '%' );
2251 }
2252
2253 public function nextSequenceValue( $seqName ) {
2254 return null;
2255 }
2256
2257 /**
2258 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2259 * is only needed because a) MySQL must be as efficient as possible due to
2260 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2261 * which index to pick. Anyway, other databases might have different
2262 * indexes on a given table. So don't bother overriding this unless you're
2263 * MySQL.
2264 * @param string $index
2265 * @return string
2266 */
2267 public function useIndexClause( $index ) {
2268 return '';
2269 }
2270
2271 /**
2272 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2273 * is only needed because a) MySQL must be as efficient as possible due to
2274 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2275 * which index to pick. Anyway, other databases might have different
2276 * indexes on a given table. So don't bother overriding this unless you're
2277 * MySQL.
2278 * @param string $index
2279 * @return string
2280 */
2281 public function ignoreIndexClause( $index ) {
2282 return '';
2283 }
2284
2285 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2286 if ( count( $rows ) == 0 ) {
2287 return;
2288 }
2289
2290 // Single row case
2291 if ( !is_array( reset( $rows ) ) ) {
2292 $rows = [ $rows ];
2293 }
2294
2295 $useTrx = !$this->trxLevel;
2296 if ( $useTrx ) {
2297 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2298 }
2299 try {
2300 $affectedRowCount = 0;
2301 foreach ( $rows as $row ) {
2302 // Delete rows which collide with this one
2303 $indexWhereClauses = [];
2304 foreach ( $uniqueIndexes as $index ) {
2305 $indexColumns = (array)$index;
2306 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2307 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2308 throw new DBUnexpectedError(
2309 $this,
2310 'New record does not provide all values for unique key (' .
2311 implode( ', ', $indexColumns ) . ')'
2312 );
2313 } elseif ( in_array( null, $indexRowValues, true ) ) {
2314 throw new DBUnexpectedError(
2315 $this,
2316 'New record has a null value for unique key (' .
2317 implode( ', ', $indexColumns ) . ')'
2318 );
2319 }
2320 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND );
2321 }
2322
2323 if ( $indexWhereClauses ) {
2324 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR ), $fname );
2325 $affectedRowCount += $this->affectedRows();
2326 }
2327
2328 // Now insert the row
2329 $this->insert( $table, $row, $fname );
2330 $affectedRowCount += $this->affectedRows();
2331 }
2332 } catch ( Exception $e ) {
2333 if ( $useTrx ) {
2334 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2335 }
2336 throw $e;
2337 }
2338 if ( $useTrx ) {
2339 $this->commit( $fname, self::FLUSHING_INTERNAL );
2340 }
2341
2342 $this->affectedRowCount = $affectedRowCount;
2343 }
2344
2345 /**
2346 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2347 * statement.
2348 *
2349 * @param string $table Table name
2350 * @param array|string $rows Row(s) to insert
2351 * @param string $fname Caller function name
2352 *
2353 * @return ResultWrapper
2354 */
2355 protected function nativeReplace( $table, $rows, $fname ) {
2356 $table = $this->tableName( $table );
2357
2358 # Single row case
2359 if ( !is_array( reset( $rows ) ) ) {
2360 $rows = [ $rows ];
2361 }
2362
2363 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2364 $first = true;
2365
2366 foreach ( $rows as $row ) {
2367 if ( $first ) {
2368 $first = false;
2369 } else {
2370 $sql .= ',';
2371 }
2372
2373 $sql .= '(' . $this->makeList( $row ) . ')';
2374 }
2375
2376 return $this->query( $sql, $fname );
2377 }
2378
2379 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2380 $fname = __METHOD__
2381 ) {
2382 if ( !count( $rows ) ) {
2383 return true; // nothing to do
2384 }
2385
2386 if ( !is_array( reset( $rows ) ) ) {
2387 $rows = [ $rows ];
2388 }
2389
2390 if ( count( $uniqueIndexes ) ) {
2391 $clauses = []; // list WHERE clauses that each identify a single row
2392 foreach ( $rows as $row ) {
2393 foreach ( $uniqueIndexes as $index ) {
2394 $index = is_array( $index ) ? $index : [ $index ]; // columns
2395 $rowKey = []; // unique key to this row
2396 foreach ( $index as $column ) {
2397 $rowKey[$column] = $row[$column];
2398 }
2399 $clauses[] = $this->makeList( $rowKey, self::LIST_AND );
2400 }
2401 }
2402 $where = [ $this->makeList( $clauses, self::LIST_OR ) ];
2403 } else {
2404 $where = false;
2405 }
2406
2407 $affectedRowCount = 0;
2408 $useTrx = !$this->trxLevel;
2409 if ( $useTrx ) {
2410 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2411 }
2412 try {
2413 # Update any existing conflicting row(s)
2414 if ( $where !== false ) {
2415 $ok = $this->update( $table, $set, $where, $fname );
2416 $affectedRowCount += $this->affectedRows();
2417 } else {
2418 $ok = true;
2419 }
2420 # Now insert any non-conflicting row(s)
2421 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2422 $affectedRowCount += $this->affectedRows();
2423 } catch ( Exception $e ) {
2424 if ( $useTrx ) {
2425 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2426 }
2427 throw $e;
2428 }
2429 if ( $useTrx ) {
2430 $this->commit( $fname, self::FLUSHING_INTERNAL );
2431 }
2432 $this->affectedRowCount = $affectedRowCount;
2433
2434 return $ok;
2435 }
2436
2437 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2438 $fname = __METHOD__
2439 ) {
2440 if ( !$conds ) {
2441 throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
2442 }
2443
2444 $delTable = $this->tableName( $delTable );
2445 $joinTable = $this->tableName( $joinTable );
2446 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2447 if ( $conds != '*' ) {
2448 $sql .= 'WHERE ' . $this->makeList( $conds, self::LIST_AND );
2449 }
2450 $sql .= ')';
2451
2452 $this->query( $sql, $fname );
2453 }
2454
2455 public function textFieldSize( $table, $field ) {
2456 $table = $this->tableName( $table );
2457 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2458 $res = $this->query( $sql, __METHOD__ );
2459 $row = $this->fetchObject( $res );
2460
2461 $m = [];
2462
2463 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2464 $size = $m[1];
2465 } else {
2466 $size = -1;
2467 }
2468
2469 return $size;
2470 }
2471
2472 public function delete( $table, $conds, $fname = __METHOD__ ) {
2473 if ( !$conds ) {
2474 throw new DBUnexpectedError( $this, __METHOD__ . ' called with no conditions' );
2475 }
2476
2477 $table = $this->tableName( $table );
2478 $sql = "DELETE FROM $table";
2479
2480 if ( $conds != '*' ) {
2481 if ( is_array( $conds ) ) {
2482 $conds = $this->makeList( $conds, self::LIST_AND );
2483 }
2484 $sql .= ' WHERE ' . $conds;
2485 }
2486
2487 return $this->query( $sql, $fname );
2488 }
2489
2490 public function insertSelect(
2491 $destTable, $srcTable, $varMap, $conds,
2492 $fname = __METHOD__, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2493 ) {
2494 if ( $this->cliMode ) {
2495 // For massive migrations with downtime, we don't want to select everything
2496 // into memory and OOM, so do all this native on the server side if possible.
2497 return $this->nativeInsertSelect(
2498 $destTable,
2499 $srcTable,
2500 $varMap,
2501 $conds,
2502 $fname,
2503 $insertOptions,
2504 $selectOptions,
2505 $selectJoinConds
2506 );
2507 }
2508
2509 return $this->nonNativeInsertSelect(
2510 $destTable,
2511 $srcTable,
2512 $varMap,
2513 $conds,
2514 $fname,
2515 $insertOptions,
2516 $selectOptions,
2517 $selectJoinConds
2518 );
2519 }
2520
2521 /**
2522 * Implementation of insertSelect() based on select() and insert()
2523 *
2524 * @see IDatabase::insertSelect()
2525 * @since 1.30
2526 * @param string $destTable
2527 * @param string|array $srcTable
2528 * @param array $varMap
2529 * @param array $conds
2530 * @param string $fname
2531 * @param array $insertOptions
2532 * @param array $selectOptions
2533 * @param array $selectJoinConds
2534 * @return bool
2535 */
2536 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2537 $fname = __METHOD__,
2538 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2539 ) {
2540 $insertOptions = array_diff( (array)$insertOptions, [ 'NO_AUTO_COLUMNS' ] );
2541
2542 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2543 // on only the master (without needing row-based-replication). It also makes it easy to
2544 // know how big the INSERT is going to be.
2545 $fields = [];
2546 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2547 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2548 }
2549 $selectOptions[] = 'FOR UPDATE';
2550 $res = $this->select(
2551 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2552 );
2553 if ( !$res ) {
2554 return false;
2555 }
2556
2557 try {
2558 $affectedRowCount = 0;
2559 $this->startAtomic( $fname );
2560 $rows = [];
2561 $ok = true;
2562 foreach ( $res as $row ) {
2563 $rows[] = (array)$row;
2564
2565 // Avoid inserts that are too huge
2566 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize ) {
2567 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2568 if ( !$ok ) {
2569 break;
2570 }
2571 $affectedRowCount += $this->affectedRows();
2572 $rows = [];
2573 }
2574 }
2575 if ( $rows && $ok ) {
2576 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2577 if ( $ok ) {
2578 $affectedRowCount += $this->affectedRows();
2579 }
2580 }
2581 if ( $ok ) {
2582 $this->endAtomic( $fname );
2583 $this->affectedRowCount = $affectedRowCount;
2584 } else {
2585 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2586 $this->affectedRowCount = 0;
2587 }
2588 return $ok;
2589 } catch ( Exception $e ) {
2590 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2591 $this->affectedRowCount = 0;
2592 throw $e;
2593 }
2594 }
2595
2596 /**
2597 * Native server-side implementation of insertSelect() for situations where
2598 * we don't want to select everything into memory
2599 *
2600 * @see IDatabase::insertSelect()
2601 * @param string $destTable
2602 * @param string|array $srcTable
2603 * @param array $varMap
2604 * @param array $conds
2605 * @param string $fname
2606 * @param array $insertOptions
2607 * @param array $selectOptions
2608 * @param array $selectJoinConds
2609 * @return bool
2610 */
2611 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2612 $fname = __METHOD__,
2613 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2614 ) {
2615 $destTable = $this->tableName( $destTable );
2616
2617 if ( !is_array( $insertOptions ) ) {
2618 $insertOptions = [ $insertOptions ];
2619 }
2620 $insertOptions = array_diff( (array)$insertOptions, [ 'NO_AUTO_COLUMNS' ] );
2621
2622 $insertOptions = $this->makeInsertOptions( $insertOptions );
2623
2624 $selectSql = $this->selectSQLText(
2625 $srcTable,
2626 array_values( $varMap ),
2627 $conds,
2628 $fname,
2629 $selectOptions,
2630 $selectJoinConds
2631 );
2632
2633 $sql = "INSERT $insertOptions" .
2634 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2635 $selectSql;
2636
2637 return $this->query( $sql, $fname );
2638 }
2639
2640 /**
2641 * Construct a LIMIT query with optional offset. This is used for query
2642 * pages. The SQL should be adjusted so that only the first $limit rows
2643 * are returned. If $offset is provided as well, then the first $offset
2644 * rows should be discarded, and the next $limit rows should be returned.
2645 * If the result of the query is not ordered, then the rows to be returned
2646 * are theoretically arbitrary.
2647 *
2648 * $sql is expected to be a SELECT, if that makes a difference.
2649 *
2650 * The version provided by default works in MySQL and SQLite. It will very
2651 * likely need to be overridden for most other DBMSes.
2652 *
2653 * @param string $sql SQL query we will append the limit too
2654 * @param int $limit The SQL limit
2655 * @param int|bool $offset The SQL offset (default false)
2656 * @throws DBUnexpectedError
2657 * @return string
2658 */
2659 public function limitResult( $sql, $limit, $offset = false ) {
2660 if ( !is_numeric( $limit ) ) {
2661 throw new DBUnexpectedError( $this,
2662 "Invalid non-numeric limit passed to limitResult()\n" );
2663 }
2664
2665 return "$sql LIMIT "
2666 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2667 . "{$limit} ";
2668 }
2669
2670 public function unionSupportsOrderAndLimit() {
2671 return true; // True for almost every DB supported
2672 }
2673
2674 public function unionQueries( $sqls, $all ) {
2675 $glue = $all ? ') UNION ALL (' : ') UNION (';
2676
2677 return '(' . implode( $glue, $sqls ) . ')';
2678 }
2679
2680 public function unionConditionPermutations(
2681 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__,
2682 $options = [], $join_conds = []
2683 ) {
2684 // First, build the Cartesian product of $permute_conds
2685 $conds = [ [] ];
2686 foreach ( $permute_conds as $field => $values ) {
2687 if ( !$values ) {
2688 // Skip empty $values
2689 continue;
2690 }
2691 $values = array_unique( $values ); // For sanity
2692 $newConds = [];
2693 foreach ( $conds as $cond ) {
2694 foreach ( $values as $value ) {
2695 $cond[$field] = $value;
2696 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
2697 }
2698 }
2699 $conds = $newConds;
2700 }
2701
2702 $extra_conds = $extra_conds === '' ? [] : (array)$extra_conds;
2703
2704 // If there's just one condition and no subordering, hand off to
2705 // selectSQLText directly.
2706 if ( count( $conds ) === 1 &&
2707 ( !isset( $options['INNER ORDER BY'] ) || !$this->unionSupportsOrderAndLimit() )
2708 ) {
2709 return $this->selectSQLText(
2710 $table, $vars, $conds[0] + $extra_conds, $fname, $options, $join_conds
2711 );
2712 }
2713
2714 // Otherwise, we need to pull out the order and limit to apply after
2715 // the union. Then build the SQL queries for each set of conditions in
2716 // $conds. Then union them together (using UNION ALL, because the
2717 // product *should* already be distinct).
2718 $orderBy = $this->makeOrderBy( $options );
2719 $limit = isset( $options['LIMIT'] ) ? $options['LIMIT'] : null;
2720 $offset = isset( $options['OFFSET'] ) ? $options['OFFSET'] : false;
2721 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
2722 if ( !$this->unionSupportsOrderAndLimit() ) {
2723 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
2724 } else {
2725 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
2726 $options['ORDER BY'] = $options['INNER ORDER BY'];
2727 }
2728 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
2729 // We need to increase the limit by the offset rather than
2730 // using the offset directly, otherwise it'll skip incorrectly
2731 // in the subqueries.
2732 $options['LIMIT'] = $limit + $offset;
2733 unset( $options['OFFSET'] );
2734 }
2735 }
2736
2737 $sqls = [];
2738 foreach ( $conds as $cond ) {
2739 $sqls[] = $this->selectSQLText(
2740 $table, $vars, $cond + $extra_conds, $fname, $options, $join_conds
2741 );
2742 }
2743 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
2744 if ( $limit !== null ) {
2745 $sql = $this->limitResult( $sql, $limit, $offset );
2746 }
2747
2748 return $sql;
2749 }
2750
2751 public function conditional( $cond, $trueVal, $falseVal ) {
2752 if ( is_array( $cond ) ) {
2753 $cond = $this->makeList( $cond, self::LIST_AND );
2754 }
2755
2756 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2757 }
2758
2759 public function strreplace( $orig, $old, $new ) {
2760 return "REPLACE({$orig}, {$old}, {$new})";
2761 }
2762
2763 public function getServerUptime() {
2764 return 0;
2765 }
2766
2767 public function wasDeadlock() {
2768 return false;
2769 }
2770
2771 public function wasLockTimeout() {
2772 return false;
2773 }
2774
2775 public function wasErrorReissuable() {
2776 return false;
2777 }
2778
2779 public function wasReadOnlyError() {
2780 return false;
2781 }
2782
2783 /**
2784 * Do not use this method outside of Database/DBError classes
2785 *
2786 * @param int|string $errno
2787 * @return bool Whether the given query error was a connection drop
2788 */
2789 public function wasConnectionError( $errno ) {
2790 return false;
2791 }
2792
2793 public function deadlockLoop() {
2794 $args = func_get_args();
2795 $function = array_shift( $args );
2796 $tries = self::DEADLOCK_TRIES;
2797
2798 $this->begin( __METHOD__ );
2799
2800 $retVal = null;
2801 /** @var Exception $e */
2802 $e = null;
2803 do {
2804 try {
2805 $retVal = call_user_func_array( $function, $args );
2806 break;
2807 } catch ( DBQueryError $e ) {
2808 if ( $this->wasDeadlock() ) {
2809 // Retry after a randomized delay
2810