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