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