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