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