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