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