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