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