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