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