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