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