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