c3e36dabda45b4b14a2c777cbefb148ca1b2c16f
[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 public function reportConnectionError( $error = 'Unknown error' ) {
916 $myError = $this->lastError();
917 if ( $myError ) {
918 $error = $myError;
919 }
920
921 # New method
922 throw new DBConnectionError( $this, $error );
923 }
924
925 /**
926 * Run a query and return a DBMS-dependent wrapper (that has all IResultWrapper methods)
927 *
928 * This might return things, such as mysqli_result, that do not formally implement
929 * IResultWrapper, but nonetheless implement all of its methods correctly
930 *
931 * @param string $sql SQL query.
932 * @return IResultWrapper|bool Iterator to feed to fetchObject/fetchRow; false on failure
933 */
934 abstract protected function doQuery( $sql );
935
936 /**
937 * Determine whether a query writes to the DB.
938 * Should return true if unsure.
939 *
940 * @param string $sql
941 * @return bool
942 */
943 protected function isWriteQuery( $sql ) {
944 return !preg_match(
945 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
946 }
947
948 /**
949 * @param string $sql
950 * @return string|null
951 */
952 protected function getQueryVerb( $sql ) {
953 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ? strtoupper( $m[1] ) : null;
954 }
955
956 /**
957 * Determine whether a SQL statement is sensitive to isolation level.
958 * A SQL statement is considered transactable if its result could vary
959 * depending on the transaction isolation level. Operational commands
960 * such as 'SET' and 'SHOW' are not considered to be transactable.
961 *
962 * @param string $sql
963 * @return bool
964 */
965 protected function isTransactableQuery( $sql ) {
966 return !in_array(
967 $this->getQueryVerb( $sql ),
968 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
969 true
970 );
971 }
972
973 /**
974 * @param string $sql A SQL query
975 * @return bool Whether $sql is SQL for TEMPORARY table operation
976 */
977 protected function registerTempTableOperation( $sql ) {
978 if ( preg_match(
979 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
980 $sql,
981 $matches
982 ) ) {
983 $this->sessionTempTables[$matches[1]] = 1;
984
985 return true;
986 } elseif ( preg_match(
987 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
988 $sql,
989 $matches
990 ) ) {
991 $isTemp = isset( $this->sessionTempTables[$matches[1]] );
992 unset( $this->sessionTempTables[$matches[1]] );
993
994 return $isTemp;
995 } elseif ( preg_match(
996 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
997 $sql,
998 $matches
999 ) ) {
1000 return isset( $this->sessionTempTables[$matches[1]] );
1001 } elseif ( preg_match(
1002 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
1003 $sql,
1004 $matches
1005 ) ) {
1006 return isset( $this->sessionTempTables[$matches[1]] );
1007 }
1008
1009 return false;
1010 }
1011
1012 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
1013 $priorWritesPending = $this->writesOrCallbacksPending();
1014 $this->lastQuery = $sql;
1015
1016 $isWrite = $this->isWriteQuery( $sql );
1017 if ( $isWrite ) {
1018 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
1019 } else {
1020 $isNonTempWrite = false;
1021 }
1022
1023 if ( $isWrite ) {
1024 if ( $this->getLBInfo( 'replica' ) === true ) {
1025 throw new DBError(
1026 $this,
1027 'Write operations are not allowed on replica database connections.'
1028 );
1029 }
1030 # In theory, non-persistent writes are allowed in read-only mode, but due to things
1031 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1032 $reason = $this->getReadOnlyReason();
1033 if ( $reason !== false ) {
1034 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
1035 }
1036 # Set a flag indicating that writes have been done
1037 $this->lastWriteTime = microtime( true );
1038 }
1039
1040 # Add trace comment to the begin of the sql string, right after the operator.
1041 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
1042 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
1043
1044 # Start implicit transactions that wrap the request if DBO_TRX is enabled
1045 if ( !$this->trxLevel && $this->getFlag( self::DBO_TRX )
1046 && $this->isTransactableQuery( $sql )
1047 ) {
1048 $this->begin( __METHOD__ . " ($fname)", self::TRANSACTION_INTERNAL );
1049 $this->trxAutomatic = true;
1050 }
1051
1052 # Keep track of whether the transaction has write queries pending
1053 if ( $this->trxLevel && !$this->trxDoneWrites && $isWrite ) {
1054 $this->trxDoneWrites = true;
1055 $this->trxProfiler->transactionWritingIn(
1056 $this->server, $this->dbName, $this->trxShortId );
1057 }
1058
1059 if ( $this->getFlag( self::DBO_DEBUG ) ) {
1060 $this->queryLogger->debug( "{$this->dbName} {$commentedSql}" );
1061 }
1062
1063 # Avoid fatals if close() was called
1064 $this->assertOpen();
1065
1066 # Send the query to the server
1067 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1068
1069 # Try reconnecting if the connection was lost
1070 if ( false === $ret && $this->wasConnectionLoss() ) {
1071 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1072 # Stash the last error values before anything might clear them
1073 $lastError = $this->lastError();
1074 $lastErrno = $this->lastErrno();
1075 # Update state tracking to reflect transaction loss due to disconnection
1076 $this->handleSessionLoss();
1077 if ( $this->reconnect() ) {
1078 $msg = __METHOD__ . ': lost connection to {dbserver}; reconnected';
1079 $params = [ 'dbserver' => $this->getServer() ];
1080 $this->connLogger->warning( $msg, $params );
1081 $this->queryLogger->warning( $msg, $params +
1082 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ] );
1083
1084 if ( $recoverable ) {
1085 # Should be safe to silently retry the query
1086 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1087 } else {
1088 # Callers may catch the exception and continue to use the DB
1089 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
1090 }
1091 } else {
1092 $msg = __METHOD__ . ': lost connection to {dbserver} permanently';
1093 $this->connLogger->error( $msg, [ 'dbserver' => $this->getServer() ] );
1094 }
1095 }
1096
1097 if ( false === $ret ) {
1098 # Deadlocks cause the entire transaction to abort, not just the statement.
1099 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1100 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
1101 if ( $this->wasDeadlock() ) {
1102 if ( $this->explicitTrxActive() || $priorWritesPending ) {
1103 $tempIgnore = false; // not recoverable
1104 }
1105 # Update state tracking to reflect transaction loss
1106 $this->handleSessionLoss();
1107 }
1108
1109 $this->reportQueryError(
1110 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1111 }
1112
1113 $res = $this->resultObject( $ret );
1114
1115 return $res;
1116 }
1117
1118 /**
1119 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1120 *
1121 * @param string $sql Original SQL query
1122 * @param string $commentedSql SQL query with debugging/trace comment
1123 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1124 * @param string $fname Name of the calling function
1125 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1126 * object for a successful read query, or false on failure
1127 */
1128 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1129 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1130 # generalizeSQL() will probably cut down the query to reasonable
1131 # logging size most of the time. The substr is really just a sanity check.
1132 if ( $isMaster ) {
1133 $queryProf = 'query-m: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
1134 } else {
1135 $queryProf = 'query: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
1136 }
1137
1138 # Include query transaction state
1139 $queryProf .= $this->trxShortId ? " [TRX#{$this->trxShortId}]" : "";
1140
1141 $startTime = microtime( true );
1142 if ( $this->profiler ) {
1143 call_user_func( [ $this->profiler, 'profileIn' ], $queryProf );
1144 }
1145 $this->affectedRowCount = null;
1146 $ret = $this->doQuery( $commentedSql );
1147 $this->affectedRowCount = $this->affectedRows();
1148 if ( $this->profiler ) {
1149 call_user_func( [ $this->profiler, 'profileOut' ], $queryProf );
1150 }
1151 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1152
1153 unset( $queryProfSection ); // profile out (if set)
1154
1155 if ( $ret !== false ) {
1156 $this->lastPing = $startTime;
1157 if ( $isWrite && $this->trxLevel ) {
1158 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1159 $this->trxWriteCallers[] = $fname;
1160 }
1161 }
1162
1163 if ( $sql === self::PING_QUERY ) {
1164 $this->rttEstimate = $queryRuntime;
1165 }
1166
1167 $this->trxProfiler->recordQueryCompletion(
1168 $queryProf, $startTime, $isWrite, $this->affectedRows()
1169 );
1170 $this->queryLogger->debug( $sql, [
1171 'method' => $fname,
1172 'master' => $isMaster,
1173 'runtime' => $queryRuntime,
1174 ] );
1175
1176 return $ret;
1177 }
1178
1179 /**
1180 * Update the estimated run-time of a query, not counting large row lock times
1181 *
1182 * LoadBalancer can be set to rollback transactions that will create huge replication
1183 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1184 * queries, like inserting a row can take a long time due to row locking. This method
1185 * uses some simple heuristics to discount those cases.
1186 *
1187 * @param string $sql A SQL write query
1188 * @param float $runtime Total runtime, including RTT
1189 * @param int $affected Affected row count
1190 */
1191 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1192 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1193 $indicativeOfReplicaRuntime = true;
1194 if ( $runtime > self::SLOW_WRITE_SEC ) {
1195 $verb = $this->getQueryVerb( $sql );
1196 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1197 if ( $verb === 'INSERT' ) {
1198 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS;
1199 } elseif ( $verb === 'REPLACE' ) {
1200 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS / 2;
1201 }
1202 }
1203
1204 $this->trxWriteDuration += $runtime;
1205 $this->trxWriteQueryCount += 1;
1206 $this->trxWriteAffectedRows += $affected;
1207 if ( $indicativeOfReplicaRuntime ) {
1208 $this->trxWriteAdjDuration += $runtime;
1209 $this->trxWriteAdjQueryCount += 1;
1210 }
1211 }
1212
1213 /**
1214 * Determine whether or not it is safe to retry queries after a database
1215 * connection is lost
1216 *
1217 * @param string $sql SQL query
1218 * @param bool $priorWritesPending Whether there is a transaction open with
1219 * possible write queries or transaction pre-commit/idle callbacks
1220 * waiting on it to finish.
1221 * @return bool True if it is safe to retry the query, false otherwise
1222 */
1223 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1224 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1225 # Dropped connections also mean that named locks are automatically released.
1226 # Only allow error suppression in autocommit mode or when the lost transaction
1227 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1228 if ( $this->namedLocksHeld ) {
1229 return false; // possible critical section violation
1230 } elseif ( $sql === 'COMMIT' ) {
1231 return !$priorWritesPending; // nothing written anyway? (T127428)
1232 } elseif ( $sql === 'ROLLBACK' ) {
1233 return true; // transaction lost...which is also what was requested :)
1234 } elseif ( $this->explicitTrxActive() ) {
1235 return false; // don't drop atomocity
1236 } elseif ( $priorWritesPending ) {
1237 return false; // prior writes lost from implicit transaction
1238 }
1239
1240 return true;
1241 }
1242
1243 /**
1244 * Clean things up after transaction loss due to disconnection
1245 *
1246 * @return null|Exception
1247 */
1248 private function handleSessionLoss() {
1249 $this->trxLevel = 0;
1250 $this->trxAtomicCounter = 0;
1251 $this->trxIdleCallbacks = []; // T67263; transaction already lost
1252 $this->trxPreCommitCallbacks = []; // T67263; transaction already lost
1253 $this->sessionTempTables = [];
1254 $this->namedLocksHeld = [];
1255
1256 // Note: if callback suppression is set then some *Callbacks arrays are not cleared here
1257 $e = null;
1258 try {
1259 // Handle callbacks in trxEndCallbacks
1260 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
1261 } catch ( Exception $ex ) {
1262 // Already logged; move on...
1263 $e = $e ?: $ex;
1264 }
1265 try {
1266 // Handle callbacks in trxRecurringCallbacks
1267 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
1268 } catch ( Exception $ex ) {
1269 // Already logged; move on...
1270 $e = $e ?: $ex;
1271 }
1272
1273 return $e;
1274 }
1275
1276 /**
1277 * Checks whether the cause of the error is detected to be a timeout.
1278 *
1279 * It returns false by default, and not all engines support detecting this yet.
1280 * If this returns false, it will be treated as a generic query error.
1281 *
1282 * @param string $error Error text
1283 * @param int $errno Error number
1284 * @return bool
1285 */
1286 protected function wasQueryTimeout( $error, $errno ) {
1287 return false;
1288 }
1289
1290 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1291 if ( $this->ignoreErrors() || $tempIgnore ) {
1292 $this->queryLogger->debug( "SQL ERROR (ignored): $error\n" );
1293 } else {
1294 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1295 $this->queryLogger->error(
1296 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1297 $this->getLogContext( [
1298 'method' => __METHOD__,
1299 'errno' => $errno,
1300 'error' => $error,
1301 'sql1line' => $sql1line,
1302 'fname' => $fname,
1303 ] )
1304 );
1305 $this->queryLogger->debug( "SQL ERROR: " . $error . "\n" );
1306 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1307 if ( $wasQueryTimeout ) {
1308 throw new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1309 } else {
1310 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1311 }
1312 }
1313 }
1314
1315 public function freeResult( $res ) {
1316 }
1317
1318 public function selectField(
1319 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1320 ) {
1321 if ( $var === '*' ) { // sanity
1322 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1323 }
1324
1325 if ( !is_array( $options ) ) {
1326 $options = [ $options ];
1327 }
1328
1329 $options['LIMIT'] = 1;
1330
1331 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1332 if ( $res === false || !$this->numRows( $res ) ) {
1333 return false;
1334 }
1335
1336 $row = $this->fetchRow( $res );
1337
1338 if ( $row !== false ) {
1339 return reset( $row );
1340 } else {
1341 return false;
1342 }
1343 }
1344
1345 public function selectFieldValues(
1346 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1347 ) {
1348 if ( $var === '*' ) { // sanity
1349 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1350 } elseif ( !is_string( $var ) ) { // sanity
1351 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1352 }
1353
1354 if ( !is_array( $options ) ) {
1355 $options = [ $options ];
1356 }
1357
1358 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1359 if ( $res === false ) {
1360 return false;
1361 }
1362
1363 $values = [];
1364 foreach ( $res as $row ) {
1365 $values[] = $row->$var;
1366 }
1367
1368 return $values;
1369 }
1370
1371 /**
1372 * Returns an optional USE INDEX clause to go after the table, and a
1373 * string to go at the end of the query.
1374 *
1375 * @param array $options Associative array of options to be turned into
1376 * an SQL query, valid keys are listed in the function.
1377 * @return array
1378 * @see Database::select()
1379 */
1380 protected function makeSelectOptions( $options ) {
1381 $preLimitTail = $postLimitTail = '';
1382 $startOpts = '';
1383
1384 $noKeyOptions = [];
1385
1386 foreach ( $options as $key => $option ) {
1387 if ( is_numeric( $key ) ) {
1388 $noKeyOptions[$option] = true;
1389 }
1390 }
1391
1392 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1393
1394 $preLimitTail .= $this->makeOrderBy( $options );
1395
1396 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1397 $postLimitTail .= ' FOR UPDATE';
1398 }
1399
1400 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1401 $postLimitTail .= ' LOCK IN SHARE MODE';
1402 }
1403
1404 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1405 $startOpts .= 'DISTINCT';
1406 }
1407
1408 # Various MySQL extensions
1409 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1410 $startOpts .= ' /*! STRAIGHT_JOIN */';
1411 }
1412
1413 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1414 $startOpts .= ' HIGH_PRIORITY';
1415 }
1416
1417 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1418 $startOpts .= ' SQL_BIG_RESULT';
1419 }
1420
1421 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1422 $startOpts .= ' SQL_BUFFER_RESULT';
1423 }
1424
1425 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1426 $startOpts .= ' SQL_SMALL_RESULT';
1427 }
1428
1429 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1430 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1431 }
1432
1433 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1434 $startOpts .= ' SQL_CACHE';
1435 }
1436
1437 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1438 $startOpts .= ' SQL_NO_CACHE';
1439 }
1440
1441 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1442 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1443 } else {
1444 $useIndex = '';
1445 }
1446 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1447 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1448 } else {
1449 $ignoreIndex = '';
1450 }
1451
1452 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1453 }
1454
1455 /**
1456 * Returns an optional GROUP BY with an optional HAVING
1457 *
1458 * @param array $options Associative array of options
1459 * @return string
1460 * @see Database::select()
1461 * @since 1.21
1462 */
1463 protected function makeGroupByWithHaving( $options ) {
1464 $sql = '';
1465 if ( isset( $options['GROUP BY'] ) ) {
1466 $gb = is_array( $options['GROUP BY'] )
1467 ? implode( ',', $options['GROUP BY'] )
1468 : $options['GROUP BY'];
1469 $sql .= ' GROUP BY ' . $gb;
1470 }
1471 if ( isset( $options['HAVING'] ) ) {
1472 $having = is_array( $options['HAVING'] )
1473 ? $this->makeList( $options['HAVING'], self::LIST_AND )
1474 : $options['HAVING'];
1475 $sql .= ' HAVING ' . $having;
1476 }
1477
1478 return $sql;
1479 }
1480
1481 /**
1482 * Returns an optional ORDER BY
1483 *
1484 * @param array $options Associative array of options
1485 * @return string
1486 * @see Database::select()
1487 * @since 1.21
1488 */
1489 protected function makeOrderBy( $options ) {
1490 if ( isset( $options['ORDER BY'] ) ) {
1491 $ob = is_array( $options['ORDER BY'] )
1492 ? implode( ',', $options['ORDER BY'] )
1493 : $options['ORDER BY'];
1494
1495 return ' ORDER BY ' . $ob;
1496 }
1497
1498 return '';
1499 }
1500
1501 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1502 $options = [], $join_conds = [] ) {
1503 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1504
1505 return $this->query( $sql, $fname );
1506 }
1507
1508 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1509 $options = [], $join_conds = []
1510 ) {
1511 if ( is_array( $vars ) ) {
1512 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1513 }
1514
1515 $options = (array)$options;
1516 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1517 ? $options['USE INDEX']
1518 : [];
1519 $ignoreIndexes = (
1520 isset( $options['IGNORE INDEX'] ) &&
1521 is_array( $options['IGNORE INDEX'] )
1522 )
1523 ? $options['IGNORE INDEX']
1524 : [];
1525
1526 if ( is_array( $table ) ) {
1527 $from = ' FROM ' .
1528 $this->tableNamesWithIndexClauseOrJOIN(
1529 $table, $useIndexes, $ignoreIndexes, $join_conds );
1530 } elseif ( $table != '' ) {
1531 $from = ' FROM ' .
1532 $this->tableNamesWithIndexClauseOrJOIN(
1533 [ $table ], $useIndexes, $ignoreIndexes, [] );
1534 } else {
1535 $from = '';
1536 }
1537
1538 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1539 $this->makeSelectOptions( $options );
1540
1541 if ( is_array( $conds ) ) {
1542 $conds = $this->makeList( $conds, self::LIST_AND );
1543 }
1544
1545 if ( $conds === null || $conds === false ) {
1546 $this->queryLogger->warning(
1547 __METHOD__
1548 . ' called from '
1549 . $fname
1550 . ' with incorrect parameters: $conds must be a string or an array'
1551 );
1552 $conds = '';
1553 }
1554
1555 if ( $conds === '' ) {
1556 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1557 } elseif ( is_string( $conds ) ) {
1558 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1559 "WHERE $conds $preLimitTail";
1560 } else {
1561 throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
1562 }
1563
1564 if ( isset( $options['LIMIT'] ) ) {
1565 $sql = $this->limitResult( $sql, $options['LIMIT'],
1566 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1567 }
1568 $sql = "$sql $postLimitTail";
1569
1570 if ( isset( $options['EXPLAIN'] ) ) {
1571 $sql = 'EXPLAIN ' . $sql;
1572 }
1573
1574 return $sql;
1575 }
1576
1577 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1578 $options = [], $join_conds = []
1579 ) {
1580 $options = (array)$options;
1581 $options['LIMIT'] = 1;
1582 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1583
1584 if ( $res === false ) {
1585 return false;
1586 }
1587
1588 if ( !$this->numRows( $res ) ) {
1589 return false;
1590 }
1591
1592 $obj = $this->fetchObject( $res );
1593
1594 return $obj;
1595 }
1596
1597 public function estimateRowCount(
1598 $table, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1599 ) {
1600 $conds = $this->normalizeConditions( $conds, $fname );
1601 $column = $this->extractSingleFieldFromList( $var );
1602 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1603 $conds[] = "$column IS NOT NULL";
1604 }
1605
1606 $res = $this->select(
1607 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1608 );
1609 $row = $res ? $this->fetchRow( $res ) : [];
1610
1611 return isset( $row['rowcount'] ) ? (int)$row['rowcount'] : 0;
1612 }
1613
1614 public function selectRowCount(
1615 $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1616 ) {
1617 $conds = $this->normalizeConditions( $conds, $fname );
1618 $column = $this->extractSingleFieldFromList( $var );
1619 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1620 $conds[] = "$column IS NOT NULL";
1621 }
1622
1623 $res = $this->select(
1624 [
1625 'tmp_count' => $this->buildSelectSubquery(
1626 $tables,
1627 '1',
1628 $conds,
1629 $fname,
1630 $options,
1631 $join_conds
1632 )
1633 ],
1634 [ 'rowcount' => 'COUNT(*)' ],
1635 [],
1636 $fname
1637 );
1638 $row = $res ? $this->fetchRow( $res ) : [];
1639
1640 return isset( $row['rowcount'] ) ? (int)$row['rowcount'] : 0;
1641 }
1642
1643 /**
1644 * @param array|string $conds
1645 * @param string $fname
1646 * @return array
1647 */
1648 final protected function normalizeConditions( $conds, $fname ) {
1649 if ( $conds === null || $conds === false ) {
1650 $this->queryLogger->warning(
1651 __METHOD__
1652 . ' called from '
1653 . $fname
1654 . ' with incorrect parameters: $conds must be a string or an array'
1655 );
1656 $conds = '';
1657 }
1658
1659 if ( !is_array( $conds ) ) {
1660 $conds = ( $conds === '' ) ? [] : [ $conds ];
1661 }
1662
1663 return $conds;
1664 }
1665
1666 /**
1667 * @param array|string $var Field parameter in the style of select()
1668 * @return string|null Column name or null; ignores aliases
1669 * @throws DBUnexpectedError Errors out if multiple columns are given
1670 */
1671 final protected function extractSingleFieldFromList( $var ) {
1672 if ( is_array( $var ) ) {
1673 if ( !$var ) {
1674 $column = null;
1675 } elseif ( count( $var ) == 1 ) {
1676 $column = isset( $var[0] ) ? $var[0] : reset( $var );
1677 } else {
1678 throw new DBUnexpectedError( $this, __METHOD__ . ': got multiple columns.' );
1679 }
1680 } else {
1681 $column = $var;
1682 }
1683
1684 return $column;
1685 }
1686
1687 /**
1688 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1689 * It's only slightly flawed. Don't use for anything important.
1690 *
1691 * @param string $sql A SQL Query
1692 *
1693 * @return string
1694 */
1695 protected static function generalizeSQL( $sql ) {
1696 # This does the same as the regexp below would do, but in such a way
1697 # as to avoid crashing php on some large strings.
1698 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1699
1700 $sql = str_replace( "\\\\", '', $sql );
1701 $sql = str_replace( "\\'", '', $sql );
1702 $sql = str_replace( "\\\"", '', $sql );
1703 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1704 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1705
1706 # All newlines, tabs, etc replaced by single space
1707 $sql = preg_replace( '/\s+/', ' ', $sql );
1708
1709 # All numbers => N,
1710 # except the ones surrounded by characters, e.g. l10n
1711 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1712 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1713
1714 return $sql;
1715 }
1716
1717 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1718 $info = $this->fieldInfo( $table, $field );
1719
1720 return (bool)$info;
1721 }
1722
1723 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1724 if ( !$this->tableExists( $table ) ) {
1725 return null;
1726 }
1727
1728 $info = $this->indexInfo( $table, $index, $fname );
1729 if ( is_null( $info ) ) {
1730 return null;
1731 } else {
1732 return $info !== false;
1733 }
1734 }
1735
1736 public function tableExists( $table, $fname = __METHOD__ ) {
1737 $tableRaw = $this->tableName( $table, 'raw' );
1738 if ( isset( $this->sessionTempTables[$tableRaw] ) ) {
1739 return true; // already known to exist
1740 }
1741
1742 $table = $this->tableName( $table );
1743 $ignoreErrors = true;
1744 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1745
1746 return (bool)$res;
1747 }
1748
1749 public function indexUnique( $table, $index ) {
1750 $indexInfo = $this->indexInfo( $table, $index );
1751
1752 if ( !$indexInfo ) {
1753 return null;
1754 }
1755
1756 return !$indexInfo[0]->Non_unique;
1757 }
1758
1759 /**
1760 * Helper for Database::insert().
1761 *
1762 * @param array $options
1763 * @return string
1764 */
1765 protected function makeInsertOptions( $options ) {
1766 return implode( ' ', $options );
1767 }
1768
1769 public function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
1770 # No rows to insert, easy just return now
1771 if ( !count( $a ) ) {
1772 return true;
1773 }
1774
1775 $table = $this->tableName( $table );
1776
1777 if ( !is_array( $options ) ) {
1778 $options = [ $options ];
1779 }
1780
1781 $fh = null;
1782 if ( isset( $options['fileHandle'] ) ) {
1783 $fh = $options['fileHandle'];
1784 }
1785 $options = $this->makeInsertOptions( $options );
1786
1787 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1788 $multi = true;
1789 $keys = array_keys( $a[0] );
1790 } else {
1791 $multi = false;
1792 $keys = array_keys( $a );
1793 }
1794
1795 $sql = 'INSERT ' . $options .
1796 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1797
1798 if ( $multi ) {
1799 $first = true;
1800 foreach ( $a as $row ) {
1801 if ( $first ) {
1802 $first = false;
1803 } else {
1804 $sql .= ',';
1805 }
1806 $sql .= '(' . $this->makeList( $row ) . ')';
1807 }
1808 } else {
1809 $sql .= '(' . $this->makeList( $a ) . ')';
1810 }
1811
1812 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1813 return false;
1814 } elseif ( $fh !== null ) {
1815 return true;
1816 }
1817
1818 return (bool)$this->query( $sql, $fname );
1819 }
1820
1821 /**
1822 * Make UPDATE options array for Database::makeUpdateOptions
1823 *
1824 * @param array $options
1825 * @return array
1826 */
1827 protected function makeUpdateOptionsArray( $options ) {
1828 if ( !is_array( $options ) ) {
1829 $options = [ $options ];
1830 }
1831
1832 $opts = [];
1833
1834 if ( in_array( 'IGNORE', $options ) ) {
1835 $opts[] = 'IGNORE';
1836 }
1837
1838 return $opts;
1839 }
1840
1841 /**
1842 * Make UPDATE options for the Database::update function
1843 *
1844 * @param array $options The options passed to Database::update
1845 * @return string
1846 */
1847 protected function makeUpdateOptions( $options ) {
1848 $opts = $this->makeUpdateOptionsArray( $options );
1849
1850 return implode( ' ', $opts );
1851 }
1852
1853 public function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
1854 $table = $this->tableName( $table );
1855 $opts = $this->makeUpdateOptions( $options );
1856 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self::LIST_SET );
1857
1858 if ( $conds !== [] && $conds !== '*' ) {
1859 $sql .= " WHERE " . $this->makeList( $conds, self::LIST_AND );
1860 }
1861
1862 return (bool)$this->query( $sql, $fname );
1863 }
1864
1865 public function makeList( $a, $mode = self::LIST_COMMA ) {
1866 if ( !is_array( $a ) ) {
1867 throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
1868 }
1869
1870 $first = true;
1871 $list = '';
1872
1873 foreach ( $a as $field => $value ) {
1874 if ( !$first ) {
1875 if ( $mode == self::LIST_AND ) {
1876 $list .= ' AND ';
1877 } elseif ( $mode == self::LIST_OR ) {
1878 $list .= ' OR ';
1879 } else {
1880 $list .= ',';
1881 }
1882 } else {
1883 $first = false;
1884 }
1885
1886 if ( ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_numeric( $field ) ) {
1887 $list .= "($value)";
1888 } elseif ( $mode == self::LIST_SET && is_numeric( $field ) ) {
1889 $list .= "$value";
1890 } elseif (
1891 ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_array( $value )
1892 ) {
1893 // Remove null from array to be handled separately if found
1894 $includeNull = false;
1895 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1896 $includeNull = true;
1897 unset( $value[$nullKey] );
1898 }
1899 if ( count( $value ) == 0 && !$includeNull ) {
1900 throw new InvalidArgumentException(
1901 __METHOD__ . ": empty input for field $field" );
1902 } elseif ( count( $value ) == 0 ) {
1903 // only check if $field is null
1904 $list .= "$field IS NULL";
1905 } else {
1906 // IN clause contains at least one valid element
1907 if ( $includeNull ) {
1908 // Group subconditions to ensure correct precedence
1909 $list .= '(';
1910 }
1911 if ( count( $value ) == 1 ) {
1912 // Special-case single values, as IN isn't terribly efficient
1913 // Don't necessarily assume the single key is 0; we don't
1914 // enforce linear numeric ordering on other arrays here.
1915 $value = array_values( $value )[0];
1916 $list .= $field . " = " . $this->addQuotes( $value );
1917 } else {
1918 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1919 }
1920 // if null present in array, append IS NULL
1921 if ( $includeNull ) {
1922 $list .= " OR $field IS NULL)";
1923 }
1924 }
1925 } elseif ( $value === null ) {
1926 if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
1927 $list .= "$field IS ";
1928 } elseif ( $mode == self::LIST_SET ) {
1929 $list .= "$field = ";
1930 }
1931 $list .= 'NULL';
1932 } else {
1933 if (
1934 $mode == self::LIST_AND || $mode == self::LIST_OR || $mode == self::LIST_SET
1935 ) {
1936 $list .= "$field = ";
1937 }
1938 $list .= $mode == self::LIST_NAMES ? $value : $this->addQuotes( $value );
1939 }
1940 }
1941
1942 return $list;
1943 }
1944
1945 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1946 $conds = [];
1947
1948 foreach ( $data as $base => $sub ) {
1949 if ( count( $sub ) ) {
1950 $conds[] = $this->makeList(
1951 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1952 self::LIST_AND );
1953 }
1954 }
1955
1956 if ( $conds ) {
1957 return $this->makeList( $conds, self::LIST_OR );
1958 } else {
1959 // Nothing to search for...
1960 return false;
1961 }
1962 }
1963
1964 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1965 return $valuename;
1966 }
1967
1968 public function bitNot( $field ) {
1969 return "(~$field)";
1970 }
1971
1972 public function bitAnd( $fieldLeft, $fieldRight ) {
1973 return "($fieldLeft & $fieldRight)";
1974 }
1975
1976 public function bitOr( $fieldLeft, $fieldRight ) {
1977 return "($fieldLeft | $fieldRight)";
1978 }
1979
1980 public function buildConcat( $stringList ) {
1981 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1982 }
1983
1984 public function buildGroupConcatField(
1985 $delim, $table, $field, $conds = '', $join_conds = []
1986 ) {
1987 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1988
1989 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1990 }
1991
1992 public function buildSubstring( $input, $startPosition, $length = null ) {
1993 $this->assertBuildSubstringParams( $startPosition, $length );
1994 $functionBody = "$input FROM $startPosition";
1995 if ( $length !== null ) {
1996 $functionBody .= " FOR $length";
1997 }
1998 return 'SUBSTRING(' . $functionBody . ')';
1999 }
2000
2001 /**
2002 * Check type and bounds for parameters to self::buildSubstring()
2003 *
2004 * All supported databases have substring functions that behave the same for
2005 * positive $startPosition and non-negative $length, but behaviors differ when
2006 * given 0 or negative $startPosition or negative $length. The simplest
2007 * solution to that is to just forbid those values.
2008 *
2009 * @param int $startPosition
2010 * @param int|null $length
2011 * @since 1.31
2012 */
2013 protected function assertBuildSubstringParams( $startPosition, $length ) {
2014 if ( !is_int( $startPosition ) || $startPosition <= 0 ) {
2015 throw new InvalidArgumentException(
2016 '$startPosition must be a positive integer'
2017 );
2018 }
2019 if ( !( is_int( $length ) && $length >= 0 || $length === null ) ) {
2020 throw new InvalidArgumentException(
2021 '$length must be null or an integer greater than or equal to 0'
2022 );
2023 }
2024 }
2025
2026 public function buildStringCast( $field ) {
2027 return $field;
2028 }
2029
2030 public function buildIntegerCast( $field ) {
2031 return 'CAST( ' . $field . ' AS INTEGER )';
2032 }
2033
2034 public function buildSelectSubquery(
2035 $table, $vars, $conds = '', $fname = __METHOD__,
2036 $options = [], $join_conds = []
2037 ) {
2038 return new Subquery(
2039 $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2040 );
2041 }
2042
2043 public function databasesAreIndependent() {
2044 return false;
2045 }
2046
2047 public function selectDB( $db ) {
2048 # Stub. Shouldn't cause serious problems if it's not overridden, but
2049 # if your database engine supports a concept similar to MySQL's
2050 # databases you may as well.
2051 $this->dbName = $db;
2052
2053 return true;
2054 }
2055
2056 public function getDBname() {
2057 return $this->dbName;
2058 }
2059
2060 public function getServer() {
2061 return $this->server;
2062 }
2063
2064 public function tableName( $name, $format = 'quoted' ) {
2065 if ( $name instanceof Subquery ) {
2066 throw new DBUnexpectedError(
2067 $this,
2068 __METHOD__ . ': got Subquery instance when expecting a string.'
2069 );
2070 }
2071
2072 # Skip the entire process when we have a string quoted on both ends.
2073 # Note that we check the end so that we will still quote any use of
2074 # use of `database`.table. But won't break things if someone wants
2075 # to query a database table with a dot in the name.
2076 if ( $this->isQuotedIdentifier( $name ) ) {
2077 return $name;
2078 }
2079
2080 # Lets test for any bits of text that should never show up in a table
2081 # name. Basically anything like JOIN or ON which are actually part of
2082 # SQL queries, but may end up inside of the table value to combine
2083 # sql. Such as how the API is doing.
2084 # Note that we use a whitespace test rather than a \b test to avoid
2085 # any remote case where a word like on may be inside of a table name
2086 # surrounded by symbols which may be considered word breaks.
2087 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2088 $this->queryLogger->warning(
2089 __METHOD__ . ": use of subqueries is not supported this way.",
2090 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
2091 );
2092
2093 return $name;
2094 }
2095
2096 # Split database and table into proper variables.
2097 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2098
2099 # Quote $table and apply the prefix if not quoted.
2100 # $tableName might be empty if this is called from Database::replaceVars()
2101 $tableName = "{$prefix}{$table}";
2102 if ( $format === 'quoted'
2103 && !$this->isQuotedIdentifier( $tableName )
2104 && $tableName !== ''
2105 ) {
2106 $tableName = $this->addIdentifierQuotes( $tableName );
2107 }
2108
2109 # Quote $schema and $database and merge them with the table name if needed
2110 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2111 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2112
2113 return $tableName;
2114 }
2115
2116 /**
2117 * Get the table components needed for a query given the currently selected database
2118 *
2119 * @param string $name Table name in the form of db.schema.table, db.table, or table
2120 * @return array (DB name or "" for default, schema name, table prefix, table name)
2121 */
2122 protected function qualifiedTableComponents( $name ) {
2123 # We reverse the explode so that database.table and table both output the correct table.
2124 $dbDetails = explode( '.', $name, 3 );
2125 if ( count( $dbDetails ) == 3 ) {
2126 list( $database, $schema, $table ) = $dbDetails;
2127 # We don't want any prefix added in this case
2128 $prefix = '';
2129 } elseif ( count( $dbDetails ) == 2 ) {
2130 list( $database, $table ) = $dbDetails;
2131 # We don't want any prefix added in this case
2132 $prefix = '';
2133 # In dbs that support it, $database may actually be the schema
2134 # but that doesn't affect any of the functionality here
2135 $schema = '';
2136 } else {
2137 list( $table ) = $dbDetails;
2138 if ( isset( $this->tableAliases[$table] ) ) {
2139 $database = $this->tableAliases[$table]['dbname'];
2140 $schema = is_string( $this->tableAliases[$table]['schema'] )
2141 ? $this->tableAliases[$table]['schema']
2142 : $this->schema;
2143 $prefix = is_string( $this->tableAliases[$table]['prefix'] )
2144 ? $this->tableAliases[$table]['prefix']
2145 : $this->tablePrefix;
2146 } else {
2147 $database = '';
2148 $schema = $this->schema; # Default schema
2149 $prefix = $this->tablePrefix; # Default prefix
2150 }
2151 }
2152
2153 return [ $database, $schema, $prefix, $table ];
2154 }
2155
2156 /**
2157 * @param string|null $namespace Database or schema
2158 * @param string $relation Name of table, view, sequence, etc...
2159 * @param string $format One of (raw, quoted)
2160 * @return string Relation name with quoted and merged $namespace as needed
2161 */
2162 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2163 if ( strlen( $namespace ) ) {
2164 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2165 $namespace = $this->addIdentifierQuotes( $namespace );
2166 }
2167 $relation = $namespace . '.' . $relation;
2168 }
2169
2170 return $relation;
2171 }
2172
2173 public function tableNames() {
2174 $inArray = func_get_args();
2175 $retVal = [];
2176
2177 foreach ( $inArray as $name ) {
2178 $retVal[$name] = $this->tableName( $name );
2179 }
2180
2181 return $retVal;
2182 }
2183
2184 public function tableNamesN() {
2185 $inArray = func_get_args();
2186 $retVal = [];
2187
2188 foreach ( $inArray as $name ) {
2189 $retVal[] = $this->tableName( $name );
2190 }
2191
2192 return $retVal;
2193 }
2194
2195 /**
2196 * Get an aliased table name
2197 *
2198 * This returns strings like "tableName AS newTableName" for aliased tables
2199 * and "(SELECT * from tableA) newTablename" for subqueries (e.g. derived tables)
2200 *
2201 * @see Database::tableName()
2202 * @param string|Subquery $table Table name or object with a 'sql' field
2203 * @param string|bool $alias Table alias (optional)
2204 * @return string SQL name for aliased table. Will not alias a table to its own name
2205 */
2206 protected function tableNameWithAlias( $table, $alias = false ) {
2207 if ( is_string( $table ) ) {
2208 $quotedTable = $this->tableName( $table );
2209 } elseif ( $table instanceof Subquery ) {
2210 $quotedTable = (string)$table;
2211 } else {
2212 throw new InvalidArgumentException( "Table must be a string or Subquery." );
2213 }
2214
2215 if ( !strlen( $alias ) || $alias === $table ) {
2216 if ( $table instanceof Subquery ) {
2217 throw new InvalidArgumentException( "Subquery table missing alias." );
2218 }
2219
2220 return $quotedTable;
2221 } else {
2222 return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2223 }
2224 }
2225
2226 /**
2227 * Gets an array of aliased table names
2228 *
2229 * @param array $tables [ [alias] => table ]
2230 * @return string[] See tableNameWithAlias()
2231 */
2232 protected function tableNamesWithAlias( $tables ) {
2233 $retval = [];
2234 foreach ( $tables as $alias => $table ) {
2235 if ( is_numeric( $alias ) ) {
2236 $alias = $table;
2237 }
2238 $retval[] = $this->tableNameWithAlias( $table, $alias );
2239 }
2240
2241 return $retval;
2242 }
2243
2244 /**
2245 * Get an aliased field name
2246 * e.g. fieldName AS newFieldName
2247 *
2248 * @param string $name Field name
2249 * @param string|bool $alias Alias (optional)
2250 * @return string SQL name for aliased field. Will not alias a field to its own name
2251 */
2252 protected function fieldNameWithAlias( $name, $alias = false ) {
2253 if ( !$alias || (string)$alias === (string)$name ) {
2254 return $name;
2255 } else {
2256 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2257 }
2258 }
2259
2260 /**
2261 * Gets an array of aliased field names
2262 *
2263 * @param array $fields [ [alias] => field ]
2264 * @return string[] See fieldNameWithAlias()
2265 */
2266 protected function fieldNamesWithAlias( $fields ) {
2267 $retval = [];
2268 foreach ( $fields as $alias => $field ) {
2269 if ( is_numeric( $alias ) ) {
2270 $alias = $field;
2271 }
2272 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2273 }
2274
2275 return $retval;
2276 }
2277
2278 /**
2279 * Get the aliased table name clause for a FROM clause
2280 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2281 *
2282 * @param array $tables ( [alias] => table )
2283 * @param array $use_index Same as for select()
2284 * @param array $ignore_index Same as for select()
2285 * @param array $join_conds Same as for select()
2286 * @return string
2287 */
2288 protected function tableNamesWithIndexClauseOrJOIN(
2289 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2290 ) {
2291 $ret = [];
2292 $retJOIN = [];
2293 $use_index = (array)$use_index;
2294 $ignore_index = (array)$ignore_index;
2295 $join_conds = (array)$join_conds;
2296
2297 foreach ( $tables as $alias => $table ) {
2298 if ( !is_string( $alias ) ) {
2299 // No alias? Set it equal to the table name
2300 $alias = $table;
2301 }
2302
2303 if ( is_array( $table ) ) {
2304 // A parenthesized group
2305 if ( count( $table ) > 1 ) {
2306 $joinedTable = '(' .
2307 $this->tableNamesWithIndexClauseOrJOIN(
2308 $table, $use_index, $ignore_index, $join_conds ) . ')';
2309 } else {
2310 // Degenerate case
2311 $innerTable = reset( $table );
2312 $innerAlias = key( $table );
2313 $joinedTable = $this->tableNameWithAlias(
2314 $innerTable,
2315 is_string( $innerAlias ) ? $innerAlias : $innerTable
2316 );
2317 }
2318 } else {
2319 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2320 }
2321
2322 // Is there a JOIN clause for this table?
2323 if ( isset( $join_conds[$alias] ) ) {
2324 list( $joinType, $conds ) = $join_conds[$alias];
2325 $tableClause = $joinType;
2326 $tableClause .= ' ' . $joinedTable;
2327 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2328 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2329 if ( $use != '' ) {
2330 $tableClause .= ' ' . $use;
2331 }
2332 }
2333 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2334 $ignore = $this->ignoreIndexClause(
2335 implode( ',', (array)$ignore_index[$alias] ) );
2336 if ( $ignore != '' ) {
2337 $tableClause .= ' ' . $ignore;
2338 }
2339 }
2340 $on = $this->makeList( (array)$conds, self::LIST_AND );
2341 if ( $on != '' ) {
2342 $tableClause .= ' ON (' . $on . ')';
2343 }
2344
2345 $retJOIN[] = $tableClause;
2346 } elseif ( isset( $use_index[$alias] ) ) {
2347 // Is there an INDEX clause for this table?
2348 $tableClause = $joinedTable;
2349 $tableClause .= ' ' . $this->useIndexClause(
2350 implode( ',', (array)$use_index[$alias] )
2351 );
2352
2353 $ret[] = $tableClause;
2354 } elseif ( isset( $ignore_index[$alias] ) ) {
2355 // Is there an INDEX clause for this table?
2356 $tableClause = $joinedTable;
2357 $tableClause .= ' ' . $this->ignoreIndexClause(
2358 implode( ',', (array)$ignore_index[$alias] )
2359 );
2360
2361 $ret[] = $tableClause;
2362 } else {
2363 $tableClause = $joinedTable;
2364
2365 $ret[] = $tableClause;
2366 }
2367 }
2368
2369 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2370 $implicitJoins = $ret ? implode( ',', $ret ) : "";
2371 $explicitJoins = $retJOIN ? implode( ' ', $retJOIN ) : "";
2372
2373 // Compile our final table clause
2374 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2375 }
2376
2377 /**
2378 * Allows for index remapping in queries where this is not consistent across DBMS
2379 *
2380 * @param string $index
2381 * @return string
2382 */
2383 protected function indexName( $index ) {
2384 return isset( $this->indexAliases[$index] )
2385 ? $this->indexAliases[$index]
2386 : $index;
2387 }
2388
2389 public function addQuotes( $s ) {
2390 if ( $s instanceof Blob ) {
2391 $s = $s->fetch();
2392 }
2393 if ( $s === null ) {
2394 return 'NULL';
2395 } elseif ( is_bool( $s ) ) {
2396 return (int)$s;
2397 } else {
2398 # This will also quote numeric values. This should be harmless,
2399 # and protects against weird problems that occur when they really
2400 # _are_ strings such as article titles and string->number->string
2401 # conversion is not 1:1.
2402 return "'" . $this->strencode( $s ) . "'";
2403 }
2404 }
2405
2406 /**
2407 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2408 * MySQL uses `backticks` while basically everything else uses double quotes.
2409 * Since MySQL is the odd one out here the double quotes are our generic
2410 * and we implement backticks in DatabaseMysqlBase.
2411 *
2412 * @param string $s
2413 * @return string
2414 */
2415 public function addIdentifierQuotes( $s ) {
2416 return '"' . str_replace( '"', '""', $s ) . '"';
2417 }
2418
2419 /**
2420 * Returns if the given identifier looks quoted or not according to
2421 * the database convention for quoting identifiers .
2422 *
2423 * @note Do not use this to determine if untrusted input is safe.
2424 * A malicious user can trick this function.
2425 * @param string $name
2426 * @return bool
2427 */
2428 public function isQuotedIdentifier( $name ) {
2429 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2430 }
2431
2432 /**
2433 * @param string $s
2434 * @param string $escapeChar
2435 * @return string
2436 */
2437 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2438 return str_replace( [ $escapeChar, '%', '_' ],
2439 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2440 $s );
2441 }
2442
2443 public function buildLike() {
2444 $params = func_get_args();
2445
2446 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2447 $params = $params[0];
2448 }
2449
2450 $s = '';
2451
2452 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2453 // may escape backslashes, creating problems of double escaping. The `
2454 // character has good cross-DBMS compatibility, avoiding special operators
2455 // in MS SQL like ^ and %
2456 $escapeChar = '`';
2457
2458 foreach ( $params as $value ) {
2459 if ( $value instanceof LikeMatch ) {
2460 $s .= $value->toString();
2461 } else {
2462 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2463 }
2464 }
2465
2466 return ' LIKE ' .
2467 $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2468 }
2469
2470 public function anyChar() {
2471 return new LikeMatch( '_' );
2472 }
2473
2474 public function anyString() {
2475 return new LikeMatch( '%' );
2476 }
2477
2478 public function nextSequenceValue( $seqName ) {
2479 return null;
2480 }
2481
2482 /**
2483 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2484 * is only needed because a) MySQL must be as efficient as possible due to
2485 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2486 * which index to pick. Anyway, other databases might have different
2487 * indexes on a given table. So don't bother overriding this unless you're
2488 * MySQL.
2489 * @param string $index
2490 * @return string
2491 */
2492 public function useIndexClause( $index ) {
2493 return '';
2494 }
2495
2496 /**
2497 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2498 * is only needed because a) MySQL must be as efficient as possible due to
2499 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2500 * which index to pick. Anyway, other databases might have different
2501 * indexes on a given table. So don't bother overriding this unless you're
2502 * MySQL.
2503 * @param string $index
2504 * @return string
2505 */
2506 public function ignoreIndexClause( $index ) {
2507 return '';
2508 }
2509
2510 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2511 if ( count( $rows ) == 0 ) {
2512 return;
2513 }
2514
2515 // Single row case
2516 if ( !is_array( reset( $rows ) ) ) {
2517 $rows = [ $rows ];
2518 }
2519
2520 try {
2521 $this->startAtomic( $fname );
2522 $affectedRowCount = 0;
2523 foreach ( $rows as $row ) {
2524 // Delete rows which collide with this one
2525 $indexWhereClauses = [];
2526 foreach ( $uniqueIndexes as $index ) {
2527 $indexColumns = (array)$index;
2528 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2529 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2530 throw new DBUnexpectedError(
2531 $this,
2532 'New record does not provide all values for unique key (' .
2533 implode( ', ', $indexColumns ) . ')'
2534 );
2535 } elseif ( in_array( null, $indexRowValues, true ) ) {
2536 throw new DBUnexpectedError(
2537 $this,
2538 'New record has a null value for unique key (' .
2539 implode( ', ', $indexColumns ) . ')'
2540 );
2541 }
2542 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND );
2543 }
2544
2545 if ( $indexWhereClauses ) {
2546 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR ), $fname );
2547 $affectedRowCount += $this->affectedRows();
2548 }
2549
2550 // Now insert the row
2551 $this->insert( $table, $row, $fname );
2552 $affectedRowCount += $this->affectedRows();
2553 }
2554 $this->endAtomic( $fname );
2555 $this->affectedRowCount = $affectedRowCount;
2556 } catch ( Exception $e ) {
2557 $this->cancelAtomic( $fname );
2558 throw $e;
2559 }
2560 }
2561
2562 /**
2563 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2564 * statement.
2565 *
2566 * @param string $table Table name
2567 * @param array|string $rows Row(s) to insert
2568 * @param string $fname Caller function name
2569 *
2570 * @return ResultWrapper
2571 */
2572 protected function nativeReplace( $table, $rows, $fname ) {
2573 $table = $this->tableName( $table );
2574
2575 # Single row case
2576 if ( !is_array( reset( $rows ) ) ) {
2577 $rows = [ $rows ];
2578 }
2579
2580 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2581 $first = true;
2582
2583 foreach ( $rows as $row ) {
2584 if ( $first ) {
2585 $first = false;
2586 } else {
2587 $sql .= ',';
2588 }
2589
2590 $sql .= '(' . $this->makeList( $row ) . ')';
2591 }
2592
2593 return $this->query( $sql, $fname );
2594 }
2595
2596 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2597 $fname = __METHOD__
2598 ) {
2599 if ( !count( $rows ) ) {
2600 return true; // nothing to do
2601 }
2602
2603 if ( !is_array( reset( $rows ) ) ) {
2604 $rows = [ $rows ];
2605 }
2606
2607 if ( count( $uniqueIndexes ) ) {
2608 $clauses = []; // list WHERE clauses that each identify a single row
2609 foreach ( $rows as $row ) {
2610 foreach ( $uniqueIndexes as $index ) {
2611 $index = is_array( $index ) ? $index : [ $index ]; // columns
2612 $rowKey = []; // unique key to this row
2613 foreach ( $index as $column ) {
2614 $rowKey[$column] = $row[$column];
2615 }
2616 $clauses[] = $this->makeList( $rowKey, self::LIST_AND );
2617 }
2618 }
2619 $where = [ $this->makeList( $clauses, self::LIST_OR ) ];
2620 } else {
2621 $where = false;
2622 }
2623
2624 $affectedRowCount = 0;
2625 try {
2626 $this->startAtomic( $fname );
2627 # Update any existing conflicting row(s)
2628 if ( $where !== false ) {
2629 $ok = $this->update( $table, $set, $where, $fname );
2630 $affectedRowCount += $this->affectedRows();
2631 } else {
2632 $ok = true;
2633 }
2634 # Now insert any non-conflicting row(s)
2635 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2636 $affectedRowCount += $this->affectedRows();
2637 $this->endAtomic( $fname );
2638 $this->affectedRowCount = $affectedRowCount;
2639 } catch ( Exception $e ) {
2640 $this->cancelAtomic( $fname );
2641 throw $e;
2642 }
2643
2644 return $ok;
2645 }
2646
2647 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2648 $fname = __METHOD__
2649 ) {
2650 if ( !$conds ) {
2651 throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
2652 }
2653
2654 $delTable = $this->tableName( $delTable );
2655 $joinTable = $this->tableName( $joinTable );
2656 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2657 if ( $conds != '*' ) {
2658 $sql .= 'WHERE ' . $this->makeList( $conds, self::LIST_AND );
2659 }
2660 $sql .= ')';
2661
2662 $this->query( $sql, $fname );
2663 }
2664
2665 public function textFieldSize( $table, $field ) {
2666 $table = $this->tableName( $table );
2667 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2668 $res = $this->query( $sql, __METHOD__ );
2669 $row = $this->fetchObject( $res );
2670
2671 $m = [];
2672
2673 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2674 $size = $m[1];
2675 } else {
2676 $size = -1;
2677 }
2678
2679 return $size;
2680 }
2681
2682 public function delete( $table, $conds, $fname = __METHOD__ ) {
2683 if ( !$conds ) {
2684 throw new DBUnexpectedError( $this, __METHOD__ . ' called with no conditions' );
2685 }
2686
2687 $table = $this->tableName( $table );
2688 $sql = "DELETE FROM $table";
2689
2690 if ( $conds != '*' ) {
2691 if ( is_array( $conds ) ) {
2692 $conds = $this->makeList( $conds, self::LIST_AND );
2693 }
2694 $sql .= ' WHERE ' . $conds;
2695 }
2696
2697 return $this->query( $sql, $fname );
2698 }
2699
2700 final public function insertSelect(
2701 $destTable, $srcTable, $varMap, $conds,
2702 $fname = __METHOD__, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2703 ) {
2704 static $hints = [ 'NO_AUTO_COLUMNS' ];
2705
2706 $insertOptions = (array)$insertOptions;
2707 $selectOptions = (array)$selectOptions;
2708
2709 if ( $this->cliMode && $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
2710 // For massive migrations with downtime, we don't want to select everything
2711 // into memory and OOM, so do all this native on the server side if possible.
2712 return $this->nativeInsertSelect(
2713 $destTable,
2714 $srcTable,
2715 $varMap,
2716 $conds,
2717 $fname,
2718 array_diff( $insertOptions, $hints ),
2719 $selectOptions,
2720 $selectJoinConds
2721 );
2722 }
2723
2724 return $this->nonNativeInsertSelect(
2725 $destTable,
2726 $srcTable,
2727 $varMap,
2728 $conds,
2729 $fname,
2730 array_diff( $insertOptions, $hints ),
2731 $selectOptions,
2732 $selectJoinConds
2733 );
2734 }
2735
2736 /**
2737 * @param array $insertOptions INSERT options
2738 * @param array $selectOptions SELECT options
2739 * @return bool Whether an INSERT SELECT with these options will be replication safe
2740 * @since 1.31
2741 */
2742 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
2743 return true;
2744 }
2745
2746 /**
2747 * Implementation of insertSelect() based on select() and insert()
2748 *
2749 * @see IDatabase::insertSelect()
2750 * @since 1.30
2751 * @param string $destTable
2752 * @param string|array $srcTable
2753 * @param array $varMap
2754 * @param array $conds
2755 * @param string $fname
2756 * @param array $insertOptions
2757 * @param array $selectOptions
2758 * @param array $selectJoinConds
2759 * @return bool
2760 */
2761 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2762 $fname = __METHOD__,
2763 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2764 ) {
2765 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2766 // on only the master (without needing row-based-replication). It also makes it easy to
2767 // know how big the INSERT is going to be.
2768 $fields = [];
2769 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2770 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2771 }
2772 $selectOptions[] = 'FOR UPDATE';
2773 $res = $this->select(
2774 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2775 );
2776 if ( !$res ) {
2777 return false;
2778 }
2779
2780 try {
2781 $affectedRowCount = 0;
2782 $this->startAtomic( $fname );
2783 $rows = [];
2784 $ok = true;
2785 foreach ( $res as $row ) {
2786 $rows[] = (array)$row;
2787
2788 // Avoid inserts that are too huge
2789 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize ) {
2790 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2791 if ( !$ok ) {
2792 break;
2793 }
2794 $affectedRowCount += $this->affectedRows();
2795 $rows = [];
2796 }
2797 }
2798 if ( $rows && $ok ) {
2799 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2800 if ( $ok ) {
2801 $affectedRowCount += $this->affectedRows();
2802 }
2803 }
2804 if ( $ok ) {
2805 $this->endAtomic( $fname );
2806 $this->affectedRowCount = $affectedRowCount;
2807 } else {
2808 $this->cancelAtomic( $fname );
2809 }
2810 return $ok;
2811 } catch ( Exception $e ) {
2812 $this->cancelAtomic( $fname );
2813 throw $e;
2814 }
2815 }
2816
2817 /**
2818 * Native server-side implementation of insertSelect() for situations where
2819 * we don't want to select everything into memory
2820 *
2821 * @see IDatabase::insertSelect()
2822 * @param string $destTable
2823 * @param string|array $srcTable
2824 * @param array $varMap
2825 * @param array $conds
2826 * @param string $fname
2827 * @param array $insertOptions
2828 * @param array $selectOptions
2829 * @param array $selectJoinConds
2830 * @return bool
2831 */
2832 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2833 $fname = __METHOD__,
2834 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2835 ) {
2836 $destTable = $this->tableName( $destTable );
2837
2838 if ( !is_array( $insertOptions ) ) {
2839 $insertOptions = [ $insertOptions ];
2840 }
2841
2842 $insertOptions = $this->makeInsertOptions( $insertOptions );
2843
2844 $selectSql = $this->selectSQLText(
2845 $srcTable,
2846 array_values( $varMap ),
2847 $conds,
2848 $fname,
2849 $selectOptions,
2850 $selectJoinConds
2851 );
2852
2853 $sql = "INSERT $insertOptions" .
2854 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2855 $selectSql;
2856
2857 return $this->query( $sql, $fname );
2858 }
2859
2860 /**
2861 * Construct a LIMIT query with optional offset. This is used for query
2862 * pages. The SQL should be adjusted so that only the first $limit rows
2863 * are returned. If $offset is provided as well, then the first $offset
2864 * rows should be discarded, and the next $limit rows should be returned.
2865 * If the result of the query is not ordered, then the rows to be returned
2866 * are theoretically arbitrary.
2867 *
2868 * $sql is expected to be a SELECT, if that makes a difference.
2869 *
2870 * The version provided by default works in MySQL and SQLite. It will very
2871 * likely need to be overridden for most other DBMSes.
2872 *
2873 * @param string $sql SQL query we will append the limit too
2874 * @param int $limit The SQL limit
2875 * @param int|bool $offset The SQL offset (default false)
2876 * @throws DBUnexpectedError
2877 * @return string
2878 */
2879 public function limitResult( $sql, $limit, $offset = false ) {
2880 if ( !is_numeric( $limit ) ) {
2881 throw new DBUnexpectedError( $this,
2882 "Invalid non-numeric limit passed to limitResult()\n" );
2883 }
2884
2885 return "$sql LIMIT "
2886 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2887 . "{$limit} ";
2888 }
2889
2890 public function unionSupportsOrderAndLimit() {
2891 return true; // True for almost every DB supported
2892 }
2893
2894 public function unionQueries( $sqls, $all ) {
2895 $glue = $all ? ') UNION ALL (' : ') UNION (';
2896
2897 return '(' . implode( $glue, $sqls ) . ')';
2898 }
2899
2900 public function unionConditionPermutations(
2901 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__,
2902 $options = [], $join_conds = []
2903 ) {
2904 // First, build the Cartesian product of $permute_conds
2905 $conds = [ [] ];
2906 foreach ( $permute_conds as $field => $values ) {
2907 if ( !$values ) {
2908 // Skip empty $values
2909 continue;
2910 }
2911 $values = array_unique( $values ); // For sanity
2912 $newConds = [];
2913 foreach ( $conds as $cond ) {
2914 foreach ( $values as $value ) {
2915 $cond[$field] = $value;
2916 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
2917 }
2918 }
2919 $conds = $newConds;
2920 }
2921
2922 $extra_conds = $extra_conds === '' ? [] : (array)$extra_conds;
2923
2924 // If there's just one condition and no subordering, hand off to
2925 // selectSQLText directly.
2926 if ( count( $conds ) === 1 &&
2927 ( !isset( $options['INNER ORDER BY'] ) || !$this->unionSupportsOrderAndLimit() )
2928 ) {
2929 return $this->selectSQLText(
2930 $table, $vars, $conds[0] + $extra_conds, $fname, $options, $join_conds
2931 );
2932 }
2933
2934 // Otherwise, we need to pull out the order and limit to apply after
2935 // the union. Then build the SQL queries for each set of conditions in
2936 // $conds. Then union them together (using UNION ALL, because the
2937 // product *should* already be distinct).
2938 $orderBy = $this->makeOrderBy( $options );
2939 $limit = isset( $options['LIMIT'] ) ? $options['LIMIT'] : null;
2940 $offset = isset( $options['OFFSET'] ) ? $options['OFFSET'] : false;
2941 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
2942 if ( !$this->unionSupportsOrderAndLimit() ) {
2943 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
2944 } else {
2945 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
2946 $options['ORDER BY'] = $options['INNER ORDER BY'];
2947 }
2948 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
2949 // We need to increase the limit by the offset rather than
2950 // using the offset directly, otherwise it'll skip incorrectly
2951 // in the subqueries.
2952 $options['LIMIT'] = $limit + $offset;
2953 unset( $options['OFFSET'] );
2954 }
2955 }
2956
2957 $sqls = [];
2958 foreach ( $conds as $cond ) {
2959 $sqls[] = $this->selectSQLText(
2960 $table, $vars, $cond + $extra_conds, $fname, $options, $join_conds
2961 );
2962 }
2963 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
2964 if ( $limit !== null ) {
2965 $sql = $this->limitResult( $sql, $limit, $offset );
2966 }
2967
2968 return $sql;
2969 }
2970
2971 public function conditional( $cond, $trueVal, $falseVal ) {
2972 if ( is_array( $cond ) ) {
2973 $cond = $this->makeList( $cond, self::LIST_AND );
2974 }
2975
2976 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2977 }
2978
2979 public function strreplace( $orig, $old, $new ) {
2980 return "REPLACE({$orig}, {$old}, {$new})";
2981 }
2982
2983 public function getServerUptime() {
2984 return 0;
2985 }
2986
2987 public function wasDeadlock() {
2988 return false;
2989 }
2990
2991 public function wasLockTimeout() {
2992 return false;
2993 }
2994
2995 public function wasConnectionLoss() {
2996 return $this->wasConnectionError( $this->lastErrno() );
2997 }
2998
2999 public function wasReadOnlyError() {
3000 return false;
3001 }
3002
3003 public function wasErrorReissuable() {
3004 return (
3005 $this->wasDeadlock() ||
3006 $this->wasLockTimeout() ||
3007 $this->wasConnectionLoss()
3008 );
3009 }
3010
3011 /**
3012 * Do not use this method outside of Database/DBError classes
3013 *
3014 * @param int|string $errno
3015 * @return bool Whether the given query error was a connection drop
3016 */
3017 public function wasConnectionError( $errno ) {
3018 return false;
3019 }
3020
3021 public function deadlockLoop() {
3022 $args = func_get_args();
3023 $function = array_shift( $args );
3024 $tries = self::DEADLOCK_TRIES;
3025
3026 $this->begin( __METHOD__ );
3027
3028 $retVal = null;
3029 /** @var Exception $e */
3030 $e = null;
3031 do {
3032 try {
3033 $retVal = call_user_func_array( $function, $args );
3034 break;
3035 } catch ( DBQueryError $e ) {
3036 if ( $this->wasDeadlock() ) {
3037 // Retry after a randomized delay
3038 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
3039 } else {
3040 // Throw the error back up
3041 throw $e;
3042 }
3043 }
3044 } while ( --$tries > 0 );
3045
3046 if ( $tries <= 0 ) {
3047 // Too many deadlocks; give up
3048 $this->rollback( __METHOD__ );
3049 throw $e;
3050 } else {
3051 $this->commit( __METHOD__ );
3052
3053 return $retVal;
3054 }
3055 }
3056
3057 public function masterPosWait( DBMasterPos $pos, $timeout ) {
3058 # Real waits are implemented in the subclass.
3059 return 0;
3060 }
3061
3062 public function getReplicaPos() {
3063 # Stub
3064 return false;
3065 }
3066
3067 public function getMasterPos() {
3068 # Stub
3069 return false;
3070 }
3071
3072 public function serverIsReadOnly() {
3073 return false;
3074 }
3075
3076 final public function onTransactionResolution( callable $callback, $fname = __METHOD__ ) {
3077 if ( !$this->trxLevel ) {
3078 throw new DBUnexpectedError( $this, "No transaction is active." );
3079 }
3080 $this->trxEndCallbacks[] = [ $callback, $fname ];
3081 }
3082
3083 final public function onTransactionIdle( callable $callback, $fname = __METHOD__ ) {
3084 $this->trxIdleCallbacks[] = [ $callback, $fname ];
3085 if ( !$this->trxLevel ) {
3086 $this->runOnTransactionIdleCallbacks( self::TRIGGER_IDLE );
3087 }
3088 }
3089
3090 final public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
3091 if ( $this->trxLevel || $this->getFlag( self::DBO_TRX ) ) {
3092 // As long as DBO_TRX is set, writes will accumulate until the load balancer issues
3093 // an implicit commit of all peer databases. This is true even if a transaction has
3094 // not yet been triggered by writes; make sure $callback runs *after* any such writes.
3095 $this->trxPreCommitCallbacks[] = [ $callback, $fname ];
3096 } else {
3097 // No transaction is active nor will start implicitly, so make one for this callback
3098 $this->startAtomic( __METHOD__ );
3099 try {
3100 call_user_func( $callback );
3101 $this->endAtomic( __METHOD__ );
3102 } catch ( Exception $e ) {
3103 $this->cancelAtomic( __METHOD__ );
3104 throw $e;
3105 }
3106 }
3107 }
3108
3109 final public function setTransactionListener( $name, callable $callback = null ) {
3110 if ( $callback ) {
3111 $this->trxRecurringCallbacks[$name] = $callback;
3112 } else {
3113 unset( $this->trxRecurringCallbacks[$name] );
3114 }
3115 }
3116
3117 /**
3118 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
3119 *
3120 * This method should not be used outside of Database/LoadBalancer
3121 *
3122 * @param bool $suppress
3123 * @since 1.28
3124 */
3125 final public function setTrxEndCallbackSuppression( $suppress ) {
3126 $this->trxEndCallbacksSuppressed = $suppress;
3127 }
3128
3129 /**
3130 * Actually run and consume any "on transaction idle/resolution" callbacks.
3131 *
3132 * This method should not be used outside of Database/LoadBalancer
3133 *
3134 * @param int $trigger IDatabase::TRIGGER_* constant
3135 * @since 1.20
3136 * @throws Exception
3137 */
3138 public function runOnTransactionIdleCallbacks( $trigger ) {
3139 if ( $this->trxEndCallbacksSuppressed ) {
3140 return;
3141 }
3142
3143 $autoTrx = $this->getFlag( self::DBO_TRX ); // automatic begin() enabled?
3144 /** @var Exception $e */
3145 $e = null; // first exception
3146 do { // callbacks may add callbacks :)
3147 $callbacks = array_merge(
3148 $this->trxIdleCallbacks,
3149 $this->trxEndCallbacks // include "transaction resolution" callbacks
3150 );
3151 $this->trxIdleCallbacks = []; // consumed (and recursion guard)
3152 $this->trxEndCallbacks = []; // consumed (recursion guard)
3153 foreach ( $callbacks as $callback ) {
3154 try {
3155 list( $phpCallback ) = $callback;
3156 $this->clearFlag( self::DBO_TRX ); // make each query its own transaction
3157 call_user_func_array( $phpCallback, [ $trigger ] );
3158 if ( $autoTrx ) {
3159 $this->setFlag( self::DBO_TRX ); // restore automatic begin()
3160 } else {
3161 $this->clearFlag( self::DBO_TRX ); // restore auto-commit
3162 }
3163 } catch ( Exception $ex ) {
3164 call_user_func( $this->errorLogger, $ex );
3165 $e = $e ?: $ex;
3166 // Some callbacks may use startAtomic/endAtomic, so make sure
3167 // their transactions are ended so other callbacks don't fail
3168 if ( $this->trxLevel() ) {
3169 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
3170 }
3171 }
3172 }
3173 } while ( count( $this->trxIdleCallbacks ) );
3174
3175 if ( $e instanceof Exception ) {
3176 throw $e; // re-throw any first exception
3177 }
3178 }
3179
3180 /**
3181 * Actually run and consume any "on transaction pre-commit" callbacks.
3182 *
3183 * This method should not be used outside of Database/LoadBalancer
3184 *
3185 * @since 1.22
3186 * @throws Exception
3187 */
3188 public function runOnTransactionPreCommitCallbacks() {
3189 $e = null; // first exception
3190 do { // callbacks may add callbacks :)
3191 $callbacks = $this->trxPreCommitCallbacks;
3192 $this->trxPreCommitCallbacks = []; // consumed (and recursion guard)
3193 foreach ( $callbacks as $callback ) {
3194 try {
3195 list( $phpCallback ) = $callback;
3196 call_user_func( $phpCallback );
3197 } catch ( Exception $ex ) {
3198 call_user_func( $this->errorLogger, $ex );
3199 $e = $e ?: $ex;
3200 }
3201 }
3202 } while ( count( $this->trxPreCommitCallbacks ) );
3203
3204 if ( $e instanceof Exception ) {
3205 throw $e; // re-throw any first exception
3206 }
3207 }
3208
3209 /**
3210 * Actually run any "transaction listener" callbacks.
3211 *
3212 * This method should not be used outside of Database/LoadBalancer
3213 *
3214 * @param int $trigger IDatabase::TRIGGER_* constant
3215 * @throws Exception
3216 * @since 1.20
3217 */
3218 public function runTransactionListenerCallbacks( $trigger ) {
3219 if ( $this->trxEndCallbacksSuppressed ) {
3220 return;
3221 }
3222
3223 /** @var Exception $e */
3224 $e = null; // first exception
3225
3226 foreach ( $this->trxRecurringCallbacks as $phpCallback ) {
3227 try {
3228 $phpCallback( $trigger, $this );
3229 } catch ( Exception $ex ) {
3230 call_user_func( $this->errorLogger, $ex );
3231 $e = $e ?: $ex;
3232 }
3233 }
3234
3235 if ( $e instanceof Exception ) {
3236 throw $e; // re-throw any first exception
3237 }
3238 }
3239
3240 /**
3241 * Create a savepoint
3242 *
3243 * This is used internally to implement atomic sections. It should not be
3244 * used otherwise.
3245 *
3246 * @since 1.31
3247 * @param string $identifier Identifier for the savepoint
3248 * @param string $fname Calling function name
3249 */
3250 protected function doSavepoint( $identifier, $fname ) {
3251 $this->query( 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3252 }
3253
3254 /**
3255 * Release a savepoint
3256 *
3257 * This is used internally to implement atomic sections. It should not be
3258 * used otherwise.
3259 *
3260 * @since 1.31
3261 * @param string $identifier Identifier for the savepoint
3262 * @param string $fname Calling function name
3263 */
3264 protected function doReleaseSavepoint( $identifier, $fname ) {
3265 $this->query( 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3266 }
3267
3268 /**
3269 * Rollback to a savepoint
3270 *
3271 * This is used internally to implement atomic sections. It should not be
3272 * used otherwise.
3273 *
3274 * @since 1.31
3275 * @param string $identifier Identifier for the savepoint
3276 * @param string $fname Calling function name
3277 */
3278 protected function doRollbackToSavepoint( $identifier, $fname ) {
3279 $this->query( 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3280 }
3281
3282 final public function startAtomic( $fname = __METHOD__ ) {
3283 if ( !$this->trxLevel ) {
3284 $this->begin( $fname, self::TRANSACTION_INTERNAL );
3285 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3286 // in all changes being in one transaction to keep requests transactional.
3287 if ( !$this->getFlag( self::DBO_TRX ) ) {
3288 $this->trxAutomaticAtomic = true;
3289 }
3290 $savepointId = null;
3291 } else {
3292 $savepointId = 'wikimedia_rdbms_atomic' . ++$this->trxAtomicCounter;
3293 if ( strlen( $savepointId ) > 30 ) { // 30 == Oracle's identifier length limit (pre 12c)
3294 $this->queryLogger->warning(
3295 'There have been an excessively large number of atomic sections in a transaction'
3296 . " started by $this->trxFname, reusing IDs (at $fname)",
3297 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
3298 );
3299 $this->trxAtomicCounter = 0;
3300 $savepointId = 'wikimedia_rdbms_atomic' . ++$this->trxAtomicCounter;
3301 }
3302 $this->doSavepoint( $savepointId, $fname );
3303 }
3304
3305 $this->trxAtomicLevels[] = [ $fname, $savepointId ];
3306 }
3307
3308 final public function endAtomic( $fname = __METHOD__ ) {
3309 if ( !$this->trxLevel ) {
3310 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3311 }
3312
3313 list( $savedFname, $savepointId ) = $this->trxAtomicLevels
3314 ? array_pop( $this->trxAtomicLevels ) : [ null, null ];
3315 if ( $savedFname !== $fname ) {
3316 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3317 }
3318
3319 if ( !$savepointId ) {
3320 $this->commit( $fname, self::FLUSHING_INTERNAL );
3321 } else {
3322 $this->doReleaseSavepoint( $savepointId, $fname );
3323 }
3324 }
3325
3326 final public function cancelAtomic( $fname = __METHOD__ ) {
3327 if ( !$this->trxLevel ) {
3328 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3329 }
3330
3331 list( $savedFname, $savepointId ) = $this->trxAtomicLevels
3332 ? array_pop( $this->trxAtomicLevels ) : [ null, null ];
3333 if ( $savedFname !== $fname ) {
3334 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3335 }
3336
3337 if ( !$savepointId ) {
3338 $this->rollback( $fname, self::FLUSHING_INTERNAL );
3339 } else {
3340 $this->doRollbackToSavepoint( $savepointId, $fname );
3341 }
3342
3343 $this->affectedRowCount = 0; // for the sake of consistency
3344 }
3345
3346 final public function doAtomicSection( $fname, callable $callback ) {
3347 $this->startAtomic( $fname );
3348 try {
3349 $res = call_user_func_array( $callback, [ $this, $fname ] );
3350 } catch ( Exception $e ) {
3351 $this->cancelAtomic( $fname );
3352 throw $e;
3353 }
3354 $this->endAtomic( $fname );
3355
3356 return $res;
3357 }
3358
3359 final public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
3360 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3361 if ( $this->trxLevel ) {
3362 if ( $this->trxAtomicLevels ) {
3363 $levels = array_reduce( $this->trxAtomicLevels, function ( $accum, $v ) {
3364 return $accum === null ? $v[0] : "$accum, " . $v[0];
3365 } );
3366 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3367 throw new DBUnexpectedError( $this, $msg );
3368 } elseif ( !$this->trxAutomatic ) {
3369 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3370 throw new DBUnexpectedError( $this, $msg );
3371 } else {
3372 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3373 throw new DBUnexpectedError( $this, $msg );
3374 }
3375 } elseif ( $this->getFlag( self::DBO_TRX ) && $mode !== self::TRANSACTION_INTERNAL ) {
3376 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3377 throw new DBUnexpectedError( $this, $msg );
3378 }
3379
3380 // Avoid fatals if close() was called
3381 $this->assertOpen();
3382
3383 $this->doBegin( $fname );
3384 $this->trxAtomicCounter = 0;
3385 $this->trxTimestamp = microtime( true );
3386 $this->trxFname = $fname;
3387 $this->trxDoneWrites = false;
3388 $this->trxAutomaticAtomic = false;
3389 $this->trxAtomicLevels = [];
3390 $this->trxShortId = sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3391 $this->trxWriteDuration = 0.0;
3392 $this->trxWriteQueryCount = 0;
3393 $this->trxWriteAffectedRows = 0;
3394 $this->trxWriteAdjDuration = 0.0;
3395 $this->trxWriteAdjQueryCount = 0;
3396 $this->trxWriteCallers = [];
3397 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3398 // Get an estimate of the replica DB lag before then, treating estimate staleness
3399 // as lag itself just to be safe
3400 $status = $this->getApproximateLagStatus();
3401 $this->trxReplicaLag = $status['lag'] + ( microtime( true ) - $status['since'] );
3402 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3403 // caller will think its OK to muck around with the transaction just because startAtomic()
3404 // has not yet completed (e.g. setting trxAtomicLevels).
3405 $this->trxAutomatic = ( $mode === self::TRANSACTION_INTERNAL );
3406 }
3407
3408 /**
3409 * Issues the BEGIN command to the database server.
3410 *
3411 * @see Database::begin()
3412 * @param string $fname
3413 */
3414 protected function doBegin( $fname ) {
3415 $this->query( 'BEGIN', $fname );
3416 $this->trxLevel = 1;
3417 }
3418
3419 final public function commit( $fname = __METHOD__, $flush = '' ) {
3420 if ( $this->trxLevel && $this->trxAtomicLevels ) {
3421 // There are still atomic sections open. This cannot be ignored
3422 $levels = array_reduce( $this->trxAtomicLevels, function ( $accum, $v ) {
3423 return $accum === null ? $v[0] : "$accum, " . $v[0];
3424 } );
3425 throw new DBUnexpectedError(
3426 $this,
3427 "$fname: Got COMMIT while atomic sections $levels are still open."
3428 );
3429 }
3430
3431 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
3432 if ( !$this->trxLevel ) {
3433 return; // nothing to do
3434 } elseif ( !$this->trxAutomatic ) {
3435 throw new DBUnexpectedError(
3436 $this,
3437 "$fname: Flushing an explicit transaction, getting out of sync."
3438 );
3439 }
3440 } else {
3441 if ( !$this->trxLevel ) {
3442 $this->queryLogger->error(
3443 "$fname: No transaction to commit, something got out of sync." );
3444 return; // nothing to do
3445 } elseif ( $this->trxAutomatic ) {
3446 throw new DBUnexpectedError(
3447 $this,
3448 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)."
3449 );
3450 }
3451 }
3452
3453 // Avoid fatals if close() was called
3454 $this->assertOpen();
3455
3456 $this->runOnTransactionPreCommitCallbacks();
3457 $writeTime = $this->pendingWriteQueryDuration( self::ESTIMATE_DB_APPLY );
3458 $this->doCommit( $fname );
3459 if ( $this->trxDoneWrites ) {
3460 $this->lastWriteTime = microtime( true );
3461 $this->trxProfiler->transactionWritingOut(
3462 $this->server,
3463 $this->dbName,
3464 $this->trxShortId,
3465 $writeTime,
3466 $this->trxWriteAffectedRows
3467 );
3468 }
3469
3470 $this->runOnTransactionIdleCallbacks( self::TRIGGER_COMMIT );
3471 $this->runTransactionListenerCallbacks( self::TRIGGER_COMMIT );
3472 }
3473
3474 /**
3475 * Issues the COMMIT command to the database server.
3476 *
3477 * @see Database::commit()
3478 * @param string $fname
3479 */
3480 protected function doCommit( $fname ) {
3481 if ( $this->trxLevel ) {
3482 $this->query( 'COMMIT', $fname );
3483 $this->trxLevel = 0;
3484 }
3485 }
3486
3487 final public function rollback( $fname = __METHOD__, $flush = '' ) {
3488 $trxActive = $this->trxLevel;
3489
3490 if ( $flush !== self::FLUSHING_INTERNAL && $flush !== self::FLUSHING_ALL_PEERS ) {
3491 if ( $this->getFlag( self::DBO_TRX ) ) {
3492 throw new DBUnexpectedError(
3493 $this,
3494 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)."
3495 );
3496 }
3497 }
3498
3499 if ( $trxActive ) {
3500 // Avoid fatals if close() was called
3501 $this->assertOpen();
3502
3503 $this->doRollback( $fname );
3504 $this->trxAtomicLevels = [];
3505 if ( $this->trxDoneWrites ) {
3506 $this->trxProfiler->transactionWritingOut(
3507 $this->server,
3508 $this->dbName,
3509 $this->trxShortId
3510 );
3511 }
3512 }
3513
3514 // Clear any commit-dependant callbacks. They might even be present
3515 // only due to transaction rounds, with no SQL transaction being active
3516 $this->trxIdleCallbacks = [];
3517 $this->trxPreCommitCallbacks = [];
3518
3519 if ( $trxActive ) {
3520 try {
3521 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
3522 } catch ( Exception $e ) {
3523 // already logged; finish and let LoadBalancer move on during mass-rollback
3524 }
3525 try {
3526 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
3527 } catch ( Exception $e ) {
3528 // already logged; let LoadBalancer move on during mass-rollback
3529 }
3530
3531 $this->affectedRowCount = 0; // for the sake of consistency
3532 }
3533 }
3534
3535 /**
3536 * Issues the ROLLBACK command to the database server.
3537 *
3538 * @see Database::rollback()
3539 * @param string $fname
3540 */
3541 protected function doRollback( $fname ) {
3542 if ( $this->trxLevel ) {
3543 # Disconnects cause rollback anyway, so ignore those errors
3544 $ignoreErrors = true;
3545 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3546 $this->trxLevel = 0;
3547 }
3548 }
3549
3550 public function flushSnapshot( $fname = __METHOD__ ) {
3551 if ( $this->writesOrCallbacksPending() || $this->explicitTrxActive() ) {
3552 // This only flushes transactions to clear snapshots, not to write data
3553 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3554 throw new DBUnexpectedError(
3555 $this,
3556 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3557 );
3558 }
3559
3560 $this->commit( $fname, self::FLUSHING_INTERNAL );
3561 }
3562
3563 public function explicitTrxActive() {
3564 return $this->trxLevel && ( $this->trxAtomicLevels || !$this->trxAutomatic );
3565 }
3566
3567 public function duplicateTableStructure(
3568 $oldName, $newName, $temporary = false, $fname = __METHOD__
3569 ) {
3570 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3571 }
3572
3573 public function listTables( $prefix = null, $fname = __METHOD__ ) {
3574 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3575 }
3576
3577 public function listViews( $prefix = null, $fname = __METHOD__ ) {
3578 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3579 }
3580
3581 public function timestamp( $ts = 0 ) {
3582 $t = new ConvertibleTimestamp( $ts );
3583 // Let errors bubble up to avoid putting garbage in the DB
3584 return $t->getTimestamp( TS_MW );
3585 }
3586
3587 public function timestampOrNull( $ts = null ) {
3588 if ( is_null( $ts ) ) {
3589 return null;
3590 } else {
3591 return $this->timestamp( $ts );
3592 }
3593 }
3594
3595 public function affectedRows() {
3596 return ( $this->affectedRowCount === null )
3597 ? $this->fetchAffectedRowCount() // default to driver value
3598 : $this->affectedRowCount;
3599 }
3600
3601 /**
3602 * @return int Number of retrieved rows according to the driver
3603 */
3604 abstract protected function fetchAffectedRowCount();
3605
3606 /**
3607 * Take the result from a query, and wrap it in a ResultWrapper if
3608 * necessary. Boolean values are passed through as is, to indicate success
3609 * of write queries or failure.
3610 *
3611 * Once upon a time, Database::query() returned a bare MySQL result
3612 * resource, and it was necessary to call this function to convert it to
3613 * a wrapper. Nowadays, raw database objects are never exposed to external
3614 * callers, so this is unnecessary in external code.
3615 *
3616 * @param bool|ResultWrapper|resource|object $result
3617 * @return bool|ResultWrapper
3618 */
3619 protected function resultObject( $result ) {
3620 if ( !$result ) {
3621 return false;
3622 } elseif ( $result instanceof ResultWrapper ) {
3623 return $result;
3624 } elseif ( $result === true ) {
3625 // Successful write query
3626 return $result;
3627 } else {
3628 return new ResultWrapper( $this, $result );
3629 }
3630 }
3631
3632 public function ping( &$rtt = null ) {
3633 // Avoid hitting the server if it was hit recently
3634 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing ) < self::PING_TTL ) {
3635 if ( !func_num_args() || $this->rttEstimate > 0 ) {
3636 $rtt = $this->rttEstimate;
3637 return true; // don't care about $rtt
3638 }
3639 }
3640
3641 // This will reconnect if possible or return false if not
3642 $this->clearFlag( self::DBO_TRX, self::REMEMBER_PRIOR );
3643 $ok = ( $this->query( self::PING_QUERY, __METHOD__, true ) !== false );
3644 $this->restoreFlags( self::RESTORE_PRIOR );
3645
3646 if ( $ok ) {
3647 $rtt = $this->rttEstimate;
3648 }
3649
3650 return $ok;
3651 }
3652
3653 /**
3654 * Close existing database connection and open a new connection
3655 *
3656 * @return bool True if new connection is opened successfully, false if error
3657 */
3658 protected function reconnect() {
3659 $this->closeConnection();
3660 $this->opened = false;
3661 $this->conn = false;
3662 try {
3663 $this->open( $this->server, $this->user, $this->password, $this->dbName );
3664 $this->lastPing = microtime( true );
3665 $ok = true;
3666 } catch ( DBConnectionError $e ) {
3667 $ok = false;
3668 }
3669
3670 return $ok;
3671 }
3672
3673 public function getSessionLagStatus() {
3674 return $this->getTransactionLagStatus() ?: $this->getApproximateLagStatus();
3675 }
3676
3677 /**
3678 * Get the replica DB lag when the current transaction started
3679 *
3680 * This is useful when transactions might use snapshot isolation
3681 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3682 * is this lag plus transaction duration. If they don't, it is still
3683 * safe to be pessimistic. This returns null if there is no transaction.
3684 *
3685 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3686 * @since 1.27
3687 */
3688 protected function getTransactionLagStatus() {
3689 return $this->trxLevel
3690 ? [ 'lag' => $this->trxReplicaLag, 'since' => $this->trxTimestamp() ]
3691 : null;
3692 }
3693
3694 /**
3695 * Get a replica DB lag estimate for this server
3696 *
3697 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3698 * @since 1.27
3699 */
3700 protected function getApproximateLagStatus() {
3701 return [
3702 'lag' => $this->getLBInfo( 'replica' ) ? $this->getLag() : 0,
3703 'since' => microtime( true )
3704 ];
3705 }
3706
3707 /**
3708 * Merge the result of getSessionLagStatus() for several DBs
3709 * using the most pessimistic values to estimate the lag of
3710 * any data derived from them in combination
3711 *
3712 * This is information is useful for caching modules
3713 *
3714 * @see WANObjectCache::set()
3715 * @see WANObjectCache::getWithSetCallback()
3716 *
3717 * @param IDatabase $db1
3718 * @param IDatabase $db2 [optional]
3719 * @return array Map of values:
3720 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3721 * - since: oldest UNIX timestamp of any of the DB lag estimates
3722 * - pending: whether any of the DBs have uncommitted changes
3723 * @throws DBError
3724 * @since 1.27
3725 */
3726 public static function getCacheSetOptions( IDatabase $db1, IDatabase $db2 = null ) {
3727 $res = [ 'lag' => 0, 'since' => INF, 'pending' => false ];
3728 foreach ( func_get_args() as $db ) {
3729 /** @var IDatabase $db */
3730 $status = $db->getSessionLagStatus();
3731 if ( $status['lag'] === false ) {
3732 $res['lag'] = false;
3733 } elseif ( $res['lag'] !== false ) {
3734 $res['lag'] = max( $res['lag'], $status['lag'] );
3735 }
3736 $res['since'] = min( $res['since'], $status['since'] );
3737 $res['pending'] = $res['pending'] ?: $db->writesPending();
3738 }
3739
3740 return $res;
3741 }
3742
3743 public function getLag() {
3744 return 0;
3745 }
3746
3747 public function maxListLen() {
3748 return 0;
3749 }
3750
3751 public function encodeBlob( $b ) {
3752 return $b;
3753 }
3754
3755 public function decodeBlob( $b ) {
3756 if ( $b instanceof Blob ) {
3757 $b = $b->fetch();
3758 }
3759 return $b;
3760 }
3761
3762 public function setSessionOptions( array $options ) {
3763 }
3764
3765 public function sourceFile(
3766 $filename,
3767 callable $lineCallback = null,
3768 callable $resultCallback = null,
3769 $fname = false,
3770 callable $inputCallback = null
3771 ) {
3772 Wikimedia\suppressWarnings();
3773 $fp = fopen( $filename, 'r' );
3774 Wikimedia\restoreWarnings();
3775
3776 if ( false === $fp ) {
3777 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3778 }
3779
3780 if ( !$fname ) {
3781 $fname = __METHOD__ . "( $filename )";
3782 }
3783
3784 try {
3785 $error = $this->sourceStream(
3786 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3787 } catch ( Exception $e ) {
3788 fclose( $fp );
3789 throw $e;
3790 }
3791
3792 fclose( $fp );
3793
3794 return $error;
3795 }
3796
3797 public function setSchemaVars( $vars ) {
3798 $this->schemaVars = $vars;
3799 }
3800
3801 public function sourceStream(
3802 $fp,
3803 callable $lineCallback = null,
3804 callable $resultCallback = null,
3805 $fname = __METHOD__,
3806 callable $inputCallback = null
3807 ) {
3808 $delimiterReset = new ScopedCallback(
3809 function ( $delimiter ) {
3810 $this->delimiter = $delimiter;
3811 },
3812 [ $this->delimiter ]
3813 );
3814 $cmd = '';
3815
3816 while ( !feof( $fp ) ) {
3817 if ( $lineCallback ) {
3818 call_user_func( $lineCallback );
3819 }
3820
3821 $line = trim( fgets( $fp ) );
3822
3823 if ( $line == '' ) {
3824 continue;
3825 }
3826
3827 if ( '-' == $line[0] && '-' == $line[1] ) {
3828 continue;
3829 }
3830
3831 if ( $cmd != '' ) {
3832 $cmd .= ' ';
3833 }
3834
3835 $done = $this->streamStatementEnd( $cmd, $line );
3836
3837 $cmd .= "$line\n";
3838
3839 if ( $done || feof( $fp ) ) {
3840 $cmd = $this->replaceVars( $cmd );
3841
3842 if ( $inputCallback ) {
3843 $callbackResult = call_user_func( $inputCallback, $cmd );
3844
3845 if ( is_string( $callbackResult ) || !$callbackResult ) {
3846 $cmd = $callbackResult;
3847 }
3848 }
3849
3850 if ( $cmd ) {
3851 $res = $this->query( $cmd, $fname );
3852
3853 if ( $resultCallback ) {
3854 call_user_func( $resultCallback, $res, $this );
3855 }
3856
3857 if ( false === $res ) {
3858 $err = $this->lastError();
3859
3860 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3861 }
3862 }
3863 $cmd = '';
3864 }
3865 }
3866
3867 ScopedCallback::consume( $delimiterReset );
3868 return true;
3869 }
3870
3871 /**
3872 * Called by sourceStream() to check if we've reached a statement end
3873 *
3874 * @param string &$sql SQL assembled so far
3875 * @param string &$newLine New line about to be added to $sql
3876 * @return bool Whether $newLine contains end of the statement
3877 */
3878 public function streamStatementEnd( &$sql, &$newLine ) {
3879 if ( $this->delimiter ) {
3880 $prev = $newLine;
3881 $newLine = preg_replace(
3882 '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
3883 if ( $newLine != $prev ) {
3884 return true;
3885 }
3886 }
3887
3888 return false;
3889 }
3890
3891 /**
3892 * Database independent variable replacement. Replaces a set of variables
3893 * in an SQL statement with their contents as given by $this->getSchemaVars().
3894 *
3895 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3896 *
3897 * - '{$var}' should be used for text and is passed through the database's
3898 * addQuotes method.
3899 * - `{$var}` should be used for identifiers (e.g. table and database names).
3900 * It is passed through the database's addIdentifierQuotes method which
3901 * can be overridden if the database uses something other than backticks.
3902 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3903 * database's tableName method.
3904 * - / *i* / passes the name that follows through the database's indexName method.
3905 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3906 * its use should be avoided. In 1.24 and older, string encoding was applied.
3907 *
3908 * @param string $ins SQL statement to replace variables in
3909 * @return string The new SQL statement with variables replaced
3910 */
3911 protected function replaceVars( $ins ) {
3912 $vars = $this->getSchemaVars();
3913 return preg_replace_callback(
3914 '!
3915 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3916 \'\{\$ (\w+) }\' | # 3. addQuotes
3917 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3918 /\*\$ (\w+) \*/ # 5. leave unencoded
3919 !x',
3920 function ( $m ) use ( $vars ) {
3921 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3922 // check for both nonexistent keys *and* the empty string.
3923 if ( isset( $m[1] ) && $m[1] !== '' ) {
3924 if ( $m[1] === 'i' ) {
3925 return $this->indexName( $m[2] );
3926 } else {
3927 return $this->tableName( $m[2] );
3928 }
3929 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3930 return $this->addQuotes( $vars[$m[3]] );
3931 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3932 return $this->addIdentifierQuotes( $vars[$m[4]] );
3933 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3934 return $vars[$m[5]];
3935 } else {
3936 return $m[0];
3937 }
3938 },
3939 $ins
3940 );
3941 }
3942
3943 /**
3944 * Get schema variables. If none have been set via setSchemaVars(), then
3945 * use some defaults from the current object.
3946 *
3947 * @return array
3948 */
3949 protected function getSchemaVars() {
3950 if ( $this->schemaVars ) {
3951 return $this->schemaVars;
3952 } else {
3953 return $this->getDefaultSchemaVars();
3954 }
3955 }
3956
3957 /**
3958 * Get schema variables to use if none have been set via setSchemaVars().
3959 *
3960 * Override this in derived classes to provide variables for tables.sql
3961 * and SQL patch files.
3962 *
3963 * @return array
3964 */
3965 protected function getDefaultSchemaVars() {
3966 return [];
3967 }
3968
3969 public function lockIsFree( $lockName, $method ) {
3970 // RDBMs methods for checking named locks may or may not count this thread itself.
3971 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
3972 // the behavior choosen by the interface for this method.
3973 return !isset( $this->namedLocksHeld[$lockName] );
3974 }
3975
3976 public function lock( $lockName, $method, $timeout = 5 ) {
3977 $this->namedLocksHeld[$lockName] = 1;
3978
3979 return true;
3980 }
3981
3982 public function unlock( $lockName, $method ) {
3983 unset( $this->namedLocksHeld[$lockName] );
3984
3985 return true;
3986 }
3987
3988 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3989 if ( $this->writesOrCallbacksPending() ) {
3990 // This only flushes transactions to clear snapshots, not to write data
3991 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3992 throw new DBUnexpectedError(
3993 $this,
3994 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3995 );
3996 }
3997
3998 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3999 return null;
4000 }
4001
4002 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
4003 if ( $this->trxLevel() ) {
4004 // There is a good chance an exception was thrown, causing any early return
4005 // from the caller. Let any error handler get a chance to issue rollback().
4006 // If there isn't one, let the error bubble up and trigger server-side rollback.
4007 $this->onTransactionResolution(
4008 function () use ( $lockKey, $fname ) {
4009 $this->unlock( $lockKey, $fname );
4010 },
4011 $fname
4012 );
4013 } else {
4014 $this->unlock( $lockKey, $fname );
4015 }
4016 } );
4017
4018 $this->commit( $fname, self::FLUSHING_INTERNAL );
4019
4020 return $unlocker;
4021 }
4022
4023 public function namedLocksEnqueue() {
4024 return false;
4025 }
4026
4027 public function tableLocksHaveTransactionScope() {
4028 return true;
4029 }
4030
4031 final public function lockTables( array $read, array $write, $method ) {
4032 if ( $this->writesOrCallbacksPending() ) {
4033 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
4034 }
4035
4036 if ( $this->tableLocksHaveTransactionScope() ) {
4037 $this->startAtomic( $method );
4038 }
4039
4040 return $this->doLockTables( $read, $write, $method );
4041 }
4042
4043 /**
4044 * Helper function for lockTables() that handles the actual table locking
4045 *
4046 * @param array $read Array of tables to lock for read access
4047 * @param array $write Array of tables to lock for write access
4048 * @param string $method Name of caller
4049 * @return true
4050 */
4051 protected function doLockTables( array $read, array $write, $method ) {
4052 return true;
4053 }
4054
4055 final public function unlockTables( $method ) {
4056 if ( $this->tableLocksHaveTransactionScope() ) {
4057 $this->endAtomic( $method );
4058
4059 return true; // locks released on COMMIT/ROLLBACK
4060 }
4061
4062 return $this->doUnlockTables( $method );
4063 }
4064
4065 /**
4066 * Helper function for unlockTables() that handles the actual table unlocking
4067 *
4068 * @param string $method Name of caller
4069 * @return true
4070 */
4071 protected function doUnlockTables( $method ) {
4072 return true;
4073 }
4074
4075 /**
4076 * Delete a table
4077 * @param string $tableName
4078 * @param string $fName
4079 * @return bool|ResultWrapper
4080 * @since 1.18
4081 */
4082 public function dropTable( $tableName, $fName = __METHOD__ ) {
4083 if ( !$this->tableExists( $tableName, $fName ) ) {
4084 return false;
4085 }
4086 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
4087
4088 return $this->query( $sql, $fName );
4089 }
4090
4091 public function getInfinity() {
4092 return 'infinity';
4093 }
4094
4095 public function encodeExpiry( $expiry ) {
4096 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4097 ? $this->getInfinity()
4098 : $this->timestamp( $expiry );
4099 }
4100
4101 public function decodeExpiry( $expiry, $format = TS_MW ) {
4102 if ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() ) {
4103 return 'infinity';
4104 }
4105
4106 return ConvertibleTimestamp::convert( $format, $expiry );
4107 }
4108
4109 public function setBigSelects( $value = true ) {
4110 // no-op
4111 }
4112
4113 public function isReadOnly() {
4114 return ( $this->getReadOnlyReason() !== false );
4115 }
4116
4117 /**
4118 * @return string|bool Reason this DB is read-only or false if it is not
4119 */
4120 protected function getReadOnlyReason() {
4121 $reason = $this->getLBInfo( 'readOnlyReason' );
4122
4123 return is_string( $reason ) ? $reason : false;
4124 }
4125
4126 public function setTableAliases( array $aliases ) {
4127 $this->tableAliases = $aliases;
4128 }
4129
4130 public function setIndexAliases( array $aliases ) {
4131 $this->indexAliases = $aliases;
4132 }
4133
4134 /**
4135 * Get the underlying binding connection handle
4136 *
4137 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
4138 * This catches broken callers than catch and ignore disconnection exceptions.
4139 * Unlike checking isOpen(), this is safe to call inside of open().
4140 *
4141 * @return mixed
4142 * @throws DBUnexpectedError
4143 * @since 1.26
4144 */
4145 protected function getBindingHandle() {
4146 if ( !$this->conn ) {
4147 throw new DBUnexpectedError(
4148 $this,
4149 'DB connection was already closed or the connection dropped.'
4150 );
4151 }
4152
4153 return $this->conn;
4154 }
4155
4156 /**
4157 * @since 1.19
4158 * @return string
4159 */
4160 public function __toString() {
4161 return (string)$this->conn;
4162 }
4163
4164 /**
4165 * Make sure that copies do not share the same client binding handle
4166 * @throws DBConnectionError
4167 */
4168 public function __clone() {
4169 $this->connLogger->warning(
4170 "Cloning " . static::class . " is not recomended; forking connection:\n" .
4171 ( new RuntimeException() )->getTraceAsString()
4172 );
4173
4174 if ( $this->isOpen() ) {
4175 // Open a new connection resource without messing with the old one
4176 $this->opened = false;
4177 $this->conn = false;
4178 $this->trxEndCallbacks = []; // don't copy
4179 $this->handleSessionLoss(); // no trx or locks anymore
4180 $this->open( $this->server, $this->user, $this->password, $this->dbName );
4181 $this->lastPing = microtime( true );
4182 }
4183 }
4184
4185 /**
4186 * Called by serialize. Throw an exception when DB connection is serialized.
4187 * This causes problems on some database engines because the connection is
4188 * not restored on unserialize.
4189 */
4190 public function __sleep() {
4191 throw new RuntimeException( 'Database serialization may cause problems, since ' .
4192 'the connection is not restored on wakeup.' );
4193 }
4194
4195 /**
4196 * Run a few simple sanity checks and close dangling connections
4197 */
4198 public function __destruct() {
4199 if ( $this->trxLevel && $this->trxDoneWrites ) {
4200 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})." );
4201 }
4202
4203 $danglingWriters = $this->pendingWriteAndCallbackCallers();
4204 if ( $danglingWriters ) {
4205 $fnames = implode( ', ', $danglingWriters );
4206 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
4207 }
4208
4209 if ( $this->conn ) {
4210 // Avoid connection leaks for sanity. Normally, resources close at script completion.
4211 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4212 Wikimedia\suppressWarnings();
4213 $this->closeConnection();
4214 Wikimedia\restoreWarnings();
4215 $this->conn = false;
4216 $this->opened = false;
4217 }
4218 }
4219 }
4220
4221 class_alias( Database::class, 'DatabaseBase' ); // b/c for old name
4222 class_alias( Database::class, 'Database' ); // b/c global alias