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