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