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