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