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