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