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