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