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