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