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