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