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