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