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