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