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