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