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