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