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