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