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