Merge "Use LinkTarget in Revision::newFromTitle"
[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 array Map of (name => 1) for locks obtained via lock() */
159 private $mNamedLocksHeld = array();
160
161 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
162 private $lazyMasterHandle;
163
164 /**
165 * @since 1.21
166 * @var resource File handle for upgrade
167 */
168 protected $fileHandle = null;
169
170 /**
171 * @since 1.22
172 * @var string[] Process cache of VIEWs names in the database
173 */
174 protected $allViews = null;
175
176 /** @var TransactionProfiler */
177 protected $trxProfiler;
178
179 public function getServerInfo() {
180 return $this->getServerVersion();
181 }
182
183 /**
184 * @return string Command delimiter used by this database engine
185 */
186 public function getDelimiter() {
187 return $this->delimiter;
188 }
189
190 /**
191 * Boolean, controls output of large amounts of debug information.
192 * @param bool|null $debug
193 * - true to enable debugging
194 * - false to disable debugging
195 * - omitted or null to do nothing
196 *
197 * @return bool|null Previous value of the flag
198 */
199 public function debug( $debug = null ) {
200 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
201 }
202
203 public function bufferResults( $buffer = null ) {
204 if ( is_null( $buffer ) ) {
205 return !(bool)( $this->mFlags & DBO_NOBUFFER );
206 } else {
207 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
208 }
209 }
210
211 /**
212 * Turns on (false) or off (true) the automatic generation and sending
213 * of a "we're sorry, but there has been a database error" page on
214 * database errors. Default is on (false). When turned off, the
215 * code should use lastErrno() and lastError() to handle the
216 * situation as appropriate.
217 *
218 * Do not use this function outside of the Database classes.
219 *
220 * @param null|bool $ignoreErrors
221 * @return bool The previous value of the flag.
222 */
223 protected function ignoreErrors( $ignoreErrors = null ) {
224 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
225 }
226
227 public function trxLevel() {
228 return $this->mTrxLevel;
229 }
230
231 public function trxTimestamp() {
232 return $this->mTrxLevel ? $this->mTrxTimestamp : null;
233 }
234
235 public function tablePrefix( $prefix = null ) {
236 return wfSetVar( $this->mTablePrefix, $prefix );
237 }
238
239 public function dbSchema( $schema = null ) {
240 return wfSetVar( $this->mSchema, $schema );
241 }
242
243 /**
244 * Set the filehandle to copy write statements to.
245 *
246 * @param resource $fh File handle
247 */
248 public function setFileHandle( $fh ) {
249 $this->fileHandle = $fh;
250 }
251
252 public function getLBInfo( $name = null ) {
253 if ( is_null( $name ) ) {
254 return $this->mLBInfo;
255 } else {
256 if ( array_key_exists( $name, $this->mLBInfo ) ) {
257 return $this->mLBInfo[$name];
258 } else {
259 return null;
260 }
261 }
262 }
263
264 public function setLBInfo( $name, $value = null ) {
265 if ( is_null( $value ) ) {
266 $this->mLBInfo = $name;
267 } else {
268 $this->mLBInfo[$name] = $value;
269 }
270 }
271
272 /**
273 * Set a lazy-connecting DB handle to the master DB (for replication status purposes)
274 *
275 * @param IDatabase $conn
276 * @since 1.27
277 */
278 public function setLazyMasterHandle( IDatabase $conn ) {
279 $this->lazyMasterHandle = $conn;
280 }
281
282 /**
283 * @return IDatabase|null
284 * @see setLazyMasterHandle()
285 * @since 1.27
286 */
287 public function getLazyMasterHandle() {
288 return $this->lazyMasterHandle;
289 }
290
291 /**
292 * @return TransactionProfiler
293 */
294 protected function getTransactionProfiler() {
295 if ( !$this->trxProfiler ) {
296 $this->trxProfiler = new TransactionProfiler();
297 }
298
299 return $this->trxProfiler;
300 }
301
302 /**
303 * @param TransactionProfiler $profiler
304 * @since 1.27
305 */
306 public function setTransactionProfiler( TransactionProfiler $profiler ) {
307 $this->trxProfiler = $profiler;
308 }
309
310 /**
311 * Returns true if this database supports (and uses) cascading deletes
312 *
313 * @return bool
314 */
315 public function cascadingDeletes() {
316 return false;
317 }
318
319 /**
320 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
321 *
322 * @return bool
323 */
324 public function cleanupTriggers() {
325 return false;
326 }
327
328 /**
329 * Returns true if this database is strict about what can be put into an IP field.
330 * Specifically, it uses a NULL value instead of an empty string.
331 *
332 * @return bool
333 */
334 public function strictIPs() {
335 return false;
336 }
337
338 /**
339 * Returns true if this database uses timestamps rather than integers
340 *
341 * @return bool
342 */
343 public function realTimestamps() {
344 return false;
345 }
346
347 public function implicitGroupby() {
348 return true;
349 }
350
351 public function implicitOrderby() {
352 return true;
353 }
354
355 /**
356 * Returns true if this database can do a native search on IP columns
357 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
358 *
359 * @return bool
360 */
361 public function searchableIPs() {
362 return false;
363 }
364
365 /**
366 * Returns true if this database can use functional indexes
367 *
368 * @return bool
369 */
370 public function functionalIndexes() {
371 return false;
372 }
373
374 public function lastQuery() {
375 return $this->mLastQuery;
376 }
377
378 public function doneWrites() {
379 return (bool)$this->mDoneWrites;
380 }
381
382 public function lastDoneWrites() {
383 return $this->mDoneWrites ?: false;
384 }
385
386 public function writesPending() {
387 return $this->mTrxLevel && $this->mTrxDoneWrites;
388 }
389
390 public function writesOrCallbacksPending() {
391 return $this->mTrxLevel && (
392 $this->mTrxDoneWrites || $this->mTrxIdleCallbacks || $this->mTrxPreCommitCallbacks
393 );
394 }
395
396 public function pendingWriteQueryDuration() {
397 return $this->mTrxLevel ? $this->mTrxWriteDuration : false;
398 }
399
400 public function pendingWriteCallers() {
401 return $this->mTrxLevel ? $this->mTrxWriteCallers : array();
402 }
403
404 public function isOpen() {
405 return $this->mOpened;
406 }
407
408 public function setFlag( $flag ) {
409 $this->mFlags |= $flag;
410 }
411
412 public function clearFlag( $flag ) {
413 $this->mFlags &= ~$flag;
414 }
415
416 public function getFlag( $flag ) {
417 return !!( $this->mFlags & $flag );
418 }
419
420 public function getProperty( $name ) {
421 return $this->$name;
422 }
423
424 public function getWikiID() {
425 if ( $this->mTablePrefix ) {
426 return "{$this->mDBname}-{$this->mTablePrefix}";
427 } else {
428 return $this->mDBname;
429 }
430 }
431
432 /**
433 * Return a path to the DBMS-specific SQL file if it exists,
434 * otherwise default SQL file
435 *
436 * @param string $filename
437 * @return string
438 */
439 private function getSqlFilePath( $filename ) {
440 global $IP;
441 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
442 if ( file_exists( $dbmsSpecificFilePath ) ) {
443 return $dbmsSpecificFilePath;
444 } else {
445 return "$IP/maintenance/$filename";
446 }
447 }
448
449 /**
450 * Return a path to the DBMS-specific schema file,
451 * otherwise default to tables.sql
452 *
453 * @return string
454 */
455 public function getSchemaPath() {
456 return $this->getSqlFilePath( 'tables.sql' );
457 }
458
459 /**
460 * Return a path to the DBMS-specific update key file,
461 * otherwise default to update-keys.sql
462 *
463 * @return string
464 */
465 public function getUpdateKeysPath() {
466 return $this->getSqlFilePath( 'update-keys.sql' );
467 }
468
469 /**
470 * Get information about an index into an object
471 * @param string $table Table name
472 * @param string $index Index name
473 * @param string $fname Calling function name
474 * @return mixed Database-specific index description class or false if the index does not exist
475 */
476 abstract function indexInfo( $table, $index, $fname = __METHOD__ );
477
478 /**
479 * Wrapper for addslashes()
480 *
481 * @param string $s String to be slashed.
482 * @return string Slashed string.
483 */
484 abstract function strencode( $s );
485
486 /**
487 * Constructor.
488 *
489 * FIXME: It is possible to construct a Database object with no associated
490 * connection object, by specifying no parameters to __construct(). This
491 * feature is deprecated and should be removed.
492 *
493 * DatabaseBase subclasses should not be constructed directly in external
494 * code. DatabaseBase::factory() should be used instead.
495 *
496 * @param array $params Parameters passed from DatabaseBase::factory()
497 */
498 function __construct( array $params ) {
499 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode;
500
501 $this->srvCache = ObjectCache::getLocalServerInstance( 'hash' );
502
503 $server = $params['host'];
504 $user = $params['user'];
505 $password = $params['password'];
506 $dbName = $params['dbname'];
507 $flags = $params['flags'];
508 $tablePrefix = $params['tablePrefix'];
509 $schema = $params['schema'];
510 $foreign = $params['foreign'];
511
512 $this->mFlags = $flags;
513 if ( $this->mFlags & DBO_DEFAULT ) {
514 if ( $wgCommandLineMode ) {
515 $this->mFlags &= ~DBO_TRX;
516 } else {
517 $this->mFlags |= DBO_TRX;
518 }
519 }
520
521 $this->mSessionVars = $params['variables'];
522
523 /** Get the default table prefix*/
524 if ( $tablePrefix === 'get from global' ) {
525 $this->mTablePrefix = $wgDBprefix;
526 } else {
527 $this->mTablePrefix = $tablePrefix;
528 }
529
530 /** Get the database schema*/
531 if ( $schema === 'get from global' ) {
532 $this->mSchema = $wgDBmwschema;
533 } else {
534 $this->mSchema = $schema;
535 }
536
537 $this->mForeign = $foreign;
538
539 if ( isset( $params['trxProfiler'] ) ) {
540 $this->trxProfiler = $params['trxProfiler']; // override
541 }
542
543 if ( $user ) {
544 $this->open( $server, $user, $password, $dbName );
545 }
546 }
547
548 /**
549 * Called by serialize. Throw an exception when DB connection is serialized.
550 * This causes problems on some database engines because the connection is
551 * not restored on unserialize.
552 */
553 public function __sleep() {
554 throw new MWException( 'Database serialization may cause problems, since ' .
555 'the connection is not restored on wakeup.' );
556 }
557
558 /**
559 * Given a DB type, construct the name of the appropriate child class of
560 * DatabaseBase. This is designed to replace all of the manual stuff like:
561 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
562 * as well as validate against the canonical list of DB types we have
563 *
564 * This factory function is mostly useful for when you need to connect to a
565 * database other than the MediaWiki default (such as for external auth,
566 * an extension, et cetera). Do not use this to connect to the MediaWiki
567 * database. Example uses in core:
568 * @see LoadBalancer::reallyOpenConnection()
569 * @see ForeignDBRepo::getMasterDB()
570 * @see WebInstallerDBConnect::execute()
571 *
572 * @since 1.18
573 *
574 * @param string $dbType A possible DB type
575 * @param array $p An array of options to pass to the constructor.
576 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
577 * @throws MWException If the database driver or extension cannot be found
578 * @return DatabaseBase|null DatabaseBase subclass or null
579 */
580 final public static function factory( $dbType, $p = array() ) {
581 $canonicalDBTypes = array(
582 'mysql' => array( 'mysqli', 'mysql' ),
583 'postgres' => array(),
584 'sqlite' => array(),
585 'oracle' => array(),
586 'mssql' => array(),
587 );
588
589 $driver = false;
590 $dbType = strtolower( $dbType );
591 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
592 $possibleDrivers = $canonicalDBTypes[$dbType];
593 if ( !empty( $p['driver'] ) ) {
594 if ( in_array( $p['driver'], $possibleDrivers ) ) {
595 $driver = $p['driver'];
596 } else {
597 throw new MWException( __METHOD__ .
598 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
599 }
600 } else {
601 foreach ( $possibleDrivers as $posDriver ) {
602 if ( extension_loaded( $posDriver ) ) {
603 $driver = $posDriver;
604 break;
605 }
606 }
607 }
608 } else {
609 $driver = $dbType;
610 }
611 if ( $driver === false ) {
612 throw new MWException( __METHOD__ .
613 " no viable database extension found for type '$dbType'" );
614 }
615
616 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
617 // and everything else doesn't use a schema (e.g. null)
618 // Although postgres and oracle support schemas, we don't use them (yet)
619 // to maintain backwards compatibility
620 $defaultSchemas = array(
621 'mssql' => 'get from global',
622 );
623
624 $class = 'Database' . ucfirst( $driver );
625 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
626 // Resolve some defaults for b/c
627 $p['host'] = isset( $p['host'] ) ? $p['host'] : false;
628 $p['user'] = isset( $p['user'] ) ? $p['user'] : false;
629 $p['password'] = isset( $p['password'] ) ? $p['password'] : false;
630 $p['dbname'] = isset( $p['dbname'] ) ? $p['dbname'] : false;
631 $p['flags'] = isset( $p['flags'] ) ? $p['flags'] : 0;
632 $p['variables'] = isset( $p['variables'] ) ? $p['variables'] : array();
633 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : 'get from global';
634 if ( !isset( $p['schema'] ) ) {
635 $p['schema'] = isset( $defaultSchemas[$dbType] ) ? $defaultSchemas[$dbType] : null;
636 }
637 $p['foreign'] = isset( $p['foreign'] ) ? $p['foreign'] : false;
638
639 return new $class( $p );
640 } else {
641 return null;
642 }
643 }
644
645 protected function installErrorHandler() {
646 $this->mPHPError = false;
647 $this->htmlErrors = ini_set( 'html_errors', '0' );
648 set_error_handler( array( $this, 'connectionErrorHandler' ) );
649 }
650
651 /**
652 * @return bool|string
653 */
654 protected function restoreErrorHandler() {
655 restore_error_handler();
656 if ( $this->htmlErrors !== false ) {
657 ini_set( 'html_errors', $this->htmlErrors );
658 }
659 if ( $this->mPHPError ) {
660 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
661 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
662
663 return $error;
664 } else {
665 return false;
666 }
667 }
668
669 /**
670 * @param int $errno
671 * @param string $errstr
672 */
673 public function connectionErrorHandler( $errno, $errstr ) {
674 $this->mPHPError = $errstr;
675 }
676
677 /**
678 * Create a log context to pass to wfLogDBError or other logging functions.
679 *
680 * @param array $extras Additional data to add to context
681 * @return array
682 */
683 protected function getLogContext( array $extras = array() ) {
684 return array_merge(
685 array(
686 'db_server' => $this->mServer,
687 'db_name' => $this->mDBname,
688 'db_user' => $this->mUser,
689 ),
690 $extras
691 );
692 }
693
694 public function close() {
695 if ( count( $this->mTrxIdleCallbacks ) ) { // sanity
696 throw new MWException( "Transaction idle callbacks still pending." );
697 }
698 if ( $this->mConn ) {
699 if ( $this->trxLevel() ) {
700 if ( !$this->mTrxAutomatic ) {
701 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
702 " performing implicit commit before closing connection!" );
703 }
704
705 $this->commit( __METHOD__, 'flush' );
706 }
707
708 $closed = $this->closeConnection();
709 $this->mConn = false;
710 } else {
711 $closed = true;
712 }
713 $this->mOpened = false;
714
715 return $closed;
716 }
717
718 /**
719 * Make sure isOpen() returns true as a sanity check
720 *
721 * @throws DBUnexpectedError
722 */
723 protected function assertOpen() {
724 if ( !$this->isOpen() ) {
725 throw new DBUnexpectedError( $this, "DB connection was already closed." );
726 }
727 }
728
729 /**
730 * Closes underlying database connection
731 * @since 1.20
732 * @return bool Whether connection was closed successfully
733 */
734 abstract protected function closeConnection();
735
736 function reportConnectionError( $error = 'Unknown error' ) {
737 $myError = $this->lastError();
738 if ( $myError ) {
739 $error = $myError;
740 }
741
742 # New method
743 throw new DBConnectionError( $this, $error );
744 }
745
746 /**
747 * The DBMS-dependent part of query()
748 *
749 * @param string $sql SQL query.
750 * @return ResultWrapper|bool Result object to feed to fetchObject,
751 * fetchRow, ...; or false on failure
752 */
753 abstract protected function doQuery( $sql );
754
755 /**
756 * Determine whether a query writes to the DB.
757 * Should return true if unsure.
758 *
759 * @param string $sql
760 * @return bool
761 */
762 protected function isWriteQuery( $sql ) {
763 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
764 }
765
766 /**
767 * Determine whether a SQL statement is sensitive to isolation level.
768 * A SQL statement is considered transactable if its result could vary
769 * depending on the transaction isolation level. Operational commands
770 * such as 'SET' and 'SHOW' are not considered to be transactable.
771 *
772 * @param string $sql
773 * @return bool
774 */
775 protected function isTransactableQuery( $sql ) {
776 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
777 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
778 }
779
780 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
781 global $wgUser;
782
783 $this->mLastQuery = $sql;
784
785 $isWriteQuery = $this->isWriteQuery( $sql );
786 if ( $isWriteQuery ) {
787 $reason = $this->getReadOnlyReason();
788 if ( $reason !== false ) {
789 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
790 }
791 # Set a flag indicating that writes have been done
792 $this->mDoneWrites = microtime( true );
793 }
794
795 # Add a comment for easy SHOW PROCESSLIST interpretation
796 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
797 $userName = $wgUser->getName();
798 if ( mb_strlen( $userName ) > 15 ) {
799 $userName = mb_substr( $userName, 0, 15 ) . '...';
800 }
801 $userName = str_replace( '/', '', $userName );
802 } else {
803 $userName = '';
804 }
805
806 // Add trace comment to the begin of the sql string, right after the operator.
807 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
808 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
809
810 if ( !$this->mTrxLevel && $this->getFlag( DBO_TRX ) && $this->isTransactableQuery( $sql ) ) {
811 $this->begin( __METHOD__ . " ($fname)" );
812 $this->mTrxAutomatic = true;
813 }
814
815 # Keep track of whether the transaction has write queries pending
816 if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $isWriteQuery ) {
817 $this->mTrxDoneWrites = true;
818 $this->getTransactionProfiler()->transactionWritingIn(
819 $this->mServer, $this->mDBname, $this->mTrxShortId );
820 }
821
822 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
823 # generalizeSQL will probably cut down the query to reasonable
824 # logging size most of the time. The substr is really just a sanity check.
825 if ( $isMaster ) {
826 $queryProf = 'query-m: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
827 $totalProf = 'DatabaseBase::query-master';
828 } else {
829 $queryProf = 'query: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
830 $totalProf = 'DatabaseBase::query';
831 }
832 # Include query transaction state
833 $queryProf .= $this->mTrxShortId ? " [TRX#{$this->mTrxShortId}]" : "";
834
835 $profiler = Profiler::instance();
836 if ( !$profiler instanceof ProfilerStub ) {
837 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
838 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
839 }
840
841 if ( $this->debug() ) {
842 wfDebugLog( 'queries', sprintf( "%s: %s", $this->mDBname, $commentedSql ) );
843 }
844
845 $queryId = MWDebug::query( $sql, $fname, $isMaster );
846
847 # Avoid fatals if close() was called
848 $this->assertOpen();
849
850 # Do the query and handle errors
851 $startTime = microtime( true );
852 $ret = $this->doQuery( $commentedSql );
853 $queryRuntime = microtime( true ) - $startTime;
854 # Log the query time and feed it into the DB trx profiler
855 $this->getTransactionProfiler()->recordQueryCompletion(
856 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
857
858 MWDebug::queryTime( $queryId );
859
860 # Try reconnecting if the connection was lost
861 if ( false === $ret && $this->wasErrorReissuable() ) {
862 # Transaction is gone, like it or not
863 $hadTrx = $this->mTrxLevel; // possible lost transaction
864 $this->mTrxLevel = 0;
865 $this->mTrxIdleCallbacks = array(); // bug 65263
866 $this->mTrxPreCommitCallbacks = array(); // bug 65263
867 wfDebug( "Connection lost, reconnecting...\n" );
868 # Stash the last error values since ping() might clear them
869 $lastError = $this->lastError();
870 $lastErrno = $this->lastErrno();
871 if ( $this->ping() ) {
872 wfDebug( "Reconnected\n" );
873 $server = $this->getServer();
874 $msg = __METHOD__ . ": lost connection to $server; reconnected";
875 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
876
877 if ( $hadTrx || $this->mNamedLocksHeld ) {
878 # Leave $ret as false and let an error be reported.
879 # Callers may catch the exception and continue to use the DB.
880 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
881 } else {
882 # Should be safe to silently retry (no trx and thus no callbacks)
883 $startTime = microtime( true );
884 $ret = $this->doQuery( $commentedSql );
885 $queryRuntime = microtime( true ) - $startTime;
886 # Log the query time and feed it into the DB trx profiler
887 $this->getTransactionProfiler()->recordQueryCompletion(
888 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
889 }
890 } else {
891 wfDebug( "Failed\n" );
892 }
893 }
894
895 if ( false === $ret ) {
896 $this->reportQueryError(
897 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
898 }
899
900 $res = $this->resultObject( $ret );
901
902 // Destroy profile sections in the opposite order to their creation
903 ScopedCallback::consume( $queryProfSection );
904 ScopedCallback::consume( $totalProfSection );
905
906 if ( $isWriteQuery && $this->mTrxLevel ) {
907 $this->mTrxWriteDuration += $queryRuntime;
908 $this->mTrxWriteCallers[] = $fname;
909 }
910
911 return $res;
912 }
913
914 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
915 if ( $this->ignoreErrors() || $tempIgnore ) {
916 wfDebug( "SQL ERROR (ignored): $error\n" );
917 } else {
918 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
919 wfLogDBError(
920 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
921 $this->getLogContext( array(
922 'method' => __METHOD__,
923 'errno' => $errno,
924 'error' => $error,
925 'sql1line' => $sql1line,
926 'fname' => $fname,
927 ) )
928 );
929 wfDebug( "SQL ERROR: " . $error . "\n" );
930 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
931 }
932 }
933
934 /**
935 * Intended to be compatible with the PEAR::DB wrapper functions.
936 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
937 *
938 * ? = scalar value, quoted as necessary
939 * ! = raw SQL bit (a function for instance)
940 * & = filename; reads the file and inserts as a blob
941 * (we don't use this though...)
942 *
943 * @param string $sql
944 * @param string $func
945 *
946 * @return array
947 */
948 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
949 /* MySQL doesn't support prepared statements (yet), so just
950 * pack up the query for reference. We'll manually replace
951 * the bits later.
952 */
953 return array( 'query' => $sql, 'func' => $func );
954 }
955
956 /**
957 * Free a prepared query, generated by prepare().
958 * @param string $prepared
959 */
960 protected function freePrepared( $prepared ) {
961 /* No-op by default */
962 }
963
964 /**
965 * Execute a prepared query with the various arguments
966 * @param string $prepared The prepared sql
967 * @param mixed $args Either an array here, or put scalars as varargs
968 *
969 * @return ResultWrapper
970 */
971 public function execute( $prepared, $args = null ) {
972 if ( !is_array( $args ) ) {
973 # Pull the var args
974 $args = func_get_args();
975 array_shift( $args );
976 }
977
978 $sql = $this->fillPrepared( $prepared['query'], $args );
979
980 return $this->query( $sql, $prepared['func'] );
981 }
982
983 /**
984 * For faking prepared SQL statements on DBs that don't support it directly.
985 *
986 * @param string $preparedQuery A 'preparable' SQL statement
987 * @param array $args Array of Arguments to fill it with
988 * @return string Executable SQL
989 */
990 public function fillPrepared( $preparedQuery, $args ) {
991 reset( $args );
992 $this->preparedArgs =& $args;
993
994 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
995 array( &$this, 'fillPreparedArg' ), $preparedQuery );
996 }
997
998 /**
999 * preg_callback func for fillPrepared()
1000 * The arguments should be in $this->preparedArgs and must not be touched
1001 * while we're doing this.
1002 *
1003 * @param array $matches
1004 * @throws DBUnexpectedError
1005 * @return string
1006 */
1007 protected function fillPreparedArg( $matches ) {
1008 switch ( $matches[1] ) {
1009 case '\\?':
1010 return '?';
1011 case '\\!':
1012 return '!';
1013 case '\\&':
1014 return '&';
1015 }
1016
1017 list( /* $n */, $arg ) = each( $this->preparedArgs );
1018
1019 switch ( $matches[1] ) {
1020 case '?':
1021 return $this->addQuotes( $arg );
1022 case '!':
1023 return $arg;
1024 case '&':
1025 # return $this->addQuotes( file_get_contents( $arg ) );
1026 throw new DBUnexpectedError(
1027 $this,
1028 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1029 );
1030 default:
1031 throw new DBUnexpectedError(
1032 $this,
1033 'Received invalid match. This should never happen!'
1034 );
1035 }
1036 }
1037
1038 public function freeResult( $res ) {
1039 }
1040
1041 public function selectField(
1042 $table, $var, $cond = '', $fname = __METHOD__, $options = array()
1043 ) {
1044 if ( $var === '*' ) { // sanity
1045 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1046 }
1047
1048 if ( !is_array( $options ) ) {
1049 $options = array( $options );
1050 }
1051
1052 $options['LIMIT'] = 1;
1053
1054 $res = $this->select( $table, $var, $cond, $fname, $options );
1055 if ( $res === false || !$this->numRows( $res ) ) {
1056 return false;
1057 }
1058
1059 $row = $this->fetchRow( $res );
1060
1061 if ( $row !== false ) {
1062 return reset( $row );
1063 } else {
1064 return false;
1065 }
1066 }
1067
1068 public function selectFieldValues(
1069 $table, $var, $cond = '', $fname = __METHOD__, $options = array(), $join_conds = array()
1070 ) {
1071 if ( $var === '*' ) { // sanity
1072 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1073 }
1074
1075 if ( !is_array( $options ) ) {
1076 $options = array( $options );
1077 }
1078
1079 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1080 if ( $res === false ) {
1081 return false;
1082 }
1083
1084 $values = array();
1085 foreach ( $res as $row ) {
1086 $values[] = $row->$var;
1087 }
1088
1089 return $values;
1090 }
1091
1092 /**
1093 * Returns an optional USE INDEX clause to go after the table, and a
1094 * string to go at the end of the query.
1095 *
1096 * @param array $options Associative array of options to be turned into
1097 * an SQL query, valid keys are listed in the function.
1098 * @return array
1099 * @see DatabaseBase::select()
1100 */
1101 public function makeSelectOptions( $options ) {
1102 $preLimitTail = $postLimitTail = '';
1103 $startOpts = '';
1104
1105 $noKeyOptions = array();
1106
1107 foreach ( $options as $key => $option ) {
1108 if ( is_numeric( $key ) ) {
1109 $noKeyOptions[$option] = true;
1110 }
1111 }
1112
1113 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1114
1115 $preLimitTail .= $this->makeOrderBy( $options );
1116
1117 // if (isset($options['LIMIT'])) {
1118 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1119 // isset($options['OFFSET']) ? $options['OFFSET']
1120 // : false);
1121 // }
1122
1123 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1124 $postLimitTail .= ' FOR UPDATE';
1125 }
1126
1127 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1128 $postLimitTail .= ' LOCK IN SHARE MODE';
1129 }
1130
1131 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1132 $startOpts .= 'DISTINCT';
1133 }
1134
1135 # Various MySQL extensions
1136 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1137 $startOpts .= ' /*! STRAIGHT_JOIN */';
1138 }
1139
1140 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1141 $startOpts .= ' HIGH_PRIORITY';
1142 }
1143
1144 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1145 $startOpts .= ' SQL_BIG_RESULT';
1146 }
1147
1148 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1149 $startOpts .= ' SQL_BUFFER_RESULT';
1150 }
1151
1152 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1153 $startOpts .= ' SQL_SMALL_RESULT';
1154 }
1155
1156 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1157 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1158 }
1159
1160 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1161 $startOpts .= ' SQL_CACHE';
1162 }
1163
1164 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1165 $startOpts .= ' SQL_NO_CACHE';
1166 }
1167
1168 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1169 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1170 } else {
1171 $useIndex = '';
1172 }
1173
1174 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1175 }
1176
1177 /**
1178 * Returns an optional GROUP BY with an optional HAVING
1179 *
1180 * @param array $options Associative array of options
1181 * @return string
1182 * @see DatabaseBase::select()
1183 * @since 1.21
1184 */
1185 public function makeGroupByWithHaving( $options ) {
1186 $sql = '';
1187 if ( isset( $options['GROUP BY'] ) ) {
1188 $gb = is_array( $options['GROUP BY'] )
1189 ? implode( ',', $options['GROUP BY'] )
1190 : $options['GROUP BY'];
1191 $sql .= ' GROUP BY ' . $gb;
1192 }
1193 if ( isset( $options['HAVING'] ) ) {
1194 $having = is_array( $options['HAVING'] )
1195 ? $this->makeList( $options['HAVING'], LIST_AND )
1196 : $options['HAVING'];
1197 $sql .= ' HAVING ' . $having;
1198 }
1199
1200 return $sql;
1201 }
1202
1203 /**
1204 * Returns an optional ORDER BY
1205 *
1206 * @param array $options Associative array of options
1207 * @return string
1208 * @see DatabaseBase::select()
1209 * @since 1.21
1210 */
1211 public function makeOrderBy( $options ) {
1212 if ( isset( $options['ORDER BY'] ) ) {
1213 $ob = is_array( $options['ORDER BY'] )
1214 ? implode( ',', $options['ORDER BY'] )
1215 : $options['ORDER BY'];
1216
1217 return ' ORDER BY ' . $ob;
1218 }
1219
1220 return '';
1221 }
1222
1223 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1224 $options = array(), $join_conds = array() ) {
1225 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1226
1227 return $this->query( $sql, $fname );
1228 }
1229
1230 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1231 $options = array(), $join_conds = array()
1232 ) {
1233 if ( is_array( $vars ) ) {
1234 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1235 }
1236
1237 $options = (array)$options;
1238 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1239 ? $options['USE INDEX']
1240 : array();
1241
1242 if ( is_array( $table ) ) {
1243 $from = ' FROM ' .
1244 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1245 } elseif ( $table != '' ) {
1246 if ( $table[0] == ' ' ) {
1247 $from = ' FROM ' . $table;
1248 } else {
1249 $from = ' FROM ' .
1250 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1251 }
1252 } else {
1253 $from = '';
1254 }
1255
1256 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1257 $this->makeSelectOptions( $options );
1258
1259 if ( !empty( $conds ) ) {
1260 if ( is_array( $conds ) ) {
1261 $conds = $this->makeList( $conds, LIST_AND );
1262 }
1263 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1264 } else {
1265 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1266 }
1267
1268 if ( isset( $options['LIMIT'] ) ) {
1269 $sql = $this->limitResult( $sql, $options['LIMIT'],
1270 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1271 }
1272 $sql = "$sql $postLimitTail";
1273
1274 if ( isset( $options['EXPLAIN'] ) ) {
1275 $sql = 'EXPLAIN ' . $sql;
1276 }
1277
1278 return $sql;
1279 }
1280
1281 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1282 $options = array(), $join_conds = array()
1283 ) {
1284 $options = (array)$options;
1285 $options['LIMIT'] = 1;
1286 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1287
1288 if ( $res === false ) {
1289 return false;
1290 }
1291
1292 if ( !$this->numRows( $res ) ) {
1293 return false;
1294 }
1295
1296 $obj = $this->fetchObject( $res );
1297
1298 return $obj;
1299 }
1300
1301 public function estimateRowCount(
1302 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = array()
1303 ) {
1304 $rows = 0;
1305 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1306
1307 if ( $res ) {
1308 $row = $this->fetchRow( $res );
1309 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1310 }
1311
1312 return $rows;
1313 }
1314
1315 public function selectRowCount(
1316 $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = array(), $join_conds = array()
1317 ) {
1318 $rows = 0;
1319 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1320 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1321
1322 if ( $res ) {
1323 $row = $this->fetchRow( $res );
1324 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1325 }
1326
1327 return $rows;
1328 }
1329
1330 /**
1331 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1332 * It's only slightly flawed. Don't use for anything important.
1333 *
1334 * @param string $sql A SQL Query
1335 *
1336 * @return string
1337 */
1338 protected static function generalizeSQL( $sql ) {
1339 # This does the same as the regexp below would do, but in such a way
1340 # as to avoid crashing php on some large strings.
1341 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1342
1343 $sql = str_replace( "\\\\", '', $sql );
1344 $sql = str_replace( "\\'", '', $sql );
1345 $sql = str_replace( "\\\"", '', $sql );
1346 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1347 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1348
1349 # All newlines, tabs, etc replaced by single space
1350 $sql = preg_replace( '/\s+/', ' ', $sql );
1351
1352 # All numbers => N,
1353 # except the ones surrounded by characters, e.g. l10n
1354 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1355 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1356
1357 return $sql;
1358 }
1359
1360 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1361 $info = $this->fieldInfo( $table, $field );
1362
1363 return (bool)$info;
1364 }
1365
1366 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1367 if ( !$this->tableExists( $table ) ) {
1368 return null;
1369 }
1370
1371 $info = $this->indexInfo( $table, $index, $fname );
1372 if ( is_null( $info ) ) {
1373 return null;
1374 } else {
1375 return $info !== false;
1376 }
1377 }
1378
1379 public function tableExists( $table, $fname = __METHOD__ ) {
1380 $table = $this->tableName( $table );
1381 $old = $this->ignoreErrors( true );
1382 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1383 $this->ignoreErrors( $old );
1384
1385 return (bool)$res;
1386 }
1387
1388 public function indexUnique( $table, $index ) {
1389 $indexInfo = $this->indexInfo( $table, $index );
1390
1391 if ( !$indexInfo ) {
1392 return null;
1393 }
1394
1395 return !$indexInfo[0]->Non_unique;
1396 }
1397
1398 /**
1399 * Helper for DatabaseBase::insert().
1400 *
1401 * @param array $options
1402 * @return string
1403 */
1404 protected function makeInsertOptions( $options ) {
1405 return implode( ' ', $options );
1406 }
1407
1408 public function insert( $table, $a, $fname = __METHOD__, $options = array() ) {
1409 # No rows to insert, easy just return now
1410 if ( !count( $a ) ) {
1411 return true;
1412 }
1413
1414 $table = $this->tableName( $table );
1415
1416 if ( !is_array( $options ) ) {
1417 $options = array( $options );
1418 }
1419
1420 $fh = null;
1421 if ( isset( $options['fileHandle'] ) ) {
1422 $fh = $options['fileHandle'];
1423 }
1424 $options = $this->makeInsertOptions( $options );
1425
1426 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1427 $multi = true;
1428 $keys = array_keys( $a[0] );
1429 } else {
1430 $multi = false;
1431 $keys = array_keys( $a );
1432 }
1433
1434 $sql = 'INSERT ' . $options .
1435 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1436
1437 if ( $multi ) {
1438 $first = true;
1439 foreach ( $a as $row ) {
1440 if ( $first ) {
1441 $first = false;
1442 } else {
1443 $sql .= ',';
1444 }
1445 $sql .= '(' . $this->makeList( $row ) . ')';
1446 }
1447 } else {
1448 $sql .= '(' . $this->makeList( $a ) . ')';
1449 }
1450
1451 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1452 return false;
1453 } elseif ( $fh !== null ) {
1454 return true;
1455 }
1456
1457 return (bool)$this->query( $sql, $fname );
1458 }
1459
1460 /**
1461 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1462 *
1463 * @param array $options
1464 * @return array
1465 */
1466 protected function makeUpdateOptionsArray( $options ) {
1467 if ( !is_array( $options ) ) {
1468 $options = array( $options );
1469 }
1470
1471 $opts = array();
1472
1473 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1474 $opts[] = $this->lowPriorityOption();
1475 }
1476
1477 if ( in_array( 'IGNORE', $options ) ) {
1478 $opts[] = 'IGNORE';
1479 }
1480
1481 return $opts;
1482 }
1483
1484 /**
1485 * Make UPDATE options for the DatabaseBase::update function
1486 *
1487 * @param array $options The options passed to DatabaseBase::update
1488 * @return string
1489 */
1490 protected function makeUpdateOptions( $options ) {
1491 $opts = $this->makeUpdateOptionsArray( $options );
1492
1493 return implode( ' ', $opts );
1494 }
1495
1496 function update( $table, $values, $conds, $fname = __METHOD__, $options = array() ) {
1497 $table = $this->tableName( $table );
1498 $opts = $this->makeUpdateOptions( $options );
1499 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1500
1501 if ( $conds !== array() && $conds !== '*' ) {
1502 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1503 }
1504
1505 return $this->query( $sql, $fname );
1506 }
1507
1508 public function makeList( $a, $mode = LIST_COMMA ) {
1509 if ( !is_array( $a ) ) {
1510 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1511 }
1512
1513 $first = true;
1514 $list = '';
1515
1516 foreach ( $a as $field => $value ) {
1517 if ( !$first ) {
1518 if ( $mode == LIST_AND ) {
1519 $list .= ' AND ';
1520 } elseif ( $mode == LIST_OR ) {
1521 $list .= ' OR ';
1522 } else {
1523 $list .= ',';
1524 }
1525 } else {
1526 $first = false;
1527 }
1528
1529 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
1530 $list .= "($value)";
1531 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
1532 $list .= "$value";
1533 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
1534 // Remove null from array to be handled separately if found
1535 $includeNull = false;
1536 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1537 $includeNull = true;
1538 unset( $value[$nullKey] );
1539 }
1540 if ( count( $value ) == 0 && !$includeNull ) {
1541 throw new MWException( __METHOD__ . ": empty input for field $field" );
1542 } elseif ( count( $value ) == 0 ) {
1543 // only check if $field is null
1544 $list .= "$field IS NULL";
1545 } else {
1546 // IN clause contains at least one valid element
1547 if ( $includeNull ) {
1548 // Group subconditions to ensure correct precedence
1549 $list .= '(';
1550 }
1551 if ( count( $value ) == 1 ) {
1552 // Special-case single values, as IN isn't terribly efficient
1553 // Don't necessarily assume the single key is 0; we don't
1554 // enforce linear numeric ordering on other arrays here.
1555 $value = array_values( $value );
1556 $list .= $field . " = " . $this->addQuotes( $value[0] );
1557 } else {
1558 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1559 }
1560 // if null present in array, append IS NULL
1561 if ( $includeNull ) {
1562 $list .= " OR $field IS NULL)";
1563 }
1564 }
1565 } elseif ( $value === null ) {
1566 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1567 $list .= "$field IS ";
1568 } elseif ( $mode == LIST_SET ) {
1569 $list .= "$field = ";
1570 }
1571 $list .= 'NULL';
1572 } else {
1573 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1574 $list .= "$field = ";
1575 }
1576 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1577 }
1578 }
1579
1580 return $list;
1581 }
1582
1583 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1584 $conds = array();
1585
1586 foreach ( $data as $base => $sub ) {
1587 if ( count( $sub ) ) {
1588 $conds[] = $this->makeList(
1589 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1590 LIST_AND );
1591 }
1592 }
1593
1594 if ( $conds ) {
1595 return $this->makeList( $conds, LIST_OR );
1596 } else {
1597 // Nothing to search for...
1598 return false;
1599 }
1600 }
1601
1602 /**
1603 * Return aggregated value alias
1604 *
1605 * @param array $valuedata
1606 * @param string $valuename
1607 *
1608 * @return string
1609 */
1610 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1611 return $valuename;
1612 }
1613
1614 public function bitNot( $field ) {
1615 return "(~$field)";
1616 }
1617
1618 public function bitAnd( $fieldLeft, $fieldRight ) {
1619 return "($fieldLeft & $fieldRight)";
1620 }
1621
1622 public function bitOr( $fieldLeft, $fieldRight ) {
1623 return "($fieldLeft | $fieldRight)";
1624 }
1625
1626 public function buildConcat( $stringList ) {
1627 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1628 }
1629
1630 public function buildGroupConcatField(
1631 $delim, $table, $field, $conds = '', $join_conds = array()
1632 ) {
1633 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1634
1635 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
1636 }
1637
1638 public function selectDB( $db ) {
1639 # Stub. Shouldn't cause serious problems if it's not overridden, but
1640 # if your database engine supports a concept similar to MySQL's
1641 # databases you may as well.
1642 $this->mDBname = $db;
1643
1644 return true;
1645 }
1646
1647 public function getDBname() {
1648 return $this->mDBname;
1649 }
1650
1651 public function getServer() {
1652 return $this->mServer;
1653 }
1654
1655 /**
1656 * Format a table name ready for use in constructing an SQL query
1657 *
1658 * This does two important things: it quotes the table names to clean them up,
1659 * and it adds a table prefix if only given a table name with no quotes.
1660 *
1661 * All functions of this object which require a table name call this function
1662 * themselves. Pass the canonical name to such functions. This is only needed
1663 * when calling query() directly.
1664 *
1665 * @param string $name Database table name
1666 * @param string $format One of:
1667 * quoted - Automatically pass the table name through addIdentifierQuotes()
1668 * so that it can be used in a query.
1669 * raw - Do not add identifier quotes to the table name
1670 * @return string Full database name
1671 */
1672 public function tableName( $name, $format = 'quoted' ) {
1673 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
1674 # Skip the entire process when we have a string quoted on both ends.
1675 # Note that we check the end so that we will still quote any use of
1676 # use of `database`.table. But won't break things if someone wants
1677 # to query a database table with a dot in the name.
1678 if ( $this->isQuotedIdentifier( $name ) ) {
1679 return $name;
1680 }
1681
1682 # Lets test for any bits of text that should never show up in a table
1683 # name. Basically anything like JOIN or ON which are actually part of
1684 # SQL queries, but may end up inside of the table value to combine
1685 # sql. Such as how the API is doing.
1686 # Note that we use a whitespace test rather than a \b test to avoid
1687 # any remote case where a word like on may be inside of a table name
1688 # surrounded by symbols which may be considered word breaks.
1689 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1690 return $name;
1691 }
1692
1693 # Split database and table into proper variables.
1694 # We reverse the explode so that database.table and table both output
1695 # the correct table.
1696 $dbDetails = explode( '.', $name, 3 );
1697 if ( count( $dbDetails ) == 3 ) {
1698 list( $database, $schema, $table ) = $dbDetails;
1699 # We don't want any prefix added in this case
1700 $prefix = '';
1701 } elseif ( count( $dbDetails ) == 2 ) {
1702 list( $database, $table ) = $dbDetails;
1703 # We don't want any prefix added in this case
1704 # In dbs that support it, $database may actually be the schema
1705 # but that doesn't affect any of the functionality here
1706 $prefix = '';
1707 $schema = null;
1708 } else {
1709 list( $table ) = $dbDetails;
1710 if ( $wgSharedDB !== null # We have a shared database
1711 && $this->mForeign == false # We're not working on a foreign database
1712 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
1713 && in_array( $table, $wgSharedTables ) # A shared table is selected
1714 ) {
1715 $database = $wgSharedDB;
1716 $schema = $wgSharedSchema === null ? $this->mSchema : $wgSharedSchema;
1717 $prefix = $wgSharedPrefix === null ? $this->mTablePrefix : $wgSharedPrefix;
1718 } else {
1719 $database = null;
1720 $schema = $this->mSchema; # Default schema
1721 $prefix = $this->mTablePrefix; # Default prefix
1722 }
1723 }
1724
1725 # Quote $table and apply the prefix if not quoted.
1726 # $tableName might be empty if this is called from Database::replaceVars()
1727 $tableName = "{$prefix}{$table}";
1728 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
1729 $tableName = $this->addIdentifierQuotes( $tableName );
1730 }
1731
1732 # Quote $schema and merge it with the table name if needed
1733 if ( strlen( $schema ) ) {
1734 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1735 $schema = $this->addIdentifierQuotes( $schema );
1736 }
1737 $tableName = $schema . '.' . $tableName;
1738 }
1739
1740 # Quote $database and merge it with the table name if needed
1741 if ( $database !== null ) {
1742 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1743 $database = $this->addIdentifierQuotes( $database );
1744 }
1745 $tableName = $database . '.' . $tableName;
1746 }
1747
1748 return $tableName;
1749 }
1750
1751 /**
1752 * Fetch a number of table names into an array
1753 * This is handy when you need to construct SQL for joins
1754 *
1755 * Example:
1756 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1757 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1758 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1759 *
1760 * @return array
1761 */
1762 public function tableNames() {
1763 $inArray = func_get_args();
1764 $retVal = array();
1765
1766 foreach ( $inArray as $name ) {
1767 $retVal[$name] = $this->tableName( $name );
1768 }
1769
1770 return $retVal;
1771 }
1772
1773 /**
1774 * Fetch a number of table names into an zero-indexed numerical array
1775 * This is handy when you need to construct SQL for joins
1776 *
1777 * Example:
1778 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1779 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1780 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1781 *
1782 * @return array
1783 */
1784 public function tableNamesN() {
1785 $inArray = func_get_args();
1786 $retVal = array();
1787
1788 foreach ( $inArray as $name ) {
1789 $retVal[] = $this->tableName( $name );
1790 }
1791
1792 return $retVal;
1793 }
1794
1795 /**
1796 * Get an aliased table name
1797 * e.g. tableName AS newTableName
1798 *
1799 * @param string $name Table name, see tableName()
1800 * @param string|bool $alias Alias (optional)
1801 * @return string SQL name for aliased table. Will not alias a table to its own name
1802 */
1803 public function tableNameWithAlias( $name, $alias = false ) {
1804 if ( !$alias || $alias == $name ) {
1805 return $this->tableName( $name );
1806 } else {
1807 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1808 }
1809 }
1810
1811 /**
1812 * Gets an array of aliased table names
1813 *
1814 * @param array $tables Array( [alias] => table )
1815 * @return string[] See tableNameWithAlias()
1816 */
1817 public function tableNamesWithAlias( $tables ) {
1818 $retval = array();
1819 foreach ( $tables as $alias => $table ) {
1820 if ( is_numeric( $alias ) ) {
1821 $alias = $table;
1822 }
1823 $retval[] = $this->tableNameWithAlias( $table, $alias );
1824 }
1825
1826 return $retval;
1827 }
1828
1829 /**
1830 * Get an aliased field name
1831 * e.g. fieldName AS newFieldName
1832 *
1833 * @param string $name Field name
1834 * @param string|bool $alias Alias (optional)
1835 * @return string SQL name for aliased field. Will not alias a field to its own name
1836 */
1837 public function fieldNameWithAlias( $name, $alias = false ) {
1838 if ( !$alias || (string)$alias === (string)$name ) {
1839 return $name;
1840 } else {
1841 return $name . ' AS ' . $alias; // PostgreSQL needs AS
1842 }
1843 }
1844
1845 /**
1846 * Gets an array of aliased field names
1847 *
1848 * @param array $fields Array( [alias] => field )
1849 * @return string[] See fieldNameWithAlias()
1850 */
1851 public function fieldNamesWithAlias( $fields ) {
1852 $retval = array();
1853 foreach ( $fields as $alias => $field ) {
1854 if ( is_numeric( $alias ) ) {
1855 $alias = $field;
1856 }
1857 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1858 }
1859
1860 return $retval;
1861 }
1862
1863 /**
1864 * Get the aliased table name clause for a FROM clause
1865 * which might have a JOIN and/or USE INDEX clause
1866 *
1867 * @param array $tables ( [alias] => table )
1868 * @param array $use_index Same as for select()
1869 * @param array $join_conds Same as for select()
1870 * @return string
1871 */
1872 protected function tableNamesWithUseIndexOrJOIN(
1873 $tables, $use_index = array(), $join_conds = array()
1874 ) {
1875 $ret = array();
1876 $retJOIN = array();
1877 $use_index = (array)$use_index;
1878 $join_conds = (array)$join_conds;
1879
1880 foreach ( $tables as $alias => $table ) {
1881 if ( !is_string( $alias ) ) {
1882 // No alias? Set it equal to the table name
1883 $alias = $table;
1884 }
1885 // Is there a JOIN clause for this table?
1886 if ( isset( $join_conds[$alias] ) ) {
1887 list( $joinType, $conds ) = $join_conds[$alias];
1888 $tableClause = $joinType;
1889 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1890 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1891 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1892 if ( $use != '' ) {
1893 $tableClause .= ' ' . $use;
1894 }
1895 }
1896 $on = $this->makeList( (array)$conds, LIST_AND );
1897 if ( $on != '' ) {
1898 $tableClause .= ' ON (' . $on . ')';
1899 }
1900
1901 $retJOIN[] = $tableClause;
1902 } elseif ( isset( $use_index[$alias] ) ) {
1903 // Is there an INDEX clause for this table?
1904 $tableClause = $this->tableNameWithAlias( $table, $alias );
1905 $tableClause .= ' ' . $this->useIndexClause(
1906 implode( ',', (array)$use_index[$alias] )
1907 );
1908
1909 $ret[] = $tableClause;
1910 } else {
1911 $tableClause = $this->tableNameWithAlias( $table, $alias );
1912
1913 $ret[] = $tableClause;
1914 }
1915 }
1916
1917 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1918 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
1919 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
1920
1921 // Compile our final table clause
1922 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
1923 }
1924
1925 /**
1926 * Get the name of an index in a given table.
1927 *
1928 * @protected Don't use outside of DatabaseBase and childs
1929 * @param string $index
1930 * @return string
1931 */
1932 protected function indexName( $index ) {
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 $vars = $this->getSchemaVars();
3101 return preg_replace_callback(
3102 '!
3103 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3104 \'\{\$ (\w+) }\' | # 3. addQuotes
3105 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3106 /\*\$ (\w+) \*/ # 5. leave unencoded
3107 !x',
3108 function ( $m ) use ( $vars ) {
3109 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3110 // check for both nonexistent keys *and* the empty string.
3111 if ( isset( $m[1] ) && $m[1] !== '' ) {
3112 if ( $m[1] === 'i' ) {
3113 return $this->indexName( $m[2] );
3114 } else {
3115 return $this->tableName( $m[2] );
3116 }
3117 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3118 return $this->addQuotes( $vars[$m[3]] );
3119 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3120 return $this->addIdentifierQuotes( $vars[$m[4]] );
3121 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3122 return $vars[$m[5]];
3123 } else {
3124 return $m[0];
3125 }
3126 },
3127 $ins
3128 );
3129 }
3130
3131 /**
3132 * Get schema variables. If none have been set via setSchemaVars(), then
3133 * use some defaults from the current object.
3134 *
3135 * @return array
3136 */
3137 protected function getSchemaVars() {
3138 if ( $this->mSchemaVars ) {
3139 return $this->mSchemaVars;
3140 } else {
3141 return $this->getDefaultSchemaVars();
3142 }
3143 }
3144
3145 /**
3146 * Get schema variables to use if none have been set via setSchemaVars().
3147 *
3148 * Override this in derived classes to provide variables for tables.sql
3149 * and SQL patch files.
3150 *
3151 * @return array
3152 */
3153 protected function getDefaultSchemaVars() {
3154 return array();
3155 }
3156
3157 public function lockIsFree( $lockName, $method ) {
3158 return true;
3159 }
3160
3161 public function lock( $lockName, $method, $timeout = 5 ) {
3162 $this->mNamedLocksHeld[$lockName] = 1;
3163
3164 return true;
3165 }
3166
3167 public function unlock( $lockName, $method ) {
3168 unset( $this->mNamedLocksHeld[$lockName] );
3169
3170 return true;
3171 }
3172
3173 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3174 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3175 return null;
3176 }
3177
3178 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3179 $this->commit( __METHOD__, 'flush' );
3180 $this->unlock( $lockKey, $fname );
3181 } );
3182
3183 $this->commit( __METHOD__, 'flush' );
3184
3185 return $unlocker;
3186 }
3187
3188 public function namedLocksEnqueue() {
3189 return false;
3190 }
3191
3192 /**
3193 * Lock specific tables
3194 *
3195 * @param array $read Array of tables to lock for read access
3196 * @param array $write Array of tables to lock for write access
3197 * @param string $method Name of caller
3198 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3199 * @return bool
3200 */
3201 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3202 return true;
3203 }
3204
3205 /**
3206 * Unlock specific tables
3207 *
3208 * @param string $method The caller
3209 * @return bool
3210 */
3211 public function unlockTables( $method ) {
3212 return true;
3213 }
3214
3215 /**
3216 * Delete a table
3217 * @param string $tableName
3218 * @param string $fName
3219 * @return bool|ResultWrapper
3220 * @since 1.18
3221 */
3222 public function dropTable( $tableName, $fName = __METHOD__ ) {
3223 if ( !$this->tableExists( $tableName, $fName ) ) {
3224 return false;
3225 }
3226 $sql = "DROP TABLE " . $this->tableName( $tableName );
3227 if ( $this->cascadingDeletes() ) {
3228 $sql .= " CASCADE";
3229 }
3230
3231 return $this->query( $sql, $fName );
3232 }
3233
3234 /**
3235 * Get search engine class. All subclasses of this need to implement this
3236 * if they wish to use searching.
3237 *
3238 * @return string
3239 */
3240 public function getSearchEngine() {
3241 return 'SearchEngineDummy';
3242 }
3243
3244 public function getInfinity() {
3245 return 'infinity';
3246 }
3247
3248 public function encodeExpiry( $expiry ) {
3249 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
3250 ? $this->getInfinity()
3251 : $this->timestamp( $expiry );
3252 }
3253
3254 public function decodeExpiry( $expiry, $format = TS_MW ) {
3255 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
3256 ? 'infinity'
3257 : wfTimestamp( $format, $expiry );
3258 }
3259
3260 public function setBigSelects( $value = true ) {
3261 // no-op
3262 }
3263
3264 public function isReadOnly() {
3265 return ( $this->getReadOnlyReason() !== false );
3266 }
3267
3268 /**
3269 * @return string|bool Reason this DB is read-only or false if it is not
3270 */
3271 protected function getReadOnlyReason() {
3272 $reason = $this->getLBInfo( 'readOnlyReason' );
3273
3274 return is_string( $reason ) ? $reason : false;
3275 }
3276
3277 /**
3278 * @since 1.19
3279 * @return string
3280 */
3281 public function __toString() {
3282 return (string)$this->mConn;
3283 }
3284
3285 /**
3286 * Run a few simple sanity checks
3287 */
3288 public function __destruct() {
3289 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
3290 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3291 }
3292 if ( count( $this->mTrxIdleCallbacks ) || count( $this->mTrxPreCommitCallbacks ) ) {
3293 $callers = array();
3294 foreach ( $this->mTrxIdleCallbacks as $callbackInfo ) {
3295 $callers[] = $callbackInfo[1];
3296 }
3297 $callers = implode( ', ', $callers );
3298 trigger_error( "DB transaction callbacks still pending (from $callers)." );
3299 }
3300 }
3301 }
3302
3303 /**
3304 * @since 1.27
3305 */
3306 abstract class Database extends DatabaseBase {
3307 // B/C until nothing type hints for DatabaseBase
3308 // @TODO: finish renaming DatabaseBase => Database
3309 }