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