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