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