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