Merge "Avoid postgres CategoryMembershipChangeTest failures"
[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 TEMPORARY table operation
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 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
842 $sql,
843 $matches
844 ) ) {
845 return isset( $this->mSessionTempTables[$matches[1]] );
846 } elseif ( preg_match(
847 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
848 $sql,
849 $matches
850 ) ) {
851 return isset( $this->mSessionTempTables[$matches[1]] );
852 }
853
854 return false;
855 }
856
857 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
858 $priorWritesPending = $this->writesOrCallbacksPending();
859 $this->mLastQuery = $sql;
860
861 $isWrite = $this->isWriteQuery( $sql );
862 if ( $isWrite ) {
863 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
864 } else {
865 $isNonTempWrite = false;
866 }
867
868 if ( $isWrite ) {
869 # In theory, non-persistent writes are allowed in read-only mode, but due to things
870 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
871 $reason = $this->getReadOnlyReason();
872 if ( $reason !== false ) {
873 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
874 }
875 # Set a flag indicating that writes have been done
876 $this->mLastWriteTime = microtime( true );
877 }
878
879 # Add trace comment to the begin of the sql string, right after the operator.
880 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
881 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
882
883 # Start implicit transactions that wrap the request if DBO_TRX is enabled
884 if ( !$this->mTrxLevel && $this->getFlag( self::DBO_TRX )
885 && $this->isTransactableQuery( $sql )
886 ) {
887 $this->begin( __METHOD__ . " ($fname)", self::TRANSACTION_INTERNAL );
888 $this->mTrxAutomatic = true;
889 }
890
891 # Keep track of whether the transaction has write queries pending
892 if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $isWrite ) {
893 $this->mTrxDoneWrites = true;
894 $this->trxProfiler->transactionWritingIn(
895 $this->mServer, $this->mDBname, $this->mTrxShortId );
896 }
897
898 if ( $this->getFlag( self::DBO_DEBUG ) ) {
899 $this->queryLogger->debug( "{$this->mDBname} {$commentedSql}" );
900 }
901
902 # Avoid fatals if close() was called
903 $this->assertOpen();
904
905 # Send the query to the server
906 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
907
908 # Try reconnecting if the connection was lost
909 if ( false === $ret && $this->wasErrorReissuable() ) {
910 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
911 # Stash the last error values before anything might clear them
912 $lastError = $this->lastError();
913 $lastErrno = $this->lastErrno();
914 # Update state tracking to reflect transaction loss due to disconnection
915 $this->handleSessionLoss();
916 if ( $this->reconnect() ) {
917 $msg = __METHOD__ . ": lost connection to {$this->getServer()}; reconnected";
918 $this->connLogger->warning( $msg );
919 $this->queryLogger->warning(
920 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
921
922 if ( !$recoverable ) {
923 # Callers may catch the exception and continue to use the DB
924 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
925 } else {
926 # Should be safe to silently retry the query
927 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
928 }
929 } else {
930 $msg = __METHOD__ . ": lost connection to {$this->getServer()} permanently";
931 $this->connLogger->error( $msg );
932 }
933 }
934
935 if ( false === $ret ) {
936 # Deadlocks cause the entire transaction to abort, not just the statement.
937 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
938 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
939 if ( $this->wasDeadlock() ) {
940 if ( $this->explicitTrxActive() || $priorWritesPending ) {
941 $tempIgnore = false; // not recoverable
942 }
943 # Update state tracking to reflect transaction loss
944 $this->handleSessionLoss();
945 }
946
947 $this->reportQueryError(
948 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
949 }
950
951 $res = $this->resultObject( $ret );
952
953 return $res;
954 }
955
956 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
957 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
958 # generalizeSQL() will probably cut down the query to reasonable
959 # logging size most of the time. The substr is really just a sanity check.
960 if ( $isMaster ) {
961 $queryProf = 'query-m: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
962 } else {
963 $queryProf = 'query: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
964 }
965
966 # Include query transaction state
967 $queryProf .= $this->mTrxShortId ? " [TRX#{$this->mTrxShortId}]" : "";
968
969 $startTime = microtime( true );
970 if ( $this->profiler ) {
971 call_user_func( [ $this->profiler, 'profileIn' ], $queryProf );
972 }
973 $ret = $this->doQuery( $commentedSql );
974 if ( $this->profiler ) {
975 call_user_func( [ $this->profiler, 'profileOut' ], $queryProf );
976 }
977 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
978
979 unset( $queryProfSection ); // profile out (if set)
980
981 if ( $ret !== false ) {
982 $this->lastPing = $startTime;
983 if ( $isWrite && $this->mTrxLevel ) {
984 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
985 $this->mTrxWriteCallers[] = $fname;
986 }
987 }
988
989 if ( $sql === self::PING_QUERY ) {
990 $this->mRTTEstimate = $queryRuntime;
991 }
992
993 $this->trxProfiler->recordQueryCompletion(
994 $queryProf, $startTime, $isWrite, $this->affectedRows()
995 );
996 $this->queryLogger->debug( $sql, [
997 'method' => $fname,
998 'master' => $isMaster,
999 'runtime' => $queryRuntime,
1000 ] );
1001
1002 return $ret;
1003 }
1004
1005 /**
1006 * Update the estimated run-time of a query, not counting large row lock times
1007 *
1008 * LoadBalancer can be set to rollback transactions that will create huge replication
1009 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1010 * queries, like inserting a row can take a long time due to row locking. This method
1011 * uses some simple heuristics to discount those cases.
1012 *
1013 * @param string $sql A SQL write query
1014 * @param float $runtime Total runtime, including RTT
1015 */
1016 private function updateTrxWriteQueryTime( $sql, $runtime ) {
1017 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1018 $indicativeOfReplicaRuntime = true;
1019 if ( $runtime > self::SLOW_WRITE_SEC ) {
1020 $verb = $this->getQueryVerb( $sql );
1021 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1022 if ( $verb === 'INSERT' ) {
1023 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS;
1024 } elseif ( $verb === 'REPLACE' ) {
1025 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS / 2;
1026 }
1027 }
1028
1029 $this->mTrxWriteDuration += $runtime;
1030 $this->mTrxWriteQueryCount += 1;
1031 if ( $indicativeOfReplicaRuntime ) {
1032 $this->mTrxWriteAdjDuration += $runtime;
1033 $this->mTrxWriteAdjQueryCount += 1;
1034 }
1035 }
1036
1037 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1038 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1039 # Dropped connections also mean that named locks are automatically released.
1040 # Only allow error suppression in autocommit mode or when the lost transaction
1041 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1042 if ( $this->mNamedLocksHeld ) {
1043 return false; // possible critical section violation
1044 } elseif ( $sql === 'COMMIT' ) {
1045 return !$priorWritesPending; // nothing written anyway? (T127428)
1046 } elseif ( $sql === 'ROLLBACK' ) {
1047 return true; // transaction lost...which is also what was requested :)
1048 } elseif ( $this->explicitTrxActive() ) {
1049 return false; // don't drop atomocity
1050 } elseif ( $priorWritesPending ) {
1051 return false; // prior writes lost from implicit transaction
1052 }
1053
1054 return true;
1055 }
1056
1057 private function handleSessionLoss() {
1058 $this->mTrxLevel = 0;
1059 $this->mTrxIdleCallbacks = []; // T67263
1060 $this->mTrxPreCommitCallbacks = []; // T67263
1061 $this->mSessionTempTables = [];
1062 $this->mNamedLocksHeld = [];
1063 try {
1064 // Handle callbacks in mTrxEndCallbacks
1065 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
1066 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
1067 return null;
1068 } catch ( Exception $e ) {
1069 // Already logged; move on...
1070 return $e;
1071 }
1072 }
1073
1074 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1075 if ( $this->ignoreErrors() || $tempIgnore ) {
1076 $this->queryLogger->debug( "SQL ERROR (ignored): $error\n" );
1077 } else {
1078 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1079 $this->queryLogger->error(
1080 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1081 $this->getLogContext( [
1082 'method' => __METHOD__,
1083 'errno' => $errno,
1084 'error' => $error,
1085 'sql1line' => $sql1line,
1086 'fname' => $fname,
1087 ] )
1088 );
1089 $this->queryLogger->debug( "SQL ERROR: " . $error . "\n" );
1090 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1091 }
1092 }
1093
1094 public function freeResult( $res ) {
1095 }
1096
1097 public function selectField(
1098 $table, $var, $cond = '', $fname = __METHOD__, $options = []
1099 ) {
1100 if ( $var === '*' ) { // sanity
1101 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1102 }
1103
1104 if ( !is_array( $options ) ) {
1105 $options = [ $options ];
1106 }
1107
1108 $options['LIMIT'] = 1;
1109
1110 $res = $this->select( $table, $var, $cond, $fname, $options );
1111 if ( $res === false || !$this->numRows( $res ) ) {
1112 return false;
1113 }
1114
1115 $row = $this->fetchRow( $res );
1116
1117 if ( $row !== false ) {
1118 return reset( $row );
1119 } else {
1120 return false;
1121 }
1122 }
1123
1124 public function selectFieldValues(
1125 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1126 ) {
1127 if ( $var === '*' ) { // sanity
1128 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1129 } elseif ( !is_string( $var ) ) { // sanity
1130 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1131 }
1132
1133 if ( !is_array( $options ) ) {
1134 $options = [ $options ];
1135 }
1136
1137 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1138 if ( $res === false ) {
1139 return false;
1140 }
1141
1142 $values = [];
1143 foreach ( $res as $row ) {
1144 $values[] = $row->$var;
1145 }
1146
1147 return $values;
1148 }
1149
1150 /**
1151 * Returns an optional USE INDEX clause to go after the table, and a
1152 * string to go at the end of the query.
1153 *
1154 * @param array $options Associative array of options to be turned into
1155 * an SQL query, valid keys are listed in the function.
1156 * @return array
1157 * @see Database::select()
1158 */
1159 protected function makeSelectOptions( $options ) {
1160 $preLimitTail = $postLimitTail = '';
1161 $startOpts = '';
1162
1163 $noKeyOptions = [];
1164
1165 foreach ( $options as $key => $option ) {
1166 if ( is_numeric( $key ) ) {
1167 $noKeyOptions[$option] = true;
1168 }
1169 }
1170
1171 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1172
1173 $preLimitTail .= $this->makeOrderBy( $options );
1174
1175 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1176 $postLimitTail .= ' FOR UPDATE';
1177 }
1178
1179 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1180 $postLimitTail .= ' LOCK IN SHARE MODE';
1181 }
1182
1183 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1184 $startOpts .= 'DISTINCT';
1185 }
1186
1187 # Various MySQL extensions
1188 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1189 $startOpts .= ' /*! STRAIGHT_JOIN */';
1190 }
1191
1192 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1193 $startOpts .= ' HIGH_PRIORITY';
1194 }
1195
1196 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1197 $startOpts .= ' SQL_BIG_RESULT';
1198 }
1199
1200 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1201 $startOpts .= ' SQL_BUFFER_RESULT';
1202 }
1203
1204 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1205 $startOpts .= ' SQL_SMALL_RESULT';
1206 }
1207
1208 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1209 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1210 }
1211
1212 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1213 $startOpts .= ' SQL_CACHE';
1214 }
1215
1216 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1217 $startOpts .= ' SQL_NO_CACHE';
1218 }
1219
1220 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1221 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1222 } else {
1223 $useIndex = '';
1224 }
1225 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1226 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1227 } else {
1228 $ignoreIndex = '';
1229 }
1230
1231 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1232 }
1233
1234 /**
1235 * Returns an optional GROUP BY with an optional HAVING
1236 *
1237 * @param array $options Associative array of options
1238 * @return string
1239 * @see Database::select()
1240 * @since 1.21
1241 */
1242 protected function makeGroupByWithHaving( $options ) {
1243 $sql = '';
1244 if ( isset( $options['GROUP BY'] ) ) {
1245 $gb = is_array( $options['GROUP BY'] )
1246 ? implode( ',', $options['GROUP BY'] )
1247 : $options['GROUP BY'];
1248 $sql .= ' GROUP BY ' . $gb;
1249 }
1250 if ( isset( $options['HAVING'] ) ) {
1251 $having = is_array( $options['HAVING'] )
1252 ? $this->makeList( $options['HAVING'], self::LIST_AND )
1253 : $options['HAVING'];
1254 $sql .= ' HAVING ' . $having;
1255 }
1256
1257 return $sql;
1258 }
1259
1260 /**
1261 * Returns an optional ORDER BY
1262 *
1263 * @param array $options Associative array of options
1264 * @return string
1265 * @see Database::select()
1266 * @since 1.21
1267 */
1268 protected function makeOrderBy( $options ) {
1269 if ( isset( $options['ORDER BY'] ) ) {
1270 $ob = is_array( $options['ORDER BY'] )
1271 ? implode( ',', $options['ORDER BY'] )
1272 : $options['ORDER BY'];
1273
1274 return ' ORDER BY ' . $ob;
1275 }
1276
1277 return '';
1278 }
1279
1280 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1281 $options = [], $join_conds = [] ) {
1282 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1283
1284 return $this->query( $sql, $fname );
1285 }
1286
1287 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1288 $options = [], $join_conds = []
1289 ) {
1290 if ( is_array( $vars ) ) {
1291 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1292 }
1293
1294 $options = (array)$options;
1295 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1296 ? $options['USE INDEX']
1297 : [];
1298 $ignoreIndexes = (
1299 isset( $options['IGNORE INDEX'] ) &&
1300 is_array( $options['IGNORE INDEX'] )
1301 )
1302 ? $options['IGNORE INDEX']
1303 : [];
1304
1305 if ( is_array( $table ) ) {
1306 $from = ' FROM ' .
1307 $this->tableNamesWithIndexClauseOrJOIN(
1308 $table, $useIndexes, $ignoreIndexes, $join_conds );
1309 } elseif ( $table != '' ) {
1310 if ( $table[0] == ' ' ) {
1311 $from = ' FROM ' . $table;
1312 } else {
1313 $from = ' FROM ' .
1314 $this->tableNamesWithIndexClauseOrJOIN(
1315 [ $table ], $useIndexes, $ignoreIndexes, [] );
1316 }
1317 } else {
1318 $from = '';
1319 }
1320
1321 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1322 $this->makeSelectOptions( $options );
1323
1324 if ( !empty( $conds ) ) {
1325 if ( is_array( $conds ) ) {
1326 $conds = $this->makeList( $conds, self::LIST_AND );
1327 }
1328 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1329 "WHERE $conds $preLimitTail";
1330 } else {
1331 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1332 }
1333
1334 if ( isset( $options['LIMIT'] ) ) {
1335 $sql = $this->limitResult( $sql, $options['LIMIT'],
1336 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1337 }
1338 $sql = "$sql $postLimitTail";
1339
1340 if ( isset( $options['EXPLAIN'] ) ) {
1341 $sql = 'EXPLAIN ' . $sql;
1342 }
1343
1344 return $sql;
1345 }
1346
1347 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1348 $options = [], $join_conds = []
1349 ) {
1350 $options = (array)$options;
1351 $options['LIMIT'] = 1;
1352 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1353
1354 if ( $res === false ) {
1355 return false;
1356 }
1357
1358 if ( !$this->numRows( $res ) ) {
1359 return false;
1360 }
1361
1362 $obj = $this->fetchObject( $res );
1363
1364 return $obj;
1365 }
1366
1367 public function estimateRowCount(
1368 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = []
1369 ) {
1370 $rows = 0;
1371 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1372
1373 if ( $res ) {
1374 $row = $this->fetchRow( $res );
1375 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1376 }
1377
1378 return $rows;
1379 }
1380
1381 public function selectRowCount(
1382 $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1383 ) {
1384 $rows = 0;
1385 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1386 // The identifier quotes is primarily for MSSQL.
1387 $rowCountCol = $this->addIdentifierQuotes( "rowcount" );
1388 $tableName = $this->addIdentifierQuotes( "tmp_count" );
1389 $res = $this->query( "SELECT COUNT(*) AS $rowCountCol FROM ($sql) $tableName", $fname );
1390
1391 if ( $res ) {
1392 $row = $this->fetchRow( $res );
1393 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1394 }
1395
1396 return $rows;
1397 }
1398
1399 /**
1400 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1401 * It's only slightly flawed. Don't use for anything important.
1402 *
1403 * @param string $sql A SQL Query
1404 *
1405 * @return string
1406 */
1407 protected static function generalizeSQL( $sql ) {
1408 # This does the same as the regexp below would do, but in such a way
1409 # as to avoid crashing php on some large strings.
1410 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1411
1412 $sql = str_replace( "\\\\", '', $sql );
1413 $sql = str_replace( "\\'", '', $sql );
1414 $sql = str_replace( "\\\"", '', $sql );
1415 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1416 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1417
1418 # All newlines, tabs, etc replaced by single space
1419 $sql = preg_replace( '/\s+/', ' ', $sql );
1420
1421 # All numbers => N,
1422 # except the ones surrounded by characters, e.g. l10n
1423 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1424 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1425
1426 return $sql;
1427 }
1428
1429 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1430 $info = $this->fieldInfo( $table, $field );
1431
1432 return (bool)$info;
1433 }
1434
1435 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1436 if ( !$this->tableExists( $table ) ) {
1437 return null;
1438 }
1439
1440 $info = $this->indexInfo( $table, $index, $fname );
1441 if ( is_null( $info ) ) {
1442 return null;
1443 } else {
1444 return $info !== false;
1445 }
1446 }
1447
1448 public function tableExists( $table, $fname = __METHOD__ ) {
1449 $tableRaw = $this->tableName( $table, 'raw' );
1450 if ( isset( $this->mSessionTempTables[$tableRaw] ) ) {
1451 return true; // already known to exist
1452 }
1453
1454 $table = $this->tableName( $table );
1455 $ignoreErrors = true;
1456 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1457
1458 return (bool)$res;
1459 }
1460
1461 public function indexUnique( $table, $index ) {
1462 $indexInfo = $this->indexInfo( $table, $index );
1463
1464 if ( !$indexInfo ) {
1465 return null;
1466 }
1467
1468 return !$indexInfo[0]->Non_unique;
1469 }
1470
1471 /**
1472 * Helper for Database::insert().
1473 *
1474 * @param array $options
1475 * @return string
1476 */
1477 protected function makeInsertOptions( $options ) {
1478 return implode( ' ', $options );
1479 }
1480
1481 public function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
1482 # No rows to insert, easy just return now
1483 if ( !count( $a ) ) {
1484 return true;
1485 }
1486
1487 $table = $this->tableName( $table );
1488
1489 if ( !is_array( $options ) ) {
1490 $options = [ $options ];
1491 }
1492
1493 $fh = null;
1494 if ( isset( $options['fileHandle'] ) ) {
1495 $fh = $options['fileHandle'];
1496 }
1497 $options = $this->makeInsertOptions( $options );
1498
1499 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1500 $multi = true;
1501 $keys = array_keys( $a[0] );
1502 } else {
1503 $multi = false;
1504 $keys = array_keys( $a );
1505 }
1506
1507 $sql = 'INSERT ' . $options .
1508 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1509
1510 if ( $multi ) {
1511 $first = true;
1512 foreach ( $a as $row ) {
1513 if ( $first ) {
1514 $first = false;
1515 } else {
1516 $sql .= ',';
1517 }
1518 $sql .= '(' . $this->makeList( $row ) . ')';
1519 }
1520 } else {
1521 $sql .= '(' . $this->makeList( $a ) . ')';
1522 }
1523
1524 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1525 return false;
1526 } elseif ( $fh !== null ) {
1527 return true;
1528 }
1529
1530 return (bool)$this->query( $sql, $fname );
1531 }
1532
1533 /**
1534 * Make UPDATE options array for Database::makeUpdateOptions
1535 *
1536 * @param array $options
1537 * @return array
1538 */
1539 protected function makeUpdateOptionsArray( $options ) {
1540 if ( !is_array( $options ) ) {
1541 $options = [ $options ];
1542 }
1543
1544 $opts = [];
1545
1546 if ( in_array( 'IGNORE', $options ) ) {
1547 $opts[] = 'IGNORE';
1548 }
1549
1550 return $opts;
1551 }
1552
1553 /**
1554 * Make UPDATE options for the Database::update function
1555 *
1556 * @param array $options The options passed to Database::update
1557 * @return string
1558 */
1559 protected function makeUpdateOptions( $options ) {
1560 $opts = $this->makeUpdateOptionsArray( $options );
1561
1562 return implode( ' ', $opts );
1563 }
1564
1565 public function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
1566 $table = $this->tableName( $table );
1567 $opts = $this->makeUpdateOptions( $options );
1568 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self::LIST_SET );
1569
1570 if ( $conds !== [] && $conds !== '*' ) {
1571 $sql .= " WHERE " . $this->makeList( $conds, self::LIST_AND );
1572 }
1573
1574 return (bool)$this->query( $sql, $fname );
1575 }
1576
1577 public function makeList( $a, $mode = self::LIST_COMMA ) {
1578 if ( !is_array( $a ) ) {
1579 throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
1580 }
1581
1582 $first = true;
1583 $list = '';
1584
1585 foreach ( $a as $field => $value ) {
1586 if ( !$first ) {
1587 if ( $mode == self::LIST_AND ) {
1588 $list .= ' AND ';
1589 } elseif ( $mode == self::LIST_OR ) {
1590 $list .= ' OR ';
1591 } else {
1592 $list .= ',';
1593 }
1594 } else {
1595 $first = false;
1596 }
1597
1598 if ( ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_numeric( $field ) ) {
1599 $list .= "($value)";
1600 } elseif ( $mode == self::LIST_SET && is_numeric( $field ) ) {
1601 $list .= "$value";
1602 } elseif (
1603 ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_array( $value )
1604 ) {
1605 // Remove null from array to be handled separately if found
1606 $includeNull = false;
1607 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1608 $includeNull = true;
1609 unset( $value[$nullKey] );
1610 }
1611 if ( count( $value ) == 0 && !$includeNull ) {
1612 throw new InvalidArgumentException(
1613 __METHOD__ . ": empty input for field $field" );
1614 } elseif ( count( $value ) == 0 ) {
1615 // only check if $field is null
1616 $list .= "$field IS NULL";
1617 } else {
1618 // IN clause contains at least one valid element
1619 if ( $includeNull ) {
1620 // Group subconditions to ensure correct precedence
1621 $list .= '(';
1622 }
1623 if ( count( $value ) == 1 ) {
1624 // Special-case single values, as IN isn't terribly efficient
1625 // Don't necessarily assume the single key is 0; we don't
1626 // enforce linear numeric ordering on other arrays here.
1627 $value = array_values( $value )[0];
1628 $list .= $field . " = " . $this->addQuotes( $value );
1629 } else {
1630 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1631 }
1632 // if null present in array, append IS NULL
1633 if ( $includeNull ) {
1634 $list .= " OR $field IS NULL)";
1635 }
1636 }
1637 } elseif ( $value === null ) {
1638 if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
1639 $list .= "$field IS ";
1640 } elseif ( $mode == self::LIST_SET ) {
1641 $list .= "$field = ";
1642 }
1643 $list .= 'NULL';
1644 } else {
1645 if (
1646 $mode == self::LIST_AND || $mode == self::LIST_OR || $mode == self::LIST_SET
1647 ) {
1648 $list .= "$field = ";
1649 }
1650 $list .= $mode == self::LIST_NAMES ? $value : $this->addQuotes( $value );
1651 }
1652 }
1653
1654 return $list;
1655 }
1656
1657 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1658 $conds = [];
1659
1660 foreach ( $data as $base => $sub ) {
1661 if ( count( $sub ) ) {
1662 $conds[] = $this->makeList(
1663 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1664 self::LIST_AND );
1665 }
1666 }
1667
1668 if ( $conds ) {
1669 return $this->makeList( $conds, self::LIST_OR );
1670 } else {
1671 // Nothing to search for...
1672 return false;
1673 }
1674 }
1675
1676 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1677 return $valuename;
1678 }
1679
1680 public function bitNot( $field ) {
1681 return "(~$field)";
1682 }
1683
1684 public function bitAnd( $fieldLeft, $fieldRight ) {
1685 return "($fieldLeft & $fieldRight)";
1686 }
1687
1688 public function bitOr( $fieldLeft, $fieldRight ) {
1689 return "($fieldLeft | $fieldRight)";
1690 }
1691
1692 public function buildConcat( $stringList ) {
1693 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1694 }
1695
1696 public function buildGroupConcatField(
1697 $delim, $table, $field, $conds = '', $join_conds = []
1698 ) {
1699 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1700
1701 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1702 }
1703
1704 public function buildStringCast( $field ) {
1705 return $field;
1706 }
1707
1708 public function databasesAreIndependent() {
1709 return false;
1710 }
1711
1712 public function selectDB( $db ) {
1713 # Stub. Shouldn't cause serious problems if it's not overridden, but
1714 # if your database engine supports a concept similar to MySQL's
1715 # databases you may as well.
1716 $this->mDBname = $db;
1717
1718 return true;
1719 }
1720
1721 public function getDBname() {
1722 return $this->mDBname;
1723 }
1724
1725 public function getServer() {
1726 return $this->mServer;
1727 }
1728
1729 public function tableName( $name, $format = 'quoted' ) {
1730 # Skip the entire process when we have a string quoted on both ends.
1731 # Note that we check the end so that we will still quote any use of
1732 # use of `database`.table. But won't break things if someone wants
1733 # to query a database table with a dot in the name.
1734 if ( $this->isQuotedIdentifier( $name ) ) {
1735 return $name;
1736 }
1737
1738 # Lets test for any bits of text that should never show up in a table
1739 # name. Basically anything like JOIN or ON which are actually part of
1740 # SQL queries, but may end up inside of the table value to combine
1741 # sql. Such as how the API is doing.
1742 # Note that we use a whitespace test rather than a \b test to avoid
1743 # any remote case where a word like on may be inside of a table name
1744 # surrounded by symbols which may be considered word breaks.
1745 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1746 return $name;
1747 }
1748
1749 # Split database and table into proper variables.
1750 # We reverse the explode so that database.table and table both output
1751 # the correct table.
1752 $dbDetails = explode( '.', $name, 3 );
1753 if ( count( $dbDetails ) == 3 ) {
1754 list( $database, $schema, $table ) = $dbDetails;
1755 # We don't want any prefix added in this case
1756 $prefix = '';
1757 } elseif ( count( $dbDetails ) == 2 ) {
1758 list( $database, $table ) = $dbDetails;
1759 # We don't want any prefix added in this case
1760 $prefix = '';
1761 # In dbs that support it, $database may actually be the schema
1762 # but that doesn't affect any of the functionality here
1763 $schema = '';
1764 } else {
1765 list( $table ) = $dbDetails;
1766 if ( isset( $this->tableAliases[$table] ) ) {
1767 $database = $this->tableAliases[$table]['dbname'];
1768 $schema = is_string( $this->tableAliases[$table]['schema'] )
1769 ? $this->tableAliases[$table]['schema']
1770 : $this->mSchema;
1771 $prefix = is_string( $this->tableAliases[$table]['prefix'] )
1772 ? $this->tableAliases[$table]['prefix']
1773 : $this->mTablePrefix;
1774 } else {
1775 $database = '';
1776 $schema = $this->mSchema; # Default schema
1777 $prefix = $this->mTablePrefix; # Default prefix
1778 }
1779 }
1780
1781 # Quote $table and apply the prefix if not quoted.
1782 # $tableName might be empty if this is called from Database::replaceVars()
1783 $tableName = "{$prefix}{$table}";
1784 if ( $format === 'quoted'
1785 && !$this->isQuotedIdentifier( $tableName )
1786 && $tableName !== ''
1787 ) {
1788 $tableName = $this->addIdentifierQuotes( $tableName );
1789 }
1790
1791 # Quote $schema and $database and merge them with the table name if needed
1792 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1793 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1794
1795 return $tableName;
1796 }
1797
1798 /**
1799 * @param string|null $namespace Database or schema
1800 * @param string $relation Name of table, view, sequence, etc...
1801 * @param string $format One of (raw, quoted)
1802 * @return string Relation name with quoted and merged $namespace as needed
1803 */
1804 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
1805 if ( strlen( $namespace ) ) {
1806 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
1807 $namespace = $this->addIdentifierQuotes( $namespace );
1808 }
1809 $relation = $namespace . '.' . $relation;
1810 }
1811
1812 return $relation;
1813 }
1814
1815 public function tableNames() {
1816 $inArray = func_get_args();
1817 $retVal = [];
1818
1819 foreach ( $inArray as $name ) {
1820 $retVal[$name] = $this->tableName( $name );
1821 }
1822
1823 return $retVal;
1824 }
1825
1826 public function tableNamesN() {
1827 $inArray = func_get_args();
1828 $retVal = [];
1829
1830 foreach ( $inArray as $name ) {
1831 $retVal[] = $this->tableName( $name );
1832 }
1833
1834 return $retVal;
1835 }
1836
1837 /**
1838 * Get an aliased table name
1839 * e.g. tableName AS newTableName
1840 *
1841 * @param string $name Table name, see tableName()
1842 * @param string|bool $alias Alias (optional)
1843 * @return string SQL name for aliased table. Will not alias a table to its own name
1844 */
1845 protected function tableNameWithAlias( $name, $alias = false ) {
1846 if ( !$alias || $alias == $name ) {
1847 return $this->tableName( $name );
1848 } else {
1849 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1850 }
1851 }
1852
1853 /**
1854 * Gets an array of aliased table names
1855 *
1856 * @param array $tables [ [alias] => table ]
1857 * @return string[] See tableNameWithAlias()
1858 */
1859 protected function tableNamesWithAlias( $tables ) {
1860 $retval = [];
1861 foreach ( $tables as $alias => $table ) {
1862 if ( is_numeric( $alias ) ) {
1863 $alias = $table;
1864 }
1865 $retval[] = $this->tableNameWithAlias( $table, $alias );
1866 }
1867
1868 return $retval;
1869 }
1870
1871 /**
1872 * Get an aliased field name
1873 * e.g. fieldName AS newFieldName
1874 *
1875 * @param string $name Field name
1876 * @param string|bool $alias Alias (optional)
1877 * @return string SQL name for aliased field. Will not alias a field to its own name
1878 */
1879 protected function fieldNameWithAlias( $name, $alias = false ) {
1880 if ( !$alias || (string)$alias === (string)$name ) {
1881 return $name;
1882 } else {
1883 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1884 }
1885 }
1886
1887 /**
1888 * Gets an array of aliased field names
1889 *
1890 * @param array $fields [ [alias] => field ]
1891 * @return string[] See fieldNameWithAlias()
1892 */
1893 protected function fieldNamesWithAlias( $fields ) {
1894 $retval = [];
1895 foreach ( $fields as $alias => $field ) {
1896 if ( is_numeric( $alias ) ) {
1897 $alias = $field;
1898 }
1899 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1900 }
1901
1902 return $retval;
1903 }
1904
1905 /**
1906 * Get the aliased table name clause for a FROM clause
1907 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
1908 *
1909 * @param array $tables ( [alias] => table )
1910 * @param array $use_index Same as for select()
1911 * @param array $ignore_index Same as for select()
1912 * @param array $join_conds Same as for select()
1913 * @return string
1914 */
1915 protected function tableNamesWithIndexClauseOrJOIN(
1916 $tables, $use_index = [], $ignore_index = [], $join_conds = []
1917 ) {
1918 $ret = [];
1919 $retJOIN = [];
1920 $use_index = (array)$use_index;
1921 $ignore_index = (array)$ignore_index;
1922 $join_conds = (array)$join_conds;
1923
1924 foreach ( $tables as $alias => $table ) {
1925 if ( !is_string( $alias ) ) {
1926 // No alias? Set it equal to the table name
1927 $alias = $table;
1928 }
1929 // Is there a JOIN clause for this table?
1930 if ( isset( $join_conds[$alias] ) ) {
1931 list( $joinType, $conds ) = $join_conds[$alias];
1932 $tableClause = $joinType;
1933 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1934 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1935 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1936 if ( $use != '' ) {
1937 $tableClause .= ' ' . $use;
1938 }
1939 }
1940 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
1941 $ignore = $this->ignoreIndexClause(
1942 implode( ',', (array)$ignore_index[$alias] ) );
1943 if ( $ignore != '' ) {
1944 $tableClause .= ' ' . $ignore;
1945 }
1946 }
1947 $on = $this->makeList( (array)$conds, self::LIST_AND );
1948 if ( $on != '' ) {
1949 $tableClause .= ' ON (' . $on . ')';
1950 }
1951
1952 $retJOIN[] = $tableClause;
1953 } elseif ( isset( $use_index[$alias] ) ) {
1954 // Is there an INDEX clause for this table?
1955 $tableClause = $this->tableNameWithAlias( $table, $alias );
1956 $tableClause .= ' ' . $this->useIndexClause(
1957 implode( ',', (array)$use_index[$alias] )
1958 );
1959
1960 $ret[] = $tableClause;
1961 } elseif ( isset( $ignore_index[$alias] ) ) {
1962 // Is there an INDEX clause for this table?
1963 $tableClause = $this->tableNameWithAlias( $table, $alias );
1964 $tableClause .= ' ' . $this->ignoreIndexClause(
1965 implode( ',', (array)$ignore_index[$alias] )
1966 );
1967
1968 $ret[] = $tableClause;
1969 } else {
1970 $tableClause = $this->tableNameWithAlias( $table, $alias );
1971
1972 $ret[] = $tableClause;
1973 }
1974 }
1975
1976 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1977 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
1978 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
1979
1980 // Compile our final table clause
1981 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
1982 }
1983
1984 /**
1985 * Allows for index remapping in queries where this is not consistent across DBMS
1986 *
1987 * @param string $index
1988 * @return string
1989 */
1990 protected function indexName( $index ) {
1991 return $index;
1992 }
1993
1994 public function addQuotes( $s ) {
1995 if ( $s instanceof Blob ) {
1996 $s = $s->fetch();
1997 }
1998 if ( $s === null ) {
1999 return 'NULL';
2000 } elseif ( is_bool( $s ) ) {
2001 return (int)$s;
2002 } else {
2003 # This will also quote numeric values. This should be harmless,
2004 # and protects against weird problems that occur when they really
2005 # _are_ strings such as article titles and string->number->string
2006 # conversion is not 1:1.
2007 return "'" . $this->strencode( $s ) . "'";
2008 }
2009 }
2010
2011 /**
2012 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2013 * MySQL uses `backticks` while basically everything else uses double quotes.
2014 * Since MySQL is the odd one out here the double quotes are our generic
2015 * and we implement backticks in DatabaseMysql.
2016 *
2017 * @param string $s
2018 * @return string
2019 */
2020 public function addIdentifierQuotes( $s ) {
2021 return '"' . str_replace( '"', '""', $s ) . '"';
2022 }
2023
2024 /**
2025 * Returns if the given identifier looks quoted or not according to
2026 * the database convention for quoting identifiers .
2027 *
2028 * @note Do not use this to determine if untrusted input is safe.
2029 * A malicious user can trick this function.
2030 * @param string $name
2031 * @return bool
2032 */
2033 public function isQuotedIdentifier( $name ) {
2034 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2035 }
2036
2037 /**
2038 * @param string $s
2039 * @return string
2040 */
2041 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2042 return str_replace( [ $escapeChar, '%', '_' ],
2043 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2044 $s );
2045 }
2046
2047 public function buildLike() {
2048 $params = func_get_args();
2049
2050 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2051 $params = $params[0];
2052 }
2053
2054 $s = '';
2055
2056 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2057 // may escape backslashes, creating problems of double escaping. The `
2058 // character has good cross-DBMS compatibility, avoiding special operators
2059 // in MS SQL like ^ and %
2060 $escapeChar = '`';
2061
2062 foreach ( $params as $value ) {
2063 if ( $value instanceof LikeMatch ) {
2064 $s .= $value->toString();
2065 } else {
2066 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2067 }
2068 }
2069
2070 return ' LIKE ' . $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2071 }
2072
2073 public function anyChar() {
2074 return new LikeMatch( '_' );
2075 }
2076
2077 public function anyString() {
2078 return new LikeMatch( '%' );
2079 }
2080
2081 public function nextSequenceValue( $seqName ) {
2082 return null;
2083 }
2084
2085 /**
2086 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2087 * is only needed because a) MySQL must be as efficient as possible due to
2088 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2089 * which index to pick. Anyway, other databases might have different
2090 * indexes on a given table. So don't bother overriding this unless you're
2091 * MySQL.
2092 * @param string $index
2093 * @return string
2094 */
2095 public function useIndexClause( $index ) {
2096 return '';
2097 }
2098
2099 /**
2100 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2101 * is only needed because a) MySQL must be as efficient as possible due to
2102 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2103 * which index to pick. Anyway, other databases might have different
2104 * indexes on a given table. So don't bother overriding this unless you're
2105 * MySQL.
2106 * @param string $index
2107 * @return string
2108 */
2109 public function ignoreIndexClause( $index ) {
2110 return '';
2111 }
2112
2113 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2114 $quotedTable = $this->tableName( $table );
2115
2116 if ( count( $rows ) == 0 ) {
2117 return;
2118 }
2119
2120 # Single row case
2121 if ( !is_array( reset( $rows ) ) ) {
2122 $rows = [ $rows ];
2123 }
2124
2125 // @FXIME: this is not atomic, but a trx would break affectedRows()
2126 foreach ( $rows as $row ) {
2127 # Delete rows which collide
2128 if ( $uniqueIndexes ) {
2129 $sql = "DELETE FROM $quotedTable WHERE ";
2130 $first = true;
2131 foreach ( $uniqueIndexes as $index ) {
2132 if ( $first ) {
2133 $first = false;
2134 $sql .= '( ';
2135 } else {
2136 $sql .= ' ) OR ( ';
2137 }
2138 if ( is_array( $index ) ) {
2139 $first2 = true;
2140 foreach ( $index as $col ) {
2141 if ( $first2 ) {
2142 $first2 = false;
2143 } else {
2144 $sql .= ' AND ';
2145 }
2146 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2147 }
2148 } else {
2149 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2150 }
2151 }
2152 $sql .= ' )';
2153 $this->query( $sql, $fname );
2154 }
2155
2156 # Now insert the row
2157 $this->insert( $table, $row, $fname );
2158 }
2159 }
2160
2161 /**
2162 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2163 * statement.
2164 *
2165 * @param string $table Table name
2166 * @param array|string $rows Row(s) to insert
2167 * @param string $fname Caller function name
2168 *
2169 * @return ResultWrapper
2170 */
2171 protected function nativeReplace( $table, $rows, $fname ) {
2172 $table = $this->tableName( $table );
2173
2174 # Single row case
2175 if ( !is_array( reset( $rows ) ) ) {
2176 $rows = [ $rows ];
2177 }
2178
2179 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2180 $first = true;
2181
2182 foreach ( $rows as $row ) {
2183 if ( $first ) {
2184 $first = false;
2185 } else {
2186 $sql .= ',';
2187 }
2188
2189 $sql .= '(' . $this->makeList( $row ) . ')';
2190 }
2191
2192 return $this->query( $sql, $fname );
2193 }
2194
2195 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2196 $fname = __METHOD__
2197 ) {
2198 if ( !count( $rows ) ) {
2199 return true; // nothing to do
2200 }
2201
2202 if ( !is_array( reset( $rows ) ) ) {
2203 $rows = [ $rows ];
2204 }
2205
2206 if ( count( $uniqueIndexes ) ) {
2207 $clauses = []; // list WHERE clauses that each identify a single row
2208 foreach ( $rows as $row ) {
2209 foreach ( $uniqueIndexes as $index ) {
2210 $index = is_array( $index ) ? $index : [ $index ]; // columns
2211 $rowKey = []; // unique key to this row
2212 foreach ( $index as $column ) {
2213 $rowKey[$column] = $row[$column];
2214 }
2215 $clauses[] = $this->makeList( $rowKey, self::LIST_AND );
2216 }
2217 }
2218 $where = [ $this->makeList( $clauses, self::LIST_OR ) ];
2219 } else {
2220 $where = false;
2221 }
2222
2223 $useTrx = !$this->mTrxLevel;
2224 if ( $useTrx ) {
2225 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2226 }
2227 try {
2228 # Update any existing conflicting row(s)
2229 if ( $where !== false ) {
2230 $ok = $this->update( $table, $set, $where, $fname );
2231 } else {
2232 $ok = true;
2233 }
2234 # Now insert any non-conflicting row(s)
2235 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2236 } catch ( Exception $e ) {
2237 if ( $useTrx ) {
2238 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2239 }
2240 throw $e;
2241 }
2242 if ( $useTrx ) {
2243 $this->commit( $fname, self::FLUSHING_INTERNAL );
2244 }
2245
2246 return $ok;
2247 }
2248
2249 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2250 $fname = __METHOD__
2251 ) {
2252 if ( !$conds ) {
2253 throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
2254 }
2255
2256 $delTable = $this->tableName( $delTable );
2257 $joinTable = $this->tableName( $joinTable );
2258 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2259 if ( $conds != '*' ) {
2260 $sql .= 'WHERE ' . $this->makeList( $conds, self::LIST_AND );
2261 }
2262 $sql .= ')';
2263
2264 $this->query( $sql, $fname );
2265 }
2266
2267 public function textFieldSize( $table, $field ) {
2268 $table = $this->tableName( $table );
2269 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2270 $res = $this->query( $sql, __METHOD__ );
2271 $row = $this->fetchObject( $res );
2272
2273 $m = [];
2274
2275 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2276 $size = $m[1];
2277 } else {
2278 $size = -1;
2279 }
2280
2281 return $size;
2282 }
2283
2284 public function delete( $table, $conds, $fname = __METHOD__ ) {
2285 if ( !$conds ) {
2286 throw new DBUnexpectedError( $this, __METHOD__ . ' called with no conditions' );
2287 }
2288
2289 $table = $this->tableName( $table );
2290 $sql = "DELETE FROM $table";
2291
2292 if ( $conds != '*' ) {
2293 if ( is_array( $conds ) ) {
2294 $conds = $this->makeList( $conds, self::LIST_AND );
2295 }
2296 $sql .= ' WHERE ' . $conds;
2297 }
2298
2299 return $this->query( $sql, $fname );
2300 }
2301
2302 public function insertSelect(
2303 $destTable, $srcTable, $varMap, $conds,
2304 $fname = __METHOD__, $insertOptions = [], $selectOptions = []
2305 ) {
2306 if ( $this->cliMode ) {
2307 // For massive migrations with downtime, we don't want to select everything
2308 // into memory and OOM, so do all this native on the server side if possible.
2309 return $this->nativeInsertSelect(
2310 $destTable,
2311 $srcTable,
2312 $varMap,
2313 $conds,
2314 $fname,
2315 $insertOptions,
2316 $selectOptions
2317 );
2318 }
2319
2320 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2321 // on only the master (without needing row-based-replication). It also makes it easy to
2322 // know how big the INSERT is going to be.
2323 $fields = [];
2324 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2325 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2326 }
2327 $selectOptions[] = 'FOR UPDATE';
2328 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2329 if ( !$res ) {
2330 return false;
2331 }
2332
2333 $rows = [];
2334 foreach ( $res as $row ) {
2335 $rows[] = (array)$row;
2336 }
2337
2338 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2339 }
2340
2341 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2342 $fname = __METHOD__,
2343 $insertOptions = [], $selectOptions = []
2344 ) {
2345 $destTable = $this->tableName( $destTable );
2346
2347 if ( !is_array( $insertOptions ) ) {
2348 $insertOptions = [ $insertOptions ];
2349 }
2350
2351 $insertOptions = $this->makeInsertOptions( $insertOptions );
2352
2353 if ( !is_array( $selectOptions ) ) {
2354 $selectOptions = [ $selectOptions ];
2355 }
2356
2357 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2358 $selectOptions );
2359
2360 if ( is_array( $srcTable ) ) {
2361 $srcTable = implode( ',', array_map( [ $this, 'tableName' ], $srcTable ) );
2362 } else {
2363 $srcTable = $this->tableName( $srcTable );
2364 }
2365
2366 $sql = "INSERT $insertOptions" .
2367 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2368 " SELECT $startOpts " . implode( ',', $varMap ) .
2369 " FROM $srcTable $useIndex $ignoreIndex ";
2370
2371 if ( $conds != '*' ) {
2372 if ( is_array( $conds ) ) {
2373 $conds = $this->makeList( $conds, self::LIST_AND );
2374 }
2375 $sql .= " WHERE $conds";
2376 }
2377
2378 $sql .= " $tailOpts";
2379
2380 return $this->query( $sql, $fname );
2381 }
2382
2383 /**
2384 * Construct a LIMIT query with optional offset. This is used for query
2385 * pages. The SQL should be adjusted so that only the first $limit rows
2386 * are returned. If $offset is provided as well, then the first $offset
2387 * rows should be discarded, and the next $limit rows should be returned.
2388 * If the result of the query is not ordered, then the rows to be returned
2389 * are theoretically arbitrary.
2390 *
2391 * $sql is expected to be a SELECT, if that makes a difference.
2392 *
2393 * The version provided by default works in MySQL and SQLite. It will very
2394 * likely need to be overridden for most other DBMSes.
2395 *
2396 * @param string $sql SQL query we will append the limit too
2397 * @param int $limit The SQL limit
2398 * @param int|bool $offset The SQL offset (default false)
2399 * @throws DBUnexpectedError
2400 * @return string
2401 */
2402 public function limitResult( $sql, $limit, $offset = false ) {
2403 if ( !is_numeric( $limit ) ) {
2404 throw new DBUnexpectedError( $this,
2405 "Invalid non-numeric limit passed to limitResult()\n" );
2406 }
2407
2408 return "$sql LIMIT "
2409 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2410 . "{$limit} ";
2411 }
2412
2413 public function unionSupportsOrderAndLimit() {
2414 return true; // True for almost every DB supported
2415 }
2416
2417 public function unionQueries( $sqls, $all ) {
2418 $glue = $all ? ') UNION ALL (' : ') UNION (';
2419
2420 return '(' . implode( $glue, $sqls ) . ')';
2421 }
2422
2423 public function conditional( $cond, $trueVal, $falseVal ) {
2424 if ( is_array( $cond ) ) {
2425 $cond = $this->makeList( $cond, self::LIST_AND );
2426 }
2427
2428 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2429 }
2430
2431 public function strreplace( $orig, $old, $new ) {
2432 return "REPLACE({$orig}, {$old}, {$new})";
2433 }
2434
2435 public function getServerUptime() {
2436 return 0;
2437 }
2438
2439 public function wasDeadlock() {
2440 return false;
2441 }
2442
2443 public function wasLockTimeout() {
2444 return false;
2445 }
2446
2447 public function wasErrorReissuable() {
2448 return false;
2449 }
2450
2451 public function wasReadOnlyError() {
2452 return false;
2453 }
2454
2455 /**
2456 * Do not use this method outside of Database/DBError classes
2457 *
2458 * @param integer|string $errno
2459 * @return bool Whether the given query error was a connection drop
2460 */
2461 public function wasConnectionError( $errno ) {
2462 return false;
2463 }
2464
2465 public function deadlockLoop() {
2466 $args = func_get_args();
2467 $function = array_shift( $args );
2468 $tries = self::DEADLOCK_TRIES;
2469
2470 $this->begin( __METHOD__ );
2471
2472 $retVal = null;
2473 /** @var Exception $e */
2474 $e = null;
2475 do {
2476 try {
2477 $retVal = call_user_func_array( $function, $args );
2478 break;
2479 } catch ( DBQueryError $e ) {
2480 if ( $this->wasDeadlock() ) {
2481 // Retry after a randomized delay
2482 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
2483 } else {
2484 // Throw the error back up
2485 throw $e;
2486 }
2487 }
2488 } while ( --$tries > 0 );
2489
2490 if ( $tries <= 0 ) {
2491 // Too many deadlocks; give up
2492 $this->rollback( __METHOD__ );
2493 throw $e;
2494 } else {
2495 $this->commit( __METHOD__ );
2496
2497 return $retVal;
2498 }
2499 }
2500
2501 public function masterPosWait( DBMasterPos $pos, $timeout ) {
2502 # Real waits are implemented in the subclass.
2503 return 0;
2504 }
2505
2506 public function getReplicaPos() {
2507 # Stub
2508 return false;
2509 }
2510
2511 public function getMasterPos() {
2512 # Stub
2513 return false;
2514 }
2515
2516 public function serverIsReadOnly() {
2517 return false;
2518 }
2519
2520 final public function onTransactionResolution( callable $callback, $fname = __METHOD__ ) {
2521 if ( !$this->mTrxLevel ) {
2522 throw new DBUnexpectedError( $this, "No transaction is active." );
2523 }
2524 $this->mTrxEndCallbacks[] = [ $callback, $fname ];
2525 }
2526
2527 final public function onTransactionIdle( callable $callback, $fname = __METHOD__ ) {
2528 $this->mTrxIdleCallbacks[] = [ $callback, $fname ];
2529 if ( !$this->mTrxLevel ) {
2530 $this->runOnTransactionIdleCallbacks( self::TRIGGER_IDLE );
2531 }
2532 }
2533
2534 final public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
2535 if ( $this->mTrxLevel ) {
2536 $this->mTrxPreCommitCallbacks[] = [ $callback, $fname ];
2537 } else {
2538 // If no transaction is active, then make one for this callback
2539 $this->startAtomic( __METHOD__ );
2540 try {
2541 call_user_func( $callback );
2542 $this->endAtomic( __METHOD__ );
2543 } catch ( Exception $e ) {
2544 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2545 throw $e;
2546 }
2547 }
2548 }
2549
2550 final public function setTransactionListener( $name, callable $callback = null ) {
2551 if ( $callback ) {
2552 $this->mTrxRecurringCallbacks[$name] = $callback;
2553 } else {
2554 unset( $this->mTrxRecurringCallbacks[$name] );
2555 }
2556 }
2557
2558 /**
2559 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2560 *
2561 * This method should not be used outside of Database/LoadBalancer
2562 *
2563 * @param bool $suppress
2564 * @since 1.28
2565 */
2566 final public function setTrxEndCallbackSuppression( $suppress ) {
2567 $this->mTrxEndCallbacksSuppressed = $suppress;
2568 }
2569
2570 /**
2571 * Actually run and consume any "on transaction idle/resolution" callbacks.
2572 *
2573 * This method should not be used outside of Database/LoadBalancer
2574 *
2575 * @param integer $trigger IDatabase::TRIGGER_* constant
2576 * @since 1.20
2577 * @throws Exception
2578 */
2579 public function runOnTransactionIdleCallbacks( $trigger ) {
2580 if ( $this->mTrxEndCallbacksSuppressed ) {
2581 return;
2582 }
2583
2584 $autoTrx = $this->getFlag( self::DBO_TRX ); // automatic begin() enabled?
2585 /** @var Exception $e */
2586 $e = null; // first exception
2587 do { // callbacks may add callbacks :)
2588 $callbacks = array_merge(
2589 $this->mTrxIdleCallbacks,
2590 $this->mTrxEndCallbacks // include "transaction resolution" callbacks
2591 );
2592 $this->mTrxIdleCallbacks = []; // consumed (and recursion guard)
2593 $this->mTrxEndCallbacks = []; // consumed (recursion guard)
2594 foreach ( $callbacks as $callback ) {
2595 try {
2596 list( $phpCallback ) = $callback;
2597 $this->clearFlag( self::DBO_TRX ); // make each query its own transaction
2598 call_user_func_array( $phpCallback, [ $trigger ] );
2599 if ( $autoTrx ) {
2600 $this->setFlag( self::DBO_TRX ); // restore automatic begin()
2601 } else {
2602 $this->clearFlag( self::DBO_TRX ); // restore auto-commit
2603 }
2604 } catch ( Exception $ex ) {
2605 call_user_func( $this->errorLogger, $ex );
2606 $e = $e ?: $ex;
2607 // Some callbacks may use startAtomic/endAtomic, so make sure
2608 // their transactions are ended so other callbacks don't fail
2609 if ( $this->trxLevel() ) {
2610 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2611 }
2612 }
2613 }
2614 } while ( count( $this->mTrxIdleCallbacks ) );
2615
2616 if ( $e instanceof Exception ) {
2617 throw $e; // re-throw any first exception
2618 }
2619 }
2620
2621 /**
2622 * Actually run and consume any "on transaction pre-commit" callbacks.
2623 *
2624 * This method should not be used outside of Database/LoadBalancer
2625 *
2626 * @since 1.22
2627 * @throws Exception
2628 */
2629 public function runOnTransactionPreCommitCallbacks() {
2630 $e = null; // first exception
2631 do { // callbacks may add callbacks :)
2632 $callbacks = $this->mTrxPreCommitCallbacks;
2633 $this->mTrxPreCommitCallbacks = []; // consumed (and recursion guard)
2634 foreach ( $callbacks as $callback ) {
2635 try {
2636 list( $phpCallback ) = $callback;
2637 call_user_func( $phpCallback );
2638 } catch ( Exception $ex ) {
2639 call_user_func( $this->errorLogger, $ex );
2640 $e = $e ?: $ex;
2641 }
2642 }
2643 } while ( count( $this->mTrxPreCommitCallbacks ) );
2644
2645 if ( $e instanceof Exception ) {
2646 throw $e; // re-throw any first exception
2647 }
2648 }
2649
2650 /**
2651 * Actually run any "transaction listener" callbacks.
2652 *
2653 * This method should not be used outside of Database/LoadBalancer
2654 *
2655 * @param integer $trigger IDatabase::TRIGGER_* constant
2656 * @throws Exception
2657 * @since 1.20
2658 */
2659 public function runTransactionListenerCallbacks( $trigger ) {
2660 if ( $this->mTrxEndCallbacksSuppressed ) {
2661 return;
2662 }
2663
2664 /** @var Exception $e */
2665 $e = null; // first exception
2666
2667 foreach ( $this->mTrxRecurringCallbacks as $phpCallback ) {
2668 try {
2669 $phpCallback( $trigger, $this );
2670 } catch ( Exception $ex ) {
2671 call_user_func( $this->errorLogger, $ex );
2672 $e = $e ?: $ex;
2673 }
2674 }
2675
2676 if ( $e instanceof Exception ) {
2677 throw $e; // re-throw any first exception
2678 }
2679 }
2680
2681 final public function startAtomic( $fname = __METHOD__ ) {
2682 if ( !$this->mTrxLevel ) {
2683 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2684 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2685 // in all changes being in one transaction to keep requests transactional.
2686 if ( !$this->getFlag( self::DBO_TRX ) ) {
2687 $this->mTrxAutomaticAtomic = true;
2688 }
2689 }
2690
2691 $this->mTrxAtomicLevels[] = $fname;
2692 }
2693
2694 final public function endAtomic( $fname = __METHOD__ ) {
2695 if ( !$this->mTrxLevel ) {
2696 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2697 }
2698 if ( !$this->mTrxAtomicLevels ||
2699 array_pop( $this->mTrxAtomicLevels ) !== $fname
2700 ) {
2701 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2702 }
2703
2704 if ( !$this->mTrxAtomicLevels && $this->mTrxAutomaticAtomic ) {
2705 $this->commit( $fname, self::FLUSHING_INTERNAL );
2706 }
2707 }
2708
2709 final public function doAtomicSection( $fname, callable $callback ) {
2710 $this->startAtomic( $fname );
2711 try {
2712 $res = call_user_func_array( $callback, [ $this, $fname ] );
2713 } catch ( Exception $e ) {
2714 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2715 throw $e;
2716 }
2717 $this->endAtomic( $fname );
2718
2719 return $res;
2720 }
2721
2722 final public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
2723 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2724 if ( $this->mTrxLevel ) {
2725 if ( $this->mTrxAtomicLevels ) {
2726 $levels = implode( ', ', $this->mTrxAtomicLevels );
2727 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2728 throw new DBUnexpectedError( $this, $msg );
2729 } elseif ( !$this->mTrxAutomatic ) {
2730 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2731 throw new DBUnexpectedError( $this, $msg );
2732 } else {
2733 // @TODO: make this an exception at some point
2734 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2735 $this->queryLogger->error( $msg );
2736 return; // join the main transaction set
2737 }
2738 } elseif ( $this->getFlag( self::DBO_TRX ) && $mode !== self::TRANSACTION_INTERNAL ) {
2739 // @TODO: make this an exception at some point
2740 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2741 $this->queryLogger->error( $msg );
2742 return; // let any writes be in the main transaction
2743 }
2744
2745 // Avoid fatals if close() was called
2746 $this->assertOpen();
2747
2748 $this->doBegin( $fname );
2749 $this->mTrxTimestamp = microtime( true );
2750 $this->mTrxFname = $fname;
2751 $this->mTrxDoneWrites = false;
2752 $this->mTrxAutomaticAtomic = false;
2753 $this->mTrxAtomicLevels = [];
2754 $this->mTrxShortId = sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2755 $this->mTrxWriteDuration = 0.0;
2756 $this->mTrxWriteQueryCount = 0;
2757 $this->mTrxWriteAdjDuration = 0.0;
2758 $this->mTrxWriteAdjQueryCount = 0;
2759 $this->mTrxWriteCallers = [];
2760 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2761 // Get an estimate of the replica DB lag before then, treating estimate staleness
2762 // as lag itself just to be safe
2763 $status = $this->getApproximateLagStatus();
2764 $this->mTrxReplicaLag = $status['lag'] + ( microtime( true ) - $status['since'] );
2765 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
2766 // caller will think its OK to muck around with the transaction just because startAtomic()
2767 // has not yet completed (e.g. setting mTrxAtomicLevels).
2768 $this->mTrxAutomatic = ( $mode === self::TRANSACTION_INTERNAL );
2769 }
2770
2771 /**
2772 * Issues the BEGIN command to the database server.
2773 *
2774 * @see Database::begin()
2775 * @param string $fname
2776 */
2777 protected function doBegin( $fname ) {
2778 $this->query( 'BEGIN', $fname );
2779 $this->mTrxLevel = 1;
2780 }
2781
2782 final public function commit( $fname = __METHOD__, $flush = '' ) {
2783 if ( $this->mTrxLevel && $this->mTrxAtomicLevels ) {
2784 // There are still atomic sections open. This cannot be ignored
2785 $levels = implode( ', ', $this->mTrxAtomicLevels );
2786 throw new DBUnexpectedError(
2787 $this,
2788 "$fname: Got COMMIT while atomic sections $levels are still open."
2789 );
2790 }
2791
2792 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
2793 if ( !$this->mTrxLevel ) {
2794 return; // nothing to do
2795 } elseif ( !$this->mTrxAutomatic ) {
2796 throw new DBUnexpectedError(
2797 $this,
2798 "$fname: Flushing an explicit transaction, getting out of sync."
2799 );
2800 }
2801 } else {
2802 if ( !$this->mTrxLevel ) {
2803 $this->queryLogger->error(
2804 "$fname: No transaction to commit, something got out of sync." );
2805 return; // nothing to do
2806 } elseif ( $this->mTrxAutomatic ) {
2807 // @TODO: make this an exception at some point
2808 $msg = "$fname: Explicit commit of implicit transaction.";
2809 $this->queryLogger->error( $msg );
2810 return; // wait for the main transaction set commit round
2811 }
2812 }
2813
2814 // Avoid fatals if close() was called
2815 $this->assertOpen();
2816
2817 $this->runOnTransactionPreCommitCallbacks();
2818 $writeTime = $this->pendingWriteQueryDuration( self::ESTIMATE_DB_APPLY );
2819 $this->doCommit( $fname );
2820 if ( $this->mTrxDoneWrites ) {
2821 $this->mLastWriteTime = microtime( true );
2822 $this->trxProfiler->transactionWritingOut(
2823 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
2824 }
2825
2826 $this->runOnTransactionIdleCallbacks( self::TRIGGER_COMMIT );
2827 $this->runTransactionListenerCallbacks( self::TRIGGER_COMMIT );
2828 }
2829
2830 /**
2831 * Issues the COMMIT command to the database server.
2832 *
2833 * @see Database::commit()
2834 * @param string $fname
2835 */
2836 protected function doCommit( $fname ) {
2837 if ( $this->mTrxLevel ) {
2838 $this->query( 'COMMIT', $fname );
2839 $this->mTrxLevel = 0;
2840 }
2841 }
2842
2843 final public function rollback( $fname = __METHOD__, $flush = '' ) {
2844 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
2845 if ( !$this->mTrxLevel ) {
2846 return; // nothing to do
2847 }
2848 } else {
2849 if ( !$this->mTrxLevel ) {
2850 $this->queryLogger->error(
2851 "$fname: No transaction to rollback, something got out of sync." );
2852 return; // nothing to do
2853 } elseif ( $this->getFlag( self::DBO_TRX ) ) {
2854 throw new DBUnexpectedError(
2855 $this,
2856 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2857 );
2858 }
2859 }
2860
2861 // Avoid fatals if close() was called
2862 $this->assertOpen();
2863
2864 $this->doRollback( $fname );
2865 $this->mTrxAtomicLevels = [];
2866 if ( $this->mTrxDoneWrites ) {
2867 $this->trxProfiler->transactionWritingOut(
2868 $this->mServer, $this->mDBname, $this->mTrxShortId );
2869 }
2870
2871 $this->mTrxIdleCallbacks = []; // clear
2872 $this->mTrxPreCommitCallbacks = []; // clear
2873 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
2874 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
2875 }
2876
2877 /**
2878 * Issues the ROLLBACK command to the database server.
2879 *
2880 * @see Database::rollback()
2881 * @param string $fname
2882 */
2883 protected function doRollback( $fname ) {
2884 if ( $this->mTrxLevel ) {
2885 # Disconnects cause rollback anyway, so ignore those errors
2886 $ignoreErrors = true;
2887 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
2888 $this->mTrxLevel = 0;
2889 }
2890 }
2891
2892 public function flushSnapshot( $fname = __METHOD__ ) {
2893 if ( $this->writesOrCallbacksPending() || $this->explicitTrxActive() ) {
2894 // This only flushes transactions to clear snapshots, not to write data
2895 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
2896 throw new DBUnexpectedError(
2897 $this,
2898 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
2899 );
2900 }
2901
2902 $this->commit( $fname, self::FLUSHING_INTERNAL );
2903 }
2904
2905 public function explicitTrxActive() {
2906 return $this->mTrxLevel && ( $this->mTrxAtomicLevels || !$this->mTrxAutomatic );
2907 }
2908
2909 public function duplicateTableStructure(
2910 $oldName, $newName, $temporary = false, $fname = __METHOD__
2911 ) {
2912 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
2913 }
2914
2915 public function listTables( $prefix = null, $fname = __METHOD__ ) {
2916 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
2917 }
2918
2919 public function listViews( $prefix = null, $fname = __METHOD__ ) {
2920 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
2921 }
2922
2923 public function timestamp( $ts = 0 ) {
2924 $t = new ConvertibleTimestamp( $ts );
2925 // Let errors bubble up to avoid putting garbage in the DB
2926 return $t->getTimestamp( TS_MW );
2927 }
2928
2929 public function timestampOrNull( $ts = null ) {
2930 if ( is_null( $ts ) ) {
2931 return null;
2932 } else {
2933 return $this->timestamp( $ts );
2934 }
2935 }
2936
2937 /**
2938 * Take the result from a query, and wrap it in a ResultWrapper if
2939 * necessary. Boolean values are passed through as is, to indicate success
2940 * of write queries or failure.
2941 *
2942 * Once upon a time, Database::query() returned a bare MySQL result
2943 * resource, and it was necessary to call this function to convert it to
2944 * a wrapper. Nowadays, raw database objects are never exposed to external
2945 * callers, so this is unnecessary in external code.
2946 *
2947 * @param bool|ResultWrapper|resource|object $result
2948 * @return bool|ResultWrapper
2949 */
2950 protected function resultObject( $result ) {
2951 if ( !$result ) {
2952 return false;
2953 } elseif ( $result instanceof ResultWrapper ) {
2954 return $result;
2955 } elseif ( $result === true ) {
2956 // Successful write query
2957 return $result;
2958 } else {
2959 return new ResultWrapper( $this, $result );
2960 }
2961 }
2962
2963 public function ping( &$rtt = null ) {
2964 // Avoid hitting the server if it was hit recently
2965 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing ) < self::PING_TTL ) {
2966 if ( !func_num_args() || $this->mRTTEstimate > 0 ) {
2967 $rtt = $this->mRTTEstimate;
2968 return true; // don't care about $rtt
2969 }
2970 }
2971
2972 // This will reconnect if possible or return false if not
2973 $this->clearFlag( self::DBO_TRX, self::REMEMBER_PRIOR );
2974 $ok = ( $this->query( self::PING_QUERY, __METHOD__, true ) !== false );
2975 $this->restoreFlags( self::RESTORE_PRIOR );
2976
2977 if ( $ok ) {
2978 $rtt = $this->mRTTEstimate;
2979 }
2980
2981 return $ok;
2982 }
2983
2984 /**
2985 * @return bool
2986 */
2987 protected function reconnect() {
2988 $this->closeConnection();
2989 $this->mOpened = false;
2990 $this->mConn = false;
2991 try {
2992 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
2993 $this->lastPing = microtime( true );
2994 $ok = true;
2995 } catch ( DBConnectionError $e ) {
2996 $ok = false;
2997 }
2998
2999 return $ok;
3000 }
3001
3002 public function getSessionLagStatus() {
3003 return $this->getTransactionLagStatus() ?: $this->getApproximateLagStatus();
3004 }
3005
3006 /**
3007 * Get the replica DB lag when the current transaction started
3008 *
3009 * This is useful when transactions might use snapshot isolation
3010 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3011 * is this lag plus transaction duration. If they don't, it is still
3012 * safe to be pessimistic. This returns null if there is no transaction.
3013 *
3014 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3015 * @since 1.27
3016 */
3017 protected function getTransactionLagStatus() {
3018 return $this->mTrxLevel
3019 ? [ 'lag' => $this->mTrxReplicaLag, 'since' => $this->trxTimestamp() ]
3020 : null;
3021 }
3022
3023 /**
3024 * Get a replica DB lag estimate for this server
3025 *
3026 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3027 * @since 1.27
3028 */
3029 protected function getApproximateLagStatus() {
3030 return [
3031 'lag' => $this->getLBInfo( 'replica' ) ? $this->getLag() : 0,
3032 'since' => microtime( true )
3033 ];
3034 }
3035
3036 /**
3037 * Merge the result of getSessionLagStatus() for several DBs
3038 * using the most pessimistic values to estimate the lag of
3039 * any data derived from them in combination
3040 *
3041 * This is information is useful for caching modules
3042 *
3043 * @see WANObjectCache::set()
3044 * @see WANObjectCache::getWithSetCallback()
3045 *
3046 * @param IDatabase $db1
3047 * @param IDatabase ...
3048 * @return array Map of values:
3049 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3050 * - since: oldest UNIX timestamp of any of the DB lag estimates
3051 * - pending: whether any of the DBs have uncommitted changes
3052 * @since 1.27
3053 */
3054 public static function getCacheSetOptions( IDatabase $db1 ) {
3055 $res = [ 'lag' => 0, 'since' => INF, 'pending' => false ];
3056 foreach ( func_get_args() as $db ) {
3057 /** @var IDatabase $db */
3058 $status = $db->getSessionLagStatus();
3059 if ( $status['lag'] === false ) {
3060 $res['lag'] = false;
3061 } elseif ( $res['lag'] !== false ) {
3062 $res['lag'] = max( $res['lag'], $status['lag'] );
3063 }
3064 $res['since'] = min( $res['since'], $status['since'] );
3065 $res['pending'] = $res['pending'] ?: $db->writesPending();
3066 }
3067
3068 return $res;
3069 }
3070
3071 public function getLag() {
3072 return 0;
3073 }
3074
3075 public function maxListLen() {
3076 return 0;
3077 }
3078
3079 public function encodeBlob( $b ) {
3080 return $b;
3081 }
3082
3083 public function decodeBlob( $b ) {
3084 if ( $b instanceof Blob ) {
3085 $b = $b->fetch();
3086 }
3087 return $b;
3088 }
3089
3090 public function setSessionOptions( array $options ) {
3091 }
3092
3093 public function sourceFile(
3094 $filename,
3095 callable $lineCallback = null,
3096 callable $resultCallback = null,
3097 $fname = false,
3098 callable $inputCallback = null
3099 ) {
3100 MediaWiki\suppressWarnings();
3101 $fp = fopen( $filename, 'r' );
3102 MediaWiki\restoreWarnings();
3103
3104 if ( false === $fp ) {
3105 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3106 }
3107
3108 if ( !$fname ) {
3109 $fname = __METHOD__ . "( $filename )";
3110 }
3111
3112 try {
3113 $error = $this->sourceStream(
3114 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3115 } catch ( Exception $e ) {
3116 fclose( $fp );
3117 throw $e;
3118 }
3119
3120 fclose( $fp );
3121
3122 return $error;
3123 }
3124
3125 public function setSchemaVars( $vars ) {
3126 $this->mSchemaVars = $vars;
3127 }
3128
3129 public function sourceStream(
3130 $fp,
3131 callable $lineCallback = null,
3132 callable $resultCallback = null,
3133 $fname = __METHOD__,
3134 callable $inputCallback = null
3135 ) {
3136 $cmd = '';
3137
3138 while ( !feof( $fp ) ) {
3139 if ( $lineCallback ) {
3140 call_user_func( $lineCallback );
3141 }
3142
3143 $line = trim( fgets( $fp ) );
3144
3145 if ( $line == '' ) {
3146 continue;
3147 }
3148
3149 if ( '-' == $line[0] && '-' == $line[1] ) {
3150 continue;
3151 }
3152
3153 if ( $cmd != '' ) {
3154 $cmd .= ' ';
3155 }
3156
3157 $done = $this->streamStatementEnd( $cmd, $line );
3158
3159 $cmd .= "$line\n";
3160
3161 if ( $done || feof( $fp ) ) {
3162 $cmd = $this->replaceVars( $cmd );
3163
3164 if ( !$inputCallback || call_user_func( $inputCallback, $cmd ) ) {
3165 $res = $this->query( $cmd, $fname );
3166
3167 if ( $resultCallback ) {
3168 call_user_func( $resultCallback, $res, $this );
3169 }
3170
3171 if ( false === $res ) {
3172 $err = $this->lastError();
3173
3174 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3175 }
3176 }
3177 $cmd = '';
3178 }
3179 }
3180
3181 return true;
3182 }
3183
3184 /**
3185 * Called by sourceStream() to check if we've reached a statement end
3186 *
3187 * @param string &$sql SQL assembled so far
3188 * @param string &$newLine New line about to be added to $sql
3189 * @return bool Whether $newLine contains end of the statement
3190 */
3191 public function streamStatementEnd( &$sql, &$newLine ) {
3192 if ( $this->delimiter ) {
3193 $prev = $newLine;
3194 $newLine = preg_replace(
3195 '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
3196 if ( $newLine != $prev ) {
3197 return true;
3198 }
3199 }
3200
3201 return false;
3202 }
3203
3204 /**
3205 * Database independent variable replacement. Replaces a set of variables
3206 * in an SQL statement with their contents as given by $this->getSchemaVars().
3207 *
3208 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3209 *
3210 * - '{$var}' should be used for text and is passed through the database's
3211 * addQuotes method.
3212 * - `{$var}` should be used for identifiers (e.g. table and database names).
3213 * It is passed through the database's addIdentifierQuotes method which
3214 * can be overridden if the database uses something other than backticks.
3215 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3216 * database's tableName method.
3217 * - / *i* / passes the name that follows through the database's indexName method.
3218 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3219 * its use should be avoided. In 1.24 and older, string encoding was applied.
3220 *
3221 * @param string $ins SQL statement to replace variables in
3222 * @return string The new SQL statement with variables replaced
3223 */
3224 protected function replaceVars( $ins ) {
3225 $vars = $this->getSchemaVars();
3226 return preg_replace_callback(
3227 '!
3228 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3229 \'\{\$ (\w+) }\' | # 3. addQuotes
3230 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3231 /\*\$ (\w+) \*/ # 5. leave unencoded
3232 !x',
3233 function ( $m ) use ( $vars ) {
3234 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3235 // check for both nonexistent keys *and* the empty string.
3236 if ( isset( $m[1] ) && $m[1] !== '' ) {
3237 if ( $m[1] === 'i' ) {
3238 return $this->indexName( $m[2] );
3239 } else {
3240 return $this->tableName( $m[2] );
3241 }
3242 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3243 return $this->addQuotes( $vars[$m[3]] );
3244 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3245 return $this->addIdentifierQuotes( $vars[$m[4]] );
3246 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3247 return $vars[$m[5]];
3248 } else {
3249 return $m[0];
3250 }
3251 },
3252 $ins
3253 );
3254 }
3255
3256 /**
3257 * Get schema variables. If none have been set via setSchemaVars(), then
3258 * use some defaults from the current object.
3259 *
3260 * @return array
3261 */
3262 protected function getSchemaVars() {
3263 if ( $this->mSchemaVars ) {
3264 return $this->mSchemaVars;
3265 } else {
3266 return $this->getDefaultSchemaVars();
3267 }
3268 }
3269
3270 /**
3271 * Get schema variables to use if none have been set via setSchemaVars().
3272 *
3273 * Override this in derived classes to provide variables for tables.sql
3274 * and SQL patch files.
3275 *
3276 * @return array
3277 */
3278 protected function getDefaultSchemaVars() {
3279 return [];
3280 }
3281
3282 public function lockIsFree( $lockName, $method ) {
3283 return true;
3284 }
3285
3286 public function lock( $lockName, $method, $timeout = 5 ) {
3287 $this->mNamedLocksHeld[$lockName] = 1;
3288
3289 return true;
3290 }
3291
3292 public function unlock( $lockName, $method ) {
3293 unset( $this->mNamedLocksHeld[$lockName] );
3294
3295 return true;
3296 }
3297
3298 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3299 if ( $this->writesOrCallbacksPending() ) {
3300 // This only flushes transactions to clear snapshots, not to write data
3301 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3302 throw new DBUnexpectedError(
3303 $this,
3304 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3305 );
3306 }
3307
3308 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3309 return null;
3310 }
3311
3312 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3313 if ( $this->trxLevel() ) {
3314 // There is a good chance an exception was thrown, causing any early return
3315 // from the caller. Let any error handler get a chance to issue rollback().
3316 // If there isn't one, let the error bubble up and trigger server-side rollback.
3317 $this->onTransactionResolution(
3318 function () use ( $lockKey, $fname ) {
3319 $this->unlock( $lockKey, $fname );
3320 },
3321 $fname
3322 );
3323 } else {
3324 $this->unlock( $lockKey, $fname );
3325 }
3326 } );
3327
3328 $this->commit( $fname, self::FLUSHING_INTERNAL );
3329
3330 return $unlocker;
3331 }
3332
3333 public function namedLocksEnqueue() {
3334 return false;
3335 }
3336
3337 public function tableLocksHaveTransactionScope() {
3338 return true;
3339 }
3340
3341 final public function lockTables( array $read, array $write, $method ) {
3342 if ( $this->writesOrCallbacksPending() ) {
3343 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
3344 }
3345
3346 if ( $this->tableLocksHaveTransactionScope() ) {
3347 $this->startAtomic( $method );
3348 }
3349
3350 return $this->doLockTables( $read, $write, $method );
3351 }
3352
3353 protected function doLockTables( array $read, array $write, $method ) {
3354 return true;
3355 }
3356
3357 final public function unlockTables( $method ) {
3358 if ( $this->tableLocksHaveTransactionScope() ) {
3359 $this->endAtomic( $method );
3360
3361 return true; // locks released on COMMIT/ROLLBACK
3362 }
3363
3364 return $this->doUnlockTables( $method );
3365 }
3366
3367 protected function doUnlockTables( $method ) {
3368 return true;
3369 }
3370
3371 /**
3372 * Delete a table
3373 * @param string $tableName
3374 * @param string $fName
3375 * @return bool|ResultWrapper
3376 * @since 1.18
3377 */
3378 public function dropTable( $tableName, $fName = __METHOD__ ) {
3379 if ( !$this->tableExists( $tableName, $fName ) ) {
3380 return false;
3381 }
3382 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3383
3384 return $this->query( $sql, $fName );
3385 }
3386
3387 public function getInfinity() {
3388 return 'infinity';
3389 }
3390
3391 public function encodeExpiry( $expiry ) {
3392 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
3393 ? $this->getInfinity()
3394 : $this->timestamp( $expiry );
3395 }
3396
3397 public function decodeExpiry( $expiry, $format = TS_MW ) {
3398 if ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() ) {
3399 return 'infinity';
3400 }
3401
3402 return ConvertibleTimestamp::convert( $format, $expiry );
3403 }
3404
3405 public function setBigSelects( $value = true ) {
3406 // no-op
3407 }
3408
3409 public function isReadOnly() {
3410 return ( $this->getReadOnlyReason() !== false );
3411 }
3412
3413 /**
3414 * @return string|bool Reason this DB is read-only or false if it is not
3415 */
3416 protected function getReadOnlyReason() {
3417 $reason = $this->getLBInfo( 'readOnlyReason' );
3418
3419 return is_string( $reason ) ? $reason : false;
3420 }
3421
3422 public function setTableAliases( array $aliases ) {
3423 $this->tableAliases = $aliases;
3424 }
3425
3426 /**
3427 * @return bool Whether a DB user is required to access the DB
3428 * @since 1.28
3429 */
3430 protected function requiresDatabaseUser() {
3431 return true;
3432 }
3433
3434 /**
3435 * Get the underlying binding handle, mConn
3436 *
3437 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
3438 * This catches broken callers than catch and ignore disconnection exceptions.
3439 * Unlike checking isOpen(), this is safe to call inside of open().
3440 *
3441 * @return resource|object
3442 * @throws DBUnexpectedError
3443 * @since 1.26
3444 */
3445 protected function getBindingHandle() {
3446 if ( !$this->mConn ) {
3447 throw new DBUnexpectedError(
3448 $this,
3449 'DB connection was already closed or the connection dropped.'
3450 );
3451 }
3452
3453 return $this->mConn;
3454 }
3455
3456 /**
3457 * @since 1.19
3458 * @return string
3459 */
3460 public function __toString() {
3461 return (string)$this->mConn;
3462 }
3463
3464 /**
3465 * Make sure that copies do not share the same client binding handle
3466 * @throws DBConnectionError
3467 */
3468 public function __clone() {
3469 $this->connLogger->warning(
3470 "Cloning " . static::class . " is not recomended; forking connection:\n" .
3471 ( new RuntimeException() )->getTraceAsString()
3472 );
3473
3474 if ( $this->isOpen() ) {
3475 // Open a new connection resource without messing with the old one
3476 $this->mOpened = false;
3477 $this->mConn = false;
3478 $this->mTrxEndCallbacks = []; // don't copy
3479 $this->handleSessionLoss(); // no trx or locks anymore
3480 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
3481 $this->lastPing = microtime( true );
3482 }
3483 }
3484
3485 /**
3486 * Called by serialize. Throw an exception when DB connection is serialized.
3487 * This causes problems on some database engines because the connection is
3488 * not restored on unserialize.
3489 */
3490 public function __sleep() {
3491 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3492 'the connection is not restored on wakeup.' );
3493 }
3494
3495 /**
3496 * Run a few simple sanity checks and close dangling connections
3497 */
3498 public function __destruct() {
3499 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
3500 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3501 }
3502
3503 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3504 if ( $danglingWriters ) {
3505 $fnames = implode( ', ', $danglingWriters );
3506 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3507 }
3508
3509 if ( $this->mConn ) {
3510 // Avoid connection leaks for sanity. Normally, resources close at script completion.
3511 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
3512 \MediaWiki\suppressWarnings();
3513 $this->closeConnection();
3514 \MediaWiki\restoreWarnings();
3515 $this->mConn = false;
3516 $this->mOpened = false;
3517 }
3518 }
3519 }
3520
3521 class_alias( Database::class, 'DatabaseBase' ); // b/c for old name
3522 class_alias( Database::class, 'Database' ); // b/c global alias