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