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