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