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