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