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