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