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