database: Add extra sanity check to selectFieldValues()
[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" );
1073 } elseif ( !is_string( $var ) ) { // sanity
1074 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1075 }
1076
1077 if ( !is_array( $options ) ) {
1078 $options = array( $options );
1079 }
1080
1081 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1082 if ( $res === false ) {
1083 return false;
1084 }
1085
1086 $values = array();
1087 foreach ( $res as $row ) {
1088 $values[] = $row->$var;
1089 }
1090
1091 return $values;
1092 }
1093
1094 /**
1095 * Returns an optional USE INDEX clause to go after the table, and a
1096 * string to go at the end of the query.
1097 *
1098 * @param array $options Associative array of options to be turned into
1099 * an SQL query, valid keys are listed in the function.
1100 * @return array
1101 * @see DatabaseBase::select()
1102 */
1103 public function makeSelectOptions( $options ) {
1104 $preLimitTail = $postLimitTail = '';
1105 $startOpts = '';
1106
1107 $noKeyOptions = array();
1108
1109 foreach ( $options as $key => $option ) {
1110 if ( is_numeric( $key ) ) {
1111 $noKeyOptions[$option] = true;
1112 }
1113 }
1114
1115 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1116
1117 $preLimitTail .= $this->makeOrderBy( $options );
1118
1119 // if (isset($options['LIMIT'])) {
1120 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1121 // isset($options['OFFSET']) ? $options['OFFSET']
1122 // : false);
1123 // }
1124
1125 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1126 $postLimitTail .= ' FOR UPDATE';
1127 }
1128
1129 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1130 $postLimitTail .= ' LOCK IN SHARE MODE';
1131 }
1132
1133 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1134 $startOpts .= 'DISTINCT';
1135 }
1136
1137 # Various MySQL extensions
1138 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1139 $startOpts .= ' /*! STRAIGHT_JOIN */';
1140 }
1141
1142 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1143 $startOpts .= ' HIGH_PRIORITY';
1144 }
1145
1146 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1147 $startOpts .= ' SQL_BIG_RESULT';
1148 }
1149
1150 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1151 $startOpts .= ' SQL_BUFFER_RESULT';
1152 }
1153
1154 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1155 $startOpts .= ' SQL_SMALL_RESULT';
1156 }
1157
1158 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1159 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1160 }
1161
1162 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1163 $startOpts .= ' SQL_CACHE';
1164 }
1165
1166 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1167 $startOpts .= ' SQL_NO_CACHE';
1168 }
1169
1170 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1171 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1172 } else {
1173 $useIndex = '';
1174 }
1175
1176 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1177 }
1178
1179 /**
1180 * Returns an optional GROUP BY with an optional HAVING
1181 *
1182 * @param array $options Associative array of options
1183 * @return string
1184 * @see DatabaseBase::select()
1185 * @since 1.21
1186 */
1187 public function makeGroupByWithHaving( $options ) {
1188 $sql = '';
1189 if ( isset( $options['GROUP BY'] ) ) {
1190 $gb = is_array( $options['GROUP BY'] )
1191 ? implode( ',', $options['GROUP BY'] )
1192 : $options['GROUP BY'];
1193 $sql .= ' GROUP BY ' . $gb;
1194 }
1195 if ( isset( $options['HAVING'] ) ) {
1196 $having = is_array( $options['HAVING'] )
1197 ? $this->makeList( $options['HAVING'], LIST_AND )
1198 : $options['HAVING'];
1199 $sql .= ' HAVING ' . $having;
1200 }
1201
1202 return $sql;
1203 }
1204
1205 /**
1206 * Returns an optional ORDER BY
1207 *
1208 * @param array $options Associative array of options
1209 * @return string
1210 * @see DatabaseBase::select()
1211 * @since 1.21
1212 */
1213 public function makeOrderBy( $options ) {
1214 if ( isset( $options['ORDER BY'] ) ) {
1215 $ob = is_array( $options['ORDER BY'] )
1216 ? implode( ',', $options['ORDER BY'] )
1217 : $options['ORDER BY'];
1218
1219 return ' ORDER BY ' . $ob;
1220 }
1221
1222 return '';
1223 }
1224
1225 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1226 $options = array(), $join_conds = array() ) {
1227 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1228
1229 return $this->query( $sql, $fname );
1230 }
1231
1232 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1233 $options = array(), $join_conds = array()
1234 ) {
1235 if ( is_array( $vars ) ) {
1236 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1237 }
1238
1239 $options = (array)$options;
1240 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1241 ? $options['USE INDEX']
1242 : array();
1243
1244 if ( is_array( $table ) ) {
1245 $from = ' FROM ' .
1246 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1247 } elseif ( $table != '' ) {
1248 if ( $table[0] == ' ' ) {
1249 $from = ' FROM ' . $table;
1250 } else {
1251 $from = ' FROM ' .
1252 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1253 }
1254 } else {
1255 $from = '';
1256 }
1257
1258 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1259 $this->makeSelectOptions( $options );
1260
1261 if ( !empty( $conds ) ) {
1262 if ( is_array( $conds ) ) {
1263 $conds = $this->makeList( $conds, LIST_AND );
1264 }
1265 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1266 } else {
1267 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1268 }
1269
1270 if ( isset( $options['LIMIT'] ) ) {
1271 $sql = $this->limitResult( $sql, $options['LIMIT'],
1272 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1273 }
1274 $sql = "$sql $postLimitTail";
1275
1276 if ( isset( $options['EXPLAIN'] ) ) {
1277 $sql = 'EXPLAIN ' . $sql;
1278 }
1279
1280 return $sql;
1281 }
1282
1283 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1284 $options = array(), $join_conds = array()
1285 ) {
1286 $options = (array)$options;
1287 $options['LIMIT'] = 1;
1288 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1289
1290 if ( $res === false ) {
1291 return false;
1292 }
1293
1294 if ( !$this->numRows( $res ) ) {
1295 return false;
1296 }
1297
1298 $obj = $this->fetchObject( $res );
1299
1300 return $obj;
1301 }
1302
1303 public function estimateRowCount(
1304 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = array()
1305 ) {
1306 $rows = 0;
1307 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1308
1309 if ( $res ) {
1310 $row = $this->fetchRow( $res );
1311 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1312 }
1313
1314 return $rows;
1315 }
1316
1317 public function selectRowCount(
1318 $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = array(), $join_conds = array()
1319 ) {
1320 $rows = 0;
1321 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1322 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1323
1324 if ( $res ) {
1325 $row = $this->fetchRow( $res );
1326 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1327 }
1328
1329 return $rows;
1330 }
1331
1332 /**
1333 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1334 * It's only slightly flawed. Don't use for anything important.
1335 *
1336 * @param string $sql A SQL Query
1337 *
1338 * @return string
1339 */
1340 protected static function generalizeSQL( $sql ) {
1341 # This does the same as the regexp below would do, but in such a way
1342 # as to avoid crashing php on some large strings.
1343 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1344
1345 $sql = str_replace( "\\\\", '', $sql );
1346 $sql = str_replace( "\\'", '', $sql );
1347 $sql = str_replace( "\\\"", '', $sql );
1348 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1349 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1350
1351 # All newlines, tabs, etc replaced by single space
1352 $sql = preg_replace( '/\s+/', ' ', $sql );
1353
1354 # All numbers => N,
1355 # except the ones surrounded by characters, e.g. l10n
1356 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1357 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1358
1359 return $sql;
1360 }
1361
1362 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1363 $info = $this->fieldInfo( $table, $field );
1364
1365 return (bool)$info;
1366 }
1367
1368 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1369 if ( !$this->tableExists( $table ) ) {
1370 return null;
1371 }
1372
1373 $info = $this->indexInfo( $table, $index, $fname );
1374 if ( is_null( $info ) ) {
1375 return null;
1376 } else {
1377 return $info !== false;
1378 }
1379 }
1380
1381 public function tableExists( $table, $fname = __METHOD__ ) {
1382 $table = $this->tableName( $table );
1383 $old = $this->ignoreErrors( true );
1384 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1385 $this->ignoreErrors( $old );
1386
1387 return (bool)$res;
1388 }
1389
1390 public function indexUnique( $table, $index ) {
1391 $indexInfo = $this->indexInfo( $table, $index );
1392
1393 if ( !$indexInfo ) {
1394 return null;
1395 }
1396
1397 return !$indexInfo[0]->Non_unique;
1398 }
1399
1400 /**
1401 * Helper for DatabaseBase::insert().
1402 *
1403 * @param array $options
1404 * @return string
1405 */
1406 protected function makeInsertOptions( $options ) {
1407 return implode( ' ', $options );
1408 }
1409
1410 public function insert( $table, $a, $fname = __METHOD__, $options = array() ) {
1411 # No rows to insert, easy just return now
1412 if ( !count( $a ) ) {
1413 return true;
1414 }
1415
1416 $table = $this->tableName( $table );
1417
1418 if ( !is_array( $options ) ) {
1419 $options = array( $options );
1420 }
1421
1422 $fh = null;
1423 if ( isset( $options['fileHandle'] ) ) {
1424 $fh = $options['fileHandle'];
1425 }
1426 $options = $this->makeInsertOptions( $options );
1427
1428 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1429 $multi = true;
1430 $keys = array_keys( $a[0] );
1431 } else {
1432 $multi = false;
1433 $keys = array_keys( $a );
1434 }
1435
1436 $sql = 'INSERT ' . $options .
1437 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1438
1439 if ( $multi ) {
1440 $first = true;
1441 foreach ( $a as $row ) {
1442 if ( $first ) {
1443 $first = false;
1444 } else {
1445 $sql .= ',';
1446 }
1447 $sql .= '(' . $this->makeList( $row ) . ')';
1448 }
1449 } else {
1450 $sql .= '(' . $this->makeList( $a ) . ')';
1451 }
1452
1453 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1454 return false;
1455 } elseif ( $fh !== null ) {
1456 return true;
1457 }
1458
1459 return (bool)$this->query( $sql, $fname );
1460 }
1461
1462 /**
1463 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1464 *
1465 * @param array $options
1466 * @return array
1467 */
1468 protected function makeUpdateOptionsArray( $options ) {
1469 if ( !is_array( $options ) ) {
1470 $options = array( $options );
1471 }
1472
1473 $opts = array();
1474
1475 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1476 $opts[] = $this->lowPriorityOption();
1477 }
1478
1479 if ( in_array( 'IGNORE', $options ) ) {
1480 $opts[] = 'IGNORE';
1481 }
1482
1483 return $opts;
1484 }
1485
1486 /**
1487 * Make UPDATE options for the DatabaseBase::update function
1488 *
1489 * @param array $options The options passed to DatabaseBase::update
1490 * @return string
1491 */
1492 protected function makeUpdateOptions( $options ) {
1493 $opts = $this->makeUpdateOptionsArray( $options );
1494
1495 return implode( ' ', $opts );
1496 }
1497
1498 function update( $table, $values, $conds, $fname = __METHOD__, $options = array() ) {
1499 $table = $this->tableName( $table );
1500 $opts = $this->makeUpdateOptions( $options );
1501 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1502
1503 if ( $conds !== array() && $conds !== '*' ) {
1504 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1505 }
1506
1507 return $this->query( $sql, $fname );
1508 }
1509
1510 public function makeList( $a, $mode = LIST_COMMA ) {
1511 if ( !is_array( $a ) ) {
1512 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1513 }
1514
1515 $first = true;
1516 $list = '';
1517
1518 foreach ( $a as $field => $value ) {
1519 if ( !$first ) {
1520 if ( $mode == LIST_AND ) {
1521 $list .= ' AND ';
1522 } elseif ( $mode == LIST_OR ) {
1523 $list .= ' OR ';
1524 } else {
1525 $list .= ',';
1526 }
1527 } else {
1528 $first = false;
1529 }
1530
1531 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
1532 $list .= "($value)";
1533 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
1534 $list .= "$value";
1535 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
1536 // Remove null from array to be handled separately if found
1537 $includeNull = false;
1538 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1539 $includeNull = true;
1540 unset( $value[$nullKey] );
1541 }
1542 if ( count( $value ) == 0 && !$includeNull ) {
1543 throw new MWException( __METHOD__ . ": empty input for field $field" );
1544 } elseif ( count( $value ) == 0 ) {
1545 // only check if $field is null
1546 $list .= "$field IS NULL";
1547 } else {
1548 // IN clause contains at least one valid element
1549 if ( $includeNull ) {
1550 // Group subconditions to ensure correct precedence
1551 $list .= '(';
1552 }
1553 if ( count( $value ) == 1 ) {
1554 // Special-case single values, as IN isn't terribly efficient
1555 // Don't necessarily assume the single key is 0; we don't
1556 // enforce linear numeric ordering on other arrays here.
1557 $value = array_values( $value );
1558 $list .= $field . " = " . $this->addQuotes( $value[0] );
1559 } else {
1560 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1561 }
1562 // if null present in array, append IS NULL
1563 if ( $includeNull ) {
1564 $list .= " OR $field IS NULL)";
1565 }
1566 }
1567 } elseif ( $value === null ) {
1568 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1569 $list .= "$field IS ";
1570 } elseif ( $mode == LIST_SET ) {
1571 $list .= "$field = ";
1572 }
1573 $list .= 'NULL';
1574 } else {
1575 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1576 $list .= "$field = ";
1577 }
1578 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1579 }
1580 }
1581
1582 return $list;
1583 }
1584
1585 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1586 $conds = array();
1587
1588 foreach ( $data as $base => $sub ) {
1589 if ( count( $sub ) ) {
1590 $conds[] = $this->makeList(
1591 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1592 LIST_AND );
1593 }
1594 }
1595
1596 if ( $conds ) {
1597 return $this->makeList( $conds, LIST_OR );
1598 } else {
1599 // Nothing to search for...
1600 return false;
1601 }
1602 }
1603
1604 /**
1605 * Return aggregated value alias
1606 *
1607 * @param array $valuedata
1608 * @param string $valuename
1609 *
1610 * @return string
1611 */
1612 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1613 return $valuename;
1614 }
1615
1616 public function bitNot( $field ) {
1617 return "(~$field)";
1618 }
1619
1620 public function bitAnd( $fieldLeft, $fieldRight ) {
1621 return "($fieldLeft & $fieldRight)";
1622 }
1623
1624 public function bitOr( $fieldLeft, $fieldRight ) {
1625 return "($fieldLeft | $fieldRight)";
1626 }
1627
1628 public function buildConcat( $stringList ) {
1629 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1630 }
1631
1632 public function buildGroupConcatField(
1633 $delim, $table, $field, $conds = '', $join_conds = array()
1634 ) {
1635 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1636
1637 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
1638 }
1639
1640 public function selectDB( $db ) {
1641 # Stub. Shouldn't cause serious problems if it's not overridden, but
1642 # if your database engine supports a concept similar to MySQL's
1643 # databases you may as well.
1644 $this->mDBname = $db;
1645
1646 return true;
1647 }
1648
1649 public function getDBname() {
1650 return $this->mDBname;
1651 }
1652
1653 public function getServer() {
1654 return $this->mServer;
1655 }
1656
1657 /**
1658 * Format a table name ready for use in constructing an SQL query
1659 *
1660 * This does two important things: it quotes the table names to clean them up,
1661 * and it adds a table prefix if only given a table name with no quotes.
1662 *
1663 * All functions of this object which require a table name call this function
1664 * themselves. Pass the canonical name to such functions. This is only needed
1665 * when calling query() directly.
1666 *
1667 * @param string $name Database table name
1668 * @param string $format One of:
1669 * quoted - Automatically pass the table name through addIdentifierQuotes()
1670 * so that it can be used in a query.
1671 * raw - Do not add identifier quotes to the table name
1672 * @return string Full database name
1673 */
1674 public function tableName( $name, $format = 'quoted' ) {
1675 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
1676 # Skip the entire process when we have a string quoted on both ends.
1677 # Note that we check the end so that we will still quote any use of
1678 # use of `database`.table. But won't break things if someone wants
1679 # to query a database table with a dot in the name.
1680 if ( $this->isQuotedIdentifier( $name ) ) {
1681 return $name;
1682 }
1683
1684 # Lets test for any bits of text that should never show up in a table
1685 # name. Basically anything like JOIN or ON which are actually part of
1686 # SQL queries, but may end up inside of the table value to combine
1687 # sql. Such as how the API is doing.
1688 # Note that we use a whitespace test rather than a \b test to avoid
1689 # any remote case where a word like on may be inside of a table name
1690 # surrounded by symbols which may be considered word breaks.
1691 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1692 return $name;
1693 }
1694
1695 # Split database and table into proper variables.
1696 # We reverse the explode so that database.table and table both output
1697 # the correct table.
1698 $dbDetails = explode( '.', $name, 3 );
1699 if ( count( $dbDetails ) == 3 ) {
1700 list( $database, $schema, $table ) = $dbDetails;
1701 # We don't want any prefix added in this case
1702 $prefix = '';
1703 } elseif ( count( $dbDetails ) == 2 ) {
1704 list( $database, $table ) = $dbDetails;
1705 # We don't want any prefix added in this case
1706 # In dbs that support it, $database may actually be the schema
1707 # but that doesn't affect any of the functionality here
1708 $prefix = '';
1709 $schema = null;
1710 } else {
1711 list( $table ) = $dbDetails;
1712 if ( $wgSharedDB !== null # We have a shared database
1713 && $this->mForeign == false # We're not working on a foreign database
1714 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
1715 && in_array( $table, $wgSharedTables ) # A shared table is selected
1716 ) {
1717 $database = $wgSharedDB;
1718 $schema = $wgSharedSchema === null ? $this->mSchema : $wgSharedSchema;
1719 $prefix = $wgSharedPrefix === null ? $this->mTablePrefix : $wgSharedPrefix;
1720 } else {
1721 $database = null;
1722 $schema = $this->mSchema; # Default schema
1723 $prefix = $this->mTablePrefix; # Default prefix
1724 }
1725 }
1726
1727 # Quote $table and apply the prefix if not quoted.
1728 # $tableName might be empty if this is called from Database::replaceVars()
1729 $tableName = "{$prefix}{$table}";
1730 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
1731 $tableName = $this->addIdentifierQuotes( $tableName );
1732 }
1733
1734 # Quote $schema and merge it with the table name if needed
1735 if ( strlen( $schema ) ) {
1736 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1737 $schema = $this->addIdentifierQuotes( $schema );
1738 }
1739 $tableName = $schema . '.' . $tableName;
1740 }
1741
1742 # Quote $database and merge it with the table name if needed
1743 if ( $database !== null ) {
1744 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1745 $database = $this->addIdentifierQuotes( $database );
1746 }
1747 $tableName = $database . '.' . $tableName;
1748 }
1749
1750 return $tableName;
1751 }
1752
1753 /**
1754 * Fetch a number of table names into an array
1755 * This is handy when you need to construct SQL for joins
1756 *
1757 * Example:
1758 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1759 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1760 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1761 *
1762 * @return array
1763 */
1764 public function tableNames() {
1765 $inArray = func_get_args();
1766 $retVal = array();
1767
1768 foreach ( $inArray as $name ) {
1769 $retVal[$name] = $this->tableName( $name );
1770 }
1771
1772 return $retVal;
1773 }
1774
1775 /**
1776 * Fetch a number of table names into an zero-indexed numerical array
1777 * This is handy when you need to construct SQL for joins
1778 *
1779 * Example:
1780 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1781 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1782 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1783 *
1784 * @return array
1785 */
1786 public function tableNamesN() {
1787 $inArray = func_get_args();
1788 $retVal = array();
1789
1790 foreach ( $inArray as $name ) {
1791 $retVal[] = $this->tableName( $name );
1792 }
1793
1794 return $retVal;
1795 }
1796
1797 /**
1798 * Get an aliased table name
1799 * e.g. tableName AS newTableName
1800 *
1801 * @param string $name Table name, see tableName()
1802 * @param string|bool $alias Alias (optional)
1803 * @return string SQL name for aliased table. Will not alias a table to its own name
1804 */
1805 public function tableNameWithAlias( $name, $alias = false ) {
1806 if ( !$alias || $alias == $name ) {
1807 return $this->tableName( $name );
1808 } else {
1809 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1810 }
1811 }
1812
1813 /**
1814 * Gets an array of aliased table names
1815 *
1816 * @param array $tables Array( [alias] => table )
1817 * @return string[] See tableNameWithAlias()
1818 */
1819 public function tableNamesWithAlias( $tables ) {
1820 $retval = array();
1821 foreach ( $tables as $alias => $table ) {
1822 if ( is_numeric( $alias ) ) {
1823 $alias = $table;
1824 }
1825 $retval[] = $this->tableNameWithAlias( $table, $alias );
1826 }
1827
1828 return $retval;
1829 }
1830
1831 /**
1832 * Get an aliased field name
1833 * e.g. fieldName AS newFieldName
1834 *
1835 * @param string $name Field name
1836 * @param string|bool $alias Alias (optional)
1837 * @return string SQL name for aliased field. Will not alias a field to its own name
1838 */
1839 public function fieldNameWithAlias( $name, $alias = false ) {
1840 if ( !$alias || (string)$alias === (string)$name ) {
1841 return $name;
1842 } else {
1843 return $name . ' AS ' . $alias; // PostgreSQL needs AS
1844 }
1845 }
1846
1847 /**
1848 * Gets an array of aliased field names
1849 *
1850 * @param array $fields Array( [alias] => field )
1851 * @return string[] See fieldNameWithAlias()
1852 */
1853 public function fieldNamesWithAlias( $fields ) {
1854 $retval = array();
1855 foreach ( $fields as $alias => $field ) {
1856 if ( is_numeric( $alias ) ) {
1857 $alias = $field;
1858 }
1859 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1860 }
1861
1862 return $retval;
1863 }
1864
1865 /**
1866 * Get the aliased table name clause for a FROM clause
1867 * which might have a JOIN and/or USE INDEX clause
1868 *
1869 * @param array $tables ( [alias] => table )
1870 * @param array $use_index Same as for select()
1871 * @param array $join_conds Same as for select()
1872 * @return string
1873 */
1874 protected function tableNamesWithUseIndexOrJOIN(
1875 $tables, $use_index = array(), $join_conds = array()
1876 ) {
1877 $ret = array();
1878 $retJOIN = array();
1879 $use_index = (array)$use_index;
1880 $join_conds = (array)$join_conds;
1881
1882 foreach ( $tables as $alias => $table ) {
1883 if ( !is_string( $alias ) ) {
1884 // No alias? Set it equal to the table name
1885 $alias = $table;
1886 }
1887 // Is there a JOIN clause for this table?
1888 if ( isset( $join_conds[$alias] ) ) {
1889 list( $joinType, $conds ) = $join_conds[$alias];
1890 $tableClause = $joinType;
1891 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1892 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1893 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1894 if ( $use != '' ) {
1895 $tableClause .= ' ' . $use;
1896 }
1897 }
1898 $on = $this->makeList( (array)$conds, LIST_AND );
1899 if ( $on != '' ) {
1900 $tableClause .= ' ON (' . $on . ')';
1901 }
1902
1903 $retJOIN[] = $tableClause;
1904 } elseif ( isset( $use_index[$alias] ) ) {
1905 // Is there an INDEX clause for this table?
1906 $tableClause = $this->tableNameWithAlias( $table, $alias );
1907 $tableClause .= ' ' . $this->useIndexClause(
1908 implode( ',', (array)$use_index[$alias] )
1909 );
1910
1911 $ret[] = $tableClause;
1912 } else {
1913 $tableClause = $this->tableNameWithAlias( $table, $alias );
1914
1915 $ret[] = $tableClause;
1916 }
1917 }
1918
1919 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1920 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
1921 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
1922
1923 // Compile our final table clause
1924 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
1925 }
1926
1927 /**
1928 * Get the name of an index in a given table.
1929 *
1930 * @param string $index
1931 * @return string
1932 */
1933 protected function indexName( $index ) {
1934 // Backwards-compatibility hack
1935 $renamed = array(
1936 'ar_usertext_timestamp' => 'usertext_timestamp',
1937 'un_user_id' => 'user_id',
1938 'un_user_ip' => 'user_ip',
1939 );
1940
1941 if ( isset( $renamed[$index] ) ) {
1942 return $renamed[$index];
1943 } else {
1944 return $index;
1945 }
1946 }
1947
1948 public function addQuotes( $s ) {
1949 if ( $s instanceof Blob ) {
1950 $s = $s->fetch();
1951 }
1952 if ( $s === null ) {
1953 return 'NULL';
1954 } else {
1955 # This will also quote numeric values. This should be harmless,
1956 # and protects against weird problems that occur when they really
1957 # _are_ strings such as article titles and string->number->string
1958 # conversion is not 1:1.
1959 return "'" . $this->strencode( $s ) . "'";
1960 }
1961 }
1962
1963 /**
1964 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1965 * MySQL uses `backticks` while basically everything else uses double quotes.
1966 * Since MySQL is the odd one out here the double quotes are our generic
1967 * and we implement backticks in DatabaseMysql.
1968 *
1969 * @param string $s
1970 * @return string
1971 */
1972 public function addIdentifierQuotes( $s ) {
1973 return '"' . str_replace( '"', '""', $s ) . '"';
1974 }
1975
1976 /**
1977 * Returns if the given identifier looks quoted or not according to
1978 * the database convention for quoting identifiers .
1979 *
1980 * @param string $name
1981 * @return bool
1982 */
1983 public function isQuotedIdentifier( $name ) {
1984 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
1985 }
1986
1987 /**
1988 * @param string $s
1989 * @return string
1990 */
1991 protected function escapeLikeInternal( $s ) {
1992 return addcslashes( $s, '\%_' );
1993 }
1994
1995 public function buildLike() {
1996 $params = func_get_args();
1997
1998 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1999 $params = $params[0];
2000 }
2001
2002 $s = '';
2003
2004 foreach ( $params as $value ) {
2005 if ( $value instanceof LikeMatch ) {
2006 $s .= $value->toString();
2007 } else {
2008 $s .= $this->escapeLikeInternal( $value );
2009 }
2010 }
2011
2012 return " LIKE {$this->addQuotes( $s )} ";
2013 }
2014
2015 public function anyChar() {
2016 return new LikeMatch( '_' );
2017 }
2018
2019 public function anyString() {
2020 return new LikeMatch( '%' );
2021 }
2022
2023 public function nextSequenceValue( $seqName ) {
2024 return null;
2025 }
2026
2027 /**
2028 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2029 * is only needed because a) MySQL must be as efficient as possible due to
2030 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2031 * which index to pick. Anyway, other databases might have different
2032 * indexes on a given table. So don't bother overriding this unless you're
2033 * MySQL.
2034 * @param string $index
2035 * @return string
2036 */
2037 public function useIndexClause( $index ) {
2038 return '';
2039 }
2040
2041 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2042 $quotedTable = $this->tableName( $table );
2043
2044 if ( count( $rows ) == 0 ) {
2045 return;
2046 }
2047
2048 # Single row case
2049 if ( !is_array( reset( $rows ) ) ) {
2050 $rows = array( $rows );
2051 }
2052
2053 // @FXIME: this is not atomic, but a trx would break affectedRows()
2054 foreach ( $rows as $row ) {
2055 # Delete rows which collide
2056 if ( $uniqueIndexes ) {
2057 $sql = "DELETE FROM $quotedTable WHERE ";
2058 $first = true;
2059 foreach ( $uniqueIndexes as $index ) {
2060 if ( $first ) {
2061 $first = false;
2062 $sql .= '( ';
2063 } else {
2064 $sql .= ' ) OR ( ';
2065 }
2066 if ( is_array( $index ) ) {
2067 $first2 = true;
2068 foreach ( $index as $col ) {
2069 if ( $first2 ) {
2070 $first2 = false;
2071 } else {
2072 $sql .= ' AND ';
2073 }
2074 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2075 }
2076 } else {
2077 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2078 }
2079 }
2080 $sql .= ' )';
2081 $this->query( $sql, $fname );
2082 }
2083
2084 # Now insert the row
2085 $this->insert( $table, $row, $fname );
2086 }
2087 }
2088
2089 /**
2090 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2091 * statement.
2092 *
2093 * @param string $table Table name
2094 * @param array|string $rows Row(s) to insert
2095 * @param string $fname Caller function name
2096 *
2097 * @return ResultWrapper
2098 */
2099 protected function nativeReplace( $table, $rows, $fname ) {
2100 $table = $this->tableName( $table );
2101
2102 # Single row case
2103 if ( !is_array( reset( $rows ) ) ) {
2104 $rows = array( $rows );
2105 }
2106
2107 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2108 $first = true;
2109
2110 foreach ( $rows as $row ) {
2111 if ( $first ) {
2112 $first = false;
2113 } else {
2114 $sql .= ',';
2115 }
2116
2117 $sql .= '(' . $this->makeList( $row ) . ')';
2118 }
2119
2120 return $this->query( $sql, $fname );
2121 }
2122
2123 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2124 $fname = __METHOD__
2125 ) {
2126 if ( !count( $rows ) ) {
2127 return true; // nothing to do
2128 }
2129
2130 if ( !is_array( reset( $rows ) ) ) {
2131 $rows = array( $rows );
2132 }
2133
2134 if ( count( $uniqueIndexes ) ) {
2135 $clauses = array(); // list WHERE clauses that each identify a single row
2136 foreach ( $rows as $row ) {
2137 foreach ( $uniqueIndexes as $index ) {
2138 $index = is_array( $index ) ? $index : array( $index ); // columns
2139 $rowKey = array(); // unique key to this row
2140 foreach ( $index as $column ) {
2141 $rowKey[$column] = $row[$column];
2142 }
2143 $clauses[] = $this->makeList( $rowKey, LIST_AND );
2144 }
2145 }
2146 $where = array( $this->makeList( $clauses, LIST_OR ) );
2147 } else {
2148 $where = false;
2149 }
2150
2151 $useTrx = !$this->mTrxLevel;
2152 if ( $useTrx ) {
2153 $this->begin( $fname );
2154 }
2155 try {
2156 # Update any existing conflicting row(s)
2157 if ( $where !== false ) {
2158 $ok = $this->update( $table, $set, $where, $fname );
2159 } else {
2160 $ok = true;
2161 }
2162 # Now insert any non-conflicting row(s)
2163 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2164 } catch ( Exception $e ) {
2165 if ( $useTrx ) {
2166 $this->rollback( $fname );
2167 }
2168 throw $e;
2169 }
2170 if ( $useTrx ) {
2171 $this->commit( $fname );
2172 }
2173
2174 return $ok;
2175 }
2176
2177 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2178 $fname = __METHOD__
2179 ) {
2180 if ( !$conds ) {
2181 throw new DBUnexpectedError( $this,
2182 'DatabaseBase::deleteJoin() called with empty $conds' );
2183 }
2184
2185 $delTable = $this->tableName( $delTable );
2186 $joinTable = $this->tableName( $joinTable );
2187 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2188 if ( $conds != '*' ) {
2189 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
2190 }
2191 $sql .= ')';
2192
2193 $this->query( $sql, $fname );
2194 }
2195
2196 /**
2197 * Returns the size of a text field, or -1 for "unlimited"
2198 *
2199 * @param string $table
2200 * @param string $field
2201 * @return int
2202 */
2203 public function textFieldSize( $table, $field ) {
2204 $table = $this->tableName( $table );
2205 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2206 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2207 $row = $this->fetchObject( $res );
2208
2209 $m = array();
2210
2211 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2212 $size = $m[1];
2213 } else {
2214 $size = -1;
2215 }
2216
2217 return $size;
2218 }
2219
2220 /**
2221 * A string to insert into queries to show that they're low-priority, like
2222 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2223 * string and nothing bad should happen.
2224 *
2225 * @return string Returns the text of the low priority option if it is
2226 * supported, or a blank string otherwise
2227 */
2228 public function lowPriorityOption() {
2229 return '';
2230 }
2231
2232 public function delete( $table, $conds, $fname = __METHOD__ ) {
2233 if ( !$conds ) {
2234 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2235 }
2236
2237 $table = $this->tableName( $table );
2238 $sql = "DELETE FROM $table";
2239
2240 if ( $conds != '*' ) {
2241 if ( is_array( $conds ) ) {
2242 $conds = $this->makeList( $conds, LIST_AND );
2243 }
2244 $sql .= ' WHERE ' . $conds;
2245 }
2246
2247 return $this->query( $sql, $fname );
2248 }
2249
2250 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2251 $fname = __METHOD__,
2252 $insertOptions = array(), $selectOptions = array()
2253 ) {
2254 $destTable = $this->tableName( $destTable );
2255
2256 if ( !is_array( $insertOptions ) ) {
2257 $insertOptions = array( $insertOptions );
2258 }
2259
2260 $insertOptions = $this->makeInsertOptions( $insertOptions );
2261
2262 if ( !is_array( $selectOptions ) ) {
2263 $selectOptions = array( $selectOptions );
2264 }
2265
2266 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2267
2268 if ( is_array( $srcTable ) ) {
2269 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2270 } else {
2271 $srcTable = $this->tableName( $srcTable );
2272 }
2273
2274 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2275 " SELECT $startOpts " . implode( ',', $varMap ) .
2276 " FROM $srcTable $useIndex ";
2277
2278 if ( $conds != '*' ) {
2279 if ( is_array( $conds ) ) {
2280 $conds = $this->makeList( $conds, LIST_AND );
2281 }
2282 $sql .= " WHERE $conds";
2283 }
2284
2285 $sql .= " $tailOpts";
2286
2287 return $this->query( $sql, $fname );
2288 }
2289
2290 /**
2291 * Construct a LIMIT query with optional offset. This is used for query
2292 * pages. The SQL should be adjusted so that only the first $limit rows
2293 * are returned. If $offset is provided as well, then the first $offset
2294 * rows should be discarded, and the next $limit rows should be returned.
2295 * If the result of the query is not ordered, then the rows to be returned
2296 * are theoretically arbitrary.
2297 *
2298 * $sql is expected to be a SELECT, if that makes a difference.
2299 *
2300 * The version provided by default works in MySQL and SQLite. It will very
2301 * likely need to be overridden for most other DBMSes.
2302 *
2303 * @param string $sql SQL query we will append the limit too
2304 * @param int $limit The SQL limit
2305 * @param int|bool $offset The SQL offset (default false)
2306 * @throws DBUnexpectedError
2307 * @return string
2308 */
2309 public function limitResult( $sql, $limit, $offset = false ) {
2310 if ( !is_numeric( $limit ) ) {
2311 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2312 }
2313
2314 return "$sql LIMIT "
2315 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2316 . "{$limit} ";
2317 }
2318
2319 public function unionSupportsOrderAndLimit() {
2320 return true; // True for almost every DB supported
2321 }
2322
2323 public function unionQueries( $sqls, $all ) {
2324 $glue = $all ? ') UNION ALL (' : ') UNION (';
2325
2326 return '(' . implode( $glue, $sqls ) . ')';
2327 }
2328
2329 public function conditional( $cond, $trueVal, $falseVal ) {
2330 if ( is_array( $cond ) ) {
2331 $cond = $this->makeList( $cond, LIST_AND );
2332 }
2333
2334 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2335 }
2336
2337 public function strreplace( $orig, $old, $new ) {
2338 return "REPLACE({$orig}, {$old}, {$new})";
2339 }
2340
2341 public function getServerUptime() {
2342 return 0;
2343 }
2344
2345 public function wasDeadlock() {
2346 return false;
2347 }
2348
2349 public function wasLockTimeout() {
2350 return false;
2351 }
2352
2353 public function wasErrorReissuable() {
2354 return false;
2355 }
2356
2357 public function wasReadOnlyError() {
2358 return false;
2359 }
2360
2361 /**
2362 * Determines if the given query error was a connection drop
2363 * STUB
2364 *
2365 * @param integer|string $errno
2366 * @return bool
2367 */
2368 public function wasConnectionError( $errno ) {
2369 return false;
2370 }
2371
2372 /**
2373 * Perform a deadlock-prone transaction.
2374 *
2375 * This function invokes a callback function to perform a set of write
2376 * queries. If a deadlock occurs during the processing, the transaction
2377 * will be rolled back and the callback function will be called again.
2378 *
2379 * Usage:
2380 * $dbw->deadlockLoop( callback, ... );
2381 *
2382 * Extra arguments are passed through to the specified callback function.
2383 *
2384 * Returns whatever the callback function returned on its successful,
2385 * iteration, or false on error, for example if the retry limit was
2386 * reached.
2387 * @return mixed
2388 * @throws DBUnexpectedError
2389 * @throws Exception
2390 */
2391 public function deadlockLoop() {
2392 $args = func_get_args();
2393 $function = array_shift( $args );
2394 $tries = self::DEADLOCK_TRIES;
2395
2396 $this->begin( __METHOD__ );
2397
2398 $retVal = null;
2399 /** @var Exception $e */
2400 $e = null;
2401 do {
2402 try {
2403 $retVal = call_user_func_array( $function, $args );
2404 break;
2405 } catch ( DBQueryError $e ) {
2406 if ( $this->wasDeadlock() ) {
2407 // Retry after a randomized delay
2408 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
2409 } else {
2410 // Throw the error back up
2411 throw $e;
2412 }
2413 }
2414 } while ( --$tries > 0 );
2415
2416 if ( $tries <= 0 ) {
2417 // Too many deadlocks; give up
2418 $this->rollback( __METHOD__ );
2419 throw $e;
2420 } else {
2421 $this->commit( __METHOD__ );
2422
2423 return $retVal;
2424 }
2425 }
2426
2427 public function masterPosWait( DBMasterPos $pos, $timeout ) {
2428 # Real waits are implemented in the subclass.
2429 return 0;
2430 }
2431
2432 public function getSlavePos() {
2433 # Stub
2434 return false;
2435 }
2436
2437 public function getMasterPos() {
2438 # Stub
2439 return false;
2440 }
2441
2442 final public function onTransactionIdle( $callback ) {
2443 $this->mTrxIdleCallbacks[] = array( $callback, wfGetCaller() );
2444 if ( !$this->mTrxLevel ) {
2445 $this->runOnTransactionIdleCallbacks();
2446 }
2447 }
2448
2449 final public function onTransactionPreCommitOrIdle( $callback ) {
2450 if ( $this->mTrxLevel ) {
2451 $this->mTrxPreCommitCallbacks[] = array( $callback, wfGetCaller() );
2452 } else {
2453 $this->onTransactionIdle( $callback ); // this will trigger immediately
2454 }
2455 }
2456
2457 /**
2458 * Actually any "on transaction idle" callbacks.
2459 *
2460 * @since 1.20
2461 */
2462 protected function runOnTransactionIdleCallbacks() {
2463 $autoTrx = $this->getFlag( DBO_TRX ); // automatic begin() enabled?
2464
2465 $e = $ePrior = null; // last exception
2466 do { // callbacks may add callbacks :)
2467 $callbacks = $this->mTrxIdleCallbacks;
2468 $this->mTrxIdleCallbacks = array(); // recursion guard
2469 foreach ( $callbacks as $callback ) {
2470 try {
2471 list( $phpCallback ) = $callback;
2472 $this->clearFlag( DBO_TRX ); // make each query its own transaction
2473 call_user_func( $phpCallback );
2474 if ( $autoTrx ) {
2475 $this->setFlag( DBO_TRX ); // restore automatic begin()
2476 } else {
2477 $this->clearFlag( DBO_TRX ); // restore auto-commit
2478 }
2479 } catch ( Exception $e ) {
2480 if ( $ePrior ) {
2481 MWExceptionHandler::logException( $ePrior );
2482 }
2483 $ePrior = $e;
2484 // Some callbacks may use startAtomic/endAtomic, so make sure
2485 // their transactions are ended so other callbacks don't fail
2486 if ( $this->trxLevel() ) {
2487 $this->rollback( __METHOD__ );
2488 }
2489 }
2490 }
2491 } while ( count( $this->mTrxIdleCallbacks ) );
2492
2493 if ( $e instanceof Exception ) {
2494 throw $e; // re-throw any last exception
2495 }
2496 }
2497
2498 /**
2499 * Actually any "on transaction pre-commit" callbacks.
2500 *
2501 * @since 1.22
2502 */
2503 protected function runOnTransactionPreCommitCallbacks() {
2504 $e = $ePrior = null; // last exception
2505 do { // callbacks may add callbacks :)
2506 $callbacks = $this->mTrxPreCommitCallbacks;
2507 $this->mTrxPreCommitCallbacks = array(); // recursion guard
2508 foreach ( $callbacks as $callback ) {
2509 try {
2510 list( $phpCallback ) = $callback;
2511 call_user_func( $phpCallback );
2512 } catch ( Exception $e ) {
2513 if ( $ePrior ) {
2514 MWExceptionHandler::logException( $ePrior );
2515 }
2516 $ePrior = $e;
2517 }
2518 }
2519 } while ( count( $this->mTrxPreCommitCallbacks ) );
2520
2521 if ( $e instanceof Exception ) {
2522 throw $e; // re-throw any last exception
2523 }
2524 }
2525
2526 final public function startAtomic( $fname = __METHOD__ ) {
2527 if ( !$this->mTrxLevel ) {
2528 $this->begin( $fname );
2529 $this->mTrxAutomatic = true;
2530 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2531 // in all changes being in one transaction to keep requests transactional.
2532 if ( !$this->getFlag( DBO_TRX ) ) {
2533 $this->mTrxAutomaticAtomic = true;
2534 }
2535 }
2536
2537 $this->mTrxAtomicLevels[] = $fname;
2538 }
2539
2540 final public function endAtomic( $fname = __METHOD__ ) {
2541 if ( !$this->mTrxLevel ) {
2542 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
2543 }
2544 if ( !$this->mTrxAtomicLevels ||
2545 array_pop( $this->mTrxAtomicLevels ) !== $fname
2546 ) {
2547 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
2548 }
2549
2550 if ( !$this->mTrxAtomicLevels && $this->mTrxAutomaticAtomic ) {
2551 $this->commit( $fname, 'flush' );
2552 }
2553 }
2554
2555 final public function doAtomicSection( $fname, $callback ) {
2556 if ( !is_callable( $callback ) ) {
2557 throw new UnexpectedValueException( "Invalid callback." );
2558 };
2559
2560 $this->startAtomic( $fname );
2561 try {
2562 call_user_func_array( $callback, array( $this, $fname ) );
2563 } catch ( Exception $e ) {
2564 $this->rollback( $fname );
2565 throw $e;
2566 }
2567 $this->endAtomic( $fname );
2568 }
2569
2570 final public function begin( $fname = __METHOD__ ) {
2571 if ( $this->mTrxLevel ) { // implicit commit
2572 if ( $this->mTrxAtomicLevels ) {
2573 // If the current transaction was an automatic atomic one, then we definitely have
2574 // a problem. Same if there is any unclosed atomic level.
2575 $levels = implode( ', ', $this->mTrxAtomicLevels );
2576 throw new DBUnexpectedError(
2577 $this,
2578 "Got explicit BEGIN from $fname while atomic section(s) $levels are open."
2579 );
2580 } elseif ( !$this->mTrxAutomatic ) {
2581 // We want to warn about inadvertently nested begin/commit pairs, but not about
2582 // auto-committing implicit transactions that were started by query() via DBO_TRX
2583 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
2584 " performing implicit commit!";
2585 wfWarn( $msg );
2586 wfLogDBError( $msg,
2587 $this->getLogContext( array(
2588 'method' => __METHOD__,
2589 'fname' => $fname,
2590 ) )
2591 );
2592 } else {
2593 // if the transaction was automatic and has done write operations
2594 if ( $this->mTrxDoneWrites ) {
2595 wfDebug( "$fname: Automatic transaction with writes in progress" .
2596 " (from {$this->mTrxFname}), performing implicit commit!\n"
2597 );
2598 }
2599 }
2600
2601 $this->runOnTransactionPreCommitCallbacks();
2602 $writeTime = $this->pendingWriteQueryDuration();
2603 $this->doCommit( $fname );
2604 if ( $this->mTrxDoneWrites ) {
2605 $this->mDoneWrites = microtime( true );
2606 $this->getTransactionProfiler()->transactionWritingOut(
2607 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
2608 }
2609 $this->runOnTransactionIdleCallbacks();
2610 }
2611
2612 # Avoid fatals if close() was called
2613 $this->assertOpen();
2614
2615 $this->doBegin( $fname );
2616 $this->mTrxTimestamp = microtime( true );
2617 $this->mTrxFname = $fname;
2618 $this->mTrxDoneWrites = false;
2619 $this->mTrxAutomatic = false;
2620 $this->mTrxAutomaticAtomic = false;
2621 $this->mTrxAtomicLevels = array();
2622 $this->mTrxIdleCallbacks = array();
2623 $this->mTrxPreCommitCallbacks = array();
2624 $this->mTrxShortId = wfRandomString( 12 );
2625 $this->mTrxWriteDuration = 0.0;
2626 $this->mTrxWriteCallers = array();
2627 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2628 // Get an estimate of the slave lag before then, treating estimate staleness
2629 // as lag itself just to be safe
2630 $status = $this->getApproximateLagStatus();
2631 $this->mTrxSlaveLag = $status['lag'] + ( microtime( true ) - $status['since'] );
2632 }
2633
2634 /**
2635 * Issues the BEGIN command to the database server.
2636 *
2637 * @see DatabaseBase::begin()
2638 * @param string $fname
2639 */
2640 protected function doBegin( $fname ) {
2641 $this->query( 'BEGIN', $fname );
2642 $this->mTrxLevel = 1;
2643 }
2644
2645 final public function commit( $fname = __METHOD__, $flush = '' ) {
2646 if ( $this->mTrxLevel && $this->mTrxAtomicLevels ) {
2647 // There are still atomic sections open. This cannot be ignored
2648 $levels = implode( ', ', $this->mTrxAtomicLevels );
2649 throw new DBUnexpectedError(
2650 $this,
2651 "Got COMMIT while atomic sections $levels are still open"
2652 );
2653 }
2654
2655 if ( $flush === 'flush' ) {
2656 if ( !$this->mTrxLevel ) {
2657 return; // nothing to do
2658 } elseif ( !$this->mTrxAutomatic ) {
2659 throw new DBUnexpectedError(
2660 $this,
2661 "$fname: Flushing an explicit transaction, getting out of sync!"
2662 );
2663 }
2664 } else {
2665 if ( !$this->mTrxLevel ) {
2666 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
2667 return; // nothing to do
2668 } elseif ( $this->mTrxAutomatic ) {
2669 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
2670 }
2671 }
2672
2673 # Avoid fatals if close() was called
2674 $this->assertOpen();
2675
2676 $this->runOnTransactionPreCommitCallbacks();
2677 $writeTime = $this->pendingWriteQueryDuration();
2678 $this->doCommit( $fname );
2679 if ( $this->mTrxDoneWrites ) {
2680 $this->mDoneWrites = microtime( true );
2681 $this->getTransactionProfiler()->transactionWritingOut(
2682 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
2683 }
2684 $this->runOnTransactionIdleCallbacks();
2685 }
2686
2687 /**
2688 * Issues the COMMIT command to the database server.
2689 *
2690 * @see DatabaseBase::commit()
2691 * @param string $fname
2692 */
2693 protected function doCommit( $fname ) {
2694 if ( $this->mTrxLevel ) {
2695 $this->query( 'COMMIT', $fname );
2696 $this->mTrxLevel = 0;
2697 }
2698 }
2699
2700 final public function rollback( $fname = __METHOD__, $flush = '' ) {
2701 if ( $flush !== 'flush' ) {
2702 if ( !$this->mTrxLevel ) {
2703 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
2704 return; // nothing to do
2705 }
2706 } else {
2707 if ( !$this->mTrxLevel ) {
2708 return; // nothing to do
2709 }
2710 }
2711
2712 # Avoid fatals if close() was called
2713 $this->assertOpen();
2714
2715 $this->doRollback( $fname );
2716 $this->mTrxIdleCallbacks = array(); // cancel
2717 $this->mTrxPreCommitCallbacks = array(); // cancel
2718 $this->mTrxAtomicLevels = array();
2719 if ( $this->mTrxDoneWrites ) {
2720 $this->getTransactionProfiler()->transactionWritingOut(
2721 $this->mServer, $this->mDBname, $this->mTrxShortId );
2722 }
2723 }
2724
2725 /**
2726 * Issues the ROLLBACK command to the database server.
2727 *
2728 * @see DatabaseBase::rollback()
2729 * @param string $fname
2730 */
2731 protected function doRollback( $fname ) {
2732 if ( $this->mTrxLevel ) {
2733 $this->query( 'ROLLBACK', $fname, true );
2734 $this->mTrxLevel = 0;
2735 }
2736 }
2737
2738 /**
2739 * Creates a new table with structure copied from existing table
2740 * Note that unlike most database abstraction functions, this function does not
2741 * automatically append database prefix, because it works at a lower
2742 * abstraction level.
2743 * The table names passed to this function shall not be quoted (this
2744 * function calls addIdentifierQuotes when needed).
2745 *
2746 * @param string $oldName Name of table whose structure should be copied
2747 * @param string $newName Name of table to be created
2748 * @param bool $temporary Whether the new table should be temporary
2749 * @param string $fname Calling function name
2750 * @throws MWException
2751 * @return bool True if operation was successful
2752 */
2753 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
2754 $fname = __METHOD__
2755 ) {
2756 throw new MWException(
2757 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2758 }
2759
2760 function listTables( $prefix = null, $fname = __METHOD__ ) {
2761 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2762 }
2763
2764 /**
2765 * Reset the views process cache set by listViews()
2766 * @since 1.22
2767 */
2768 final public function clearViewsCache() {
2769 $this->allViews = null;
2770 }
2771
2772 /**
2773 * Lists all the VIEWs in the database
2774 *
2775 * For caching purposes the list of all views should be stored in
2776 * $this->allViews. The process cache can be cleared with clearViewsCache()
2777 *
2778 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
2779 * @param string $fname Name of calling function
2780 * @throws MWException
2781 * @return array
2782 * @since 1.22
2783 */
2784 public function listViews( $prefix = null, $fname = __METHOD__ ) {
2785 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
2786 }
2787
2788 /**
2789 * Differentiates between a TABLE and a VIEW
2790 *
2791 * @param string $name Name of the database-structure to test.
2792 * @throws MWException
2793 * @return bool
2794 * @since 1.22
2795 */
2796 public function isView( $name ) {
2797 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
2798 }
2799
2800 public function timestamp( $ts = 0 ) {
2801 return wfTimestamp( TS_MW, $ts );
2802 }
2803
2804 public function timestampOrNull( $ts = null ) {
2805 if ( is_null( $ts ) ) {
2806 return null;
2807 } else {
2808 return $this->timestamp( $ts );
2809 }
2810 }
2811
2812 /**
2813 * Take the result from a query, and wrap it in a ResultWrapper if
2814 * necessary. Boolean values are passed through as is, to indicate success
2815 * of write queries or failure.
2816 *
2817 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2818 * resource, and it was necessary to call this function to convert it to
2819 * a wrapper. Nowadays, raw database objects are never exposed to external
2820 * callers, so this is unnecessary in external code.
2821 *
2822 * @param bool|ResultWrapper|resource|object $result
2823 * @return bool|ResultWrapper
2824 */
2825 protected function resultObject( $result ) {
2826 if ( !$result ) {
2827 return false;
2828 } elseif ( $result instanceof ResultWrapper ) {
2829 return $result;
2830 } elseif ( $result === true ) {
2831 // Successful write query
2832 return $result;
2833 } else {
2834 return new ResultWrapper( $this, $result );
2835 }
2836 }
2837
2838 public function ping() {
2839 # Stub. Not essential to override.
2840 return true;
2841 }
2842
2843 public function getSessionLagStatus() {
2844 return $this->getTransactionLagStatus() ?: $this->getApproximateLagStatus();
2845 }
2846
2847 /**
2848 * Get the slave lag when the current transaction started
2849 *
2850 * This is useful when transactions might use snapshot isolation
2851 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
2852 * is this lag plus transaction duration. If they don't, it is still
2853 * safe to be pessimistic. This returns null if there is no transaction.
2854 *
2855 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
2856 * @since 1.27
2857 */
2858 public function getTransactionLagStatus() {
2859 return $this->mTrxLevel
2860 ? array( 'lag' => $this->mTrxSlaveLag, 'since' => $this->trxTimestamp() )
2861 : null;
2862 }
2863
2864 /**
2865 * Get a slave lag estimate for this server
2866 *
2867 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
2868 * @since 1.27
2869 */
2870 public function getApproximateLagStatus() {
2871 return array(
2872 'lag' => $this->getLBInfo( 'slave' ) ? $this->getLag() : 0,
2873 'since' => microtime( true )
2874 );
2875 }
2876
2877 /**
2878 * Merge the result of getSessionLagStatus() for several DBs
2879 * using the most pessimistic values to estimate the lag of
2880 * any data derived from them in combination
2881 *
2882 * This is information is useful for caching modules
2883 *
2884 * @see WANObjectCache::set()
2885 * @see WANObjectCache::getWithSetCallback()
2886 *
2887 * @param IDatabase $db1
2888 * @param IDatabase ...
2889 * @return array Map of values:
2890 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
2891 * - since: oldest UNIX timestamp of any of the DB lag estimates
2892 * - pending: whether any of the DBs have uncommitted changes
2893 * @since 1.27
2894 */
2895 public static function getCacheSetOptions( IDatabase $db1 ) {
2896 $res = array( 'lag' => 0, 'since' => INF, 'pending' => false );
2897 foreach ( func_get_args() as $db ) {
2898 /** @var IDatabase $db */
2899 $status = $db->getSessionLagStatus();
2900 if ( $status['lag'] === false ) {
2901 $res['lag'] = false;
2902 } elseif ( $res['lag'] !== false ) {
2903 $res['lag'] = max( $res['lag'], $status['lag'] );
2904 }
2905 $res['since'] = min( $res['since'], $status['since'] );
2906 $res['pending'] = $res['pending'] ?: $db->writesPending();
2907 }
2908
2909 return $res;
2910 }
2911
2912 public function getLag() {
2913 return 0;
2914 }
2915
2916 function maxListLen() {
2917 return 0;
2918 }
2919
2920 public function encodeBlob( $b ) {
2921 return $b;
2922 }
2923
2924 public function decodeBlob( $b ) {
2925 if ( $b instanceof Blob ) {
2926 $b = $b->fetch();
2927 }
2928 return $b;
2929 }
2930
2931 public function setSessionOptions( array $options ) {
2932 }
2933
2934 /**
2935 * Read and execute SQL commands from a file.
2936 *
2937 * Returns true on success, error string or exception on failure (depending
2938 * on object's error ignore settings).
2939 *
2940 * @param string $filename File name to open
2941 * @param bool|callable $lineCallback Optional function called before reading each line
2942 * @param bool|callable $resultCallback Optional function called for each MySQL result
2943 * @param bool|string $fname Calling function name or false if name should be
2944 * generated dynamically using $filename
2945 * @param bool|callable $inputCallback Optional function called for each
2946 * complete line sent
2947 * @throws Exception|MWException
2948 * @return bool|string
2949 */
2950 public function sourceFile(
2951 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
2952 ) {
2953 MediaWiki\suppressWarnings();
2954 $fp = fopen( $filename, 'r' );
2955 MediaWiki\restoreWarnings();
2956
2957 if ( false === $fp ) {
2958 throw new MWException( "Could not open \"{$filename}\".\n" );
2959 }
2960
2961 if ( !$fname ) {
2962 $fname = __METHOD__ . "( $filename )";
2963 }
2964
2965 try {
2966 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
2967 } catch ( Exception $e ) {
2968 fclose( $fp );
2969 throw $e;
2970 }
2971
2972 fclose( $fp );
2973
2974 return $error;
2975 }
2976
2977 /**
2978 * Get the full path of a patch file. Originally based on archive()
2979 * from updaters.inc. Keep in mind this always returns a patch, as
2980 * it fails back to MySQL if no DB-specific patch can be found
2981 *
2982 * @param string $patch The name of the patch, like patch-something.sql
2983 * @return string Full path to patch file
2984 */
2985 public function patchPath( $patch ) {
2986 global $IP;
2987
2988 $dbType = $this->getType();
2989 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
2990 return "$IP/maintenance/$dbType/archives/$patch";
2991 } else {
2992 return "$IP/maintenance/archives/$patch";
2993 }
2994 }
2995
2996 public function setSchemaVars( $vars ) {
2997 $this->mSchemaVars = $vars;
2998 }
2999
3000 /**
3001 * Read and execute commands from an open file handle.
3002 *
3003 * Returns true on success, error string or exception on failure (depending
3004 * on object's error ignore settings).
3005 *
3006 * @param resource $fp File handle
3007 * @param bool|callable $lineCallback Optional function called before reading each query
3008 * @param bool|callable $resultCallback Optional function called for each MySQL result
3009 * @param string $fname Calling function name
3010 * @param bool|callable $inputCallback Optional function called for each complete query sent
3011 * @return bool|string
3012 */
3013 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3014 $fname = __METHOD__, $inputCallback = false
3015 ) {
3016 $cmd = '';
3017
3018 while ( !feof( $fp ) ) {
3019 if ( $lineCallback ) {
3020 call_user_func( $lineCallback );
3021 }
3022
3023 $line = trim( fgets( $fp ) );
3024
3025 if ( $line == '' ) {
3026 continue;
3027 }
3028
3029 if ( '-' == $line[0] && '-' == $line[1] ) {
3030 continue;
3031 }
3032
3033 if ( $cmd != '' ) {
3034 $cmd .= ' ';
3035 }
3036
3037 $done = $this->streamStatementEnd( $cmd, $line );
3038
3039 $cmd .= "$line\n";
3040
3041 if ( $done || feof( $fp ) ) {
3042 $cmd = $this->replaceVars( $cmd );
3043
3044 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) || !$inputCallback ) {
3045 $res = $this->query( $cmd, $fname );
3046
3047 if ( $resultCallback ) {
3048 call_user_func( $resultCallback, $res, $this );
3049 }
3050
3051 if ( false === $res ) {
3052 $err = $this->lastError();
3053
3054 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3055 }
3056 }
3057 $cmd = '';
3058 }
3059 }
3060
3061 return true;
3062 }
3063
3064 /**
3065 * Called by sourceStream() to check if we've reached a statement end
3066 *
3067 * @param string $sql SQL assembled so far
3068 * @param string $newLine New line about to be added to $sql
3069 * @return bool Whether $newLine contains end of the statement
3070 */
3071 public function streamStatementEnd( &$sql, &$newLine ) {
3072 if ( $this->delimiter ) {
3073 $prev = $newLine;
3074 $newLine = preg_replace( '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
3075 if ( $newLine != $prev ) {
3076 return true;
3077 }
3078 }
3079
3080 return false;
3081 }
3082
3083 /**
3084 * Database independent variable replacement. Replaces a set of variables
3085 * in an SQL statement with their contents as given by $this->getSchemaVars().
3086 *
3087 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3088 *
3089 * - '{$var}' should be used for text and is passed through the database's
3090 * addQuotes method.
3091 * - `{$var}` should be used for identifiers (e.g. table and database names).
3092 * It is passed through the database's addIdentifierQuotes method which
3093 * can be overridden if the database uses something other than backticks.
3094 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3095 * database's tableName method.
3096 * - / *i* / passes the name that follows through the database's indexName method.
3097 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3098 * its use should be avoided. In 1.24 and older, string encoding was applied.
3099 *
3100 * @param string $ins SQL statement to replace variables in
3101 * @return string The new SQL statement with variables replaced
3102 */
3103 protected function replaceVars( $ins ) {
3104 $vars = $this->getSchemaVars();
3105 return preg_replace_callback(
3106 '!
3107 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3108 \'\{\$ (\w+) }\' | # 3. addQuotes
3109 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3110 /\*\$ (\w+) \*/ # 5. leave unencoded
3111 !x',
3112 function ( $m ) use ( $vars ) {
3113 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3114 // check for both nonexistent keys *and* the empty string.
3115 if ( isset( $m[1] ) && $m[1] !== '' ) {
3116 if ( $m[1] === 'i' ) {
3117 return $this->indexName( $m[2] );
3118 } else {
3119 return $this->tableName( $m[2] );
3120 }
3121 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3122 return $this->addQuotes( $vars[$m[3]] );
3123 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3124 return $this->addIdentifierQuotes( $vars[$m[4]] );
3125 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3126 return $vars[$m[5]];
3127 } else {
3128 return $m[0];
3129 }
3130 },
3131 $ins
3132 );
3133 }
3134
3135 /**
3136 * Get schema variables. If none have been set via setSchemaVars(), then
3137 * use some defaults from the current object.
3138 *
3139 * @return array
3140 */
3141 protected function getSchemaVars() {
3142 if ( $this->mSchemaVars ) {
3143 return $this->mSchemaVars;
3144 } else {
3145 return $this->getDefaultSchemaVars();
3146 }
3147 }
3148
3149 /**
3150 * Get schema variables to use if none have been set via setSchemaVars().
3151 *
3152 * Override this in derived classes to provide variables for tables.sql
3153 * and SQL patch files.
3154 *
3155 * @return array
3156 */
3157 protected function getDefaultSchemaVars() {
3158 return array();
3159 }
3160
3161 public function lockIsFree( $lockName, $method ) {
3162 return true;
3163 }
3164
3165 public function lock( $lockName, $method, $timeout = 5 ) {
3166 $this->mNamedLocksHeld[$lockName] = 1;
3167
3168 return true;
3169 }
3170
3171 public function unlock( $lockName, $method ) {
3172 unset( $this->mNamedLocksHeld[$lockName] );
3173
3174 return true;
3175 }
3176
3177 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3178 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3179 return null;
3180 }
3181
3182 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3183 $this->commit( __METHOD__, 'flush' );
3184 $this->unlock( $lockKey, $fname );
3185 } );
3186
3187 $this->commit( __METHOD__, 'flush' );
3188
3189 return $unlocker;
3190 }
3191
3192 public function namedLocksEnqueue() {
3193 return false;
3194 }
3195
3196 /**
3197 * Lock specific tables
3198 *
3199 * @param array $read Array of tables to lock for read access
3200 * @param array $write Array of tables to lock for write access
3201 * @param string $method Name of caller
3202 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3203 * @return bool
3204 */
3205 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3206 return true;
3207 }
3208
3209 /**
3210 * Unlock specific tables
3211 *
3212 * @param string $method The caller
3213 * @return bool
3214 */
3215 public function unlockTables( $method ) {
3216 return true;
3217 }
3218
3219 /**
3220 * Delete a table
3221 * @param string $tableName
3222 * @param string $fName
3223 * @return bool|ResultWrapper
3224 * @since 1.18
3225 */
3226 public function dropTable( $tableName, $fName = __METHOD__ ) {
3227 if ( !$this->tableExists( $tableName, $fName ) ) {
3228 return false;
3229 }
3230 $sql = "DROP TABLE " . $this->tableName( $tableName );
3231 if ( $this->cascadingDeletes() ) {
3232 $sql .= " CASCADE";
3233 }
3234
3235 return $this->query( $sql, $fName );
3236 }
3237
3238 /**
3239 * Get search engine class. All subclasses of this need to implement this
3240 * if they wish to use searching.
3241 *
3242 * @return string
3243 */
3244 public function getSearchEngine() {
3245 return 'SearchEngineDummy';
3246 }
3247
3248 public function getInfinity() {
3249 return 'infinity';
3250 }
3251
3252 public function encodeExpiry( $expiry ) {
3253 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
3254 ? $this->getInfinity()
3255 : $this->timestamp( $expiry );
3256 }
3257
3258 public function decodeExpiry( $expiry, $format = TS_MW ) {
3259 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
3260 ? 'infinity'
3261 : wfTimestamp( $format, $expiry );
3262 }
3263
3264 public function setBigSelects( $value = true ) {
3265 // no-op
3266 }
3267
3268 public function isReadOnly() {
3269 return ( $this->getReadOnlyReason() !== false );
3270 }
3271
3272 /**
3273 * @return string|bool Reason this DB is read-only or false if it is not
3274 */
3275 protected function getReadOnlyReason() {
3276 $reason = $this->getLBInfo( 'readOnlyReason' );
3277
3278 return is_string( $reason ) ? $reason : false;
3279 }
3280
3281 /**
3282 * @since 1.19
3283 * @return string
3284 */
3285 public function __toString() {
3286 return (string)$this->mConn;
3287 }
3288
3289 /**
3290 * Run a few simple sanity checks
3291 */
3292 public function __destruct() {
3293 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
3294 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3295 }
3296 if ( count( $this->mTrxIdleCallbacks ) || count( $this->mTrxPreCommitCallbacks ) ) {
3297 $callers = array();
3298 foreach ( $this->mTrxIdleCallbacks as $callbackInfo ) {
3299 $callers[] = $callbackInfo[1];
3300 }
3301 $callers = implode( ', ', $callers );
3302 trigger_error( "DB transaction callbacks still pending (from $callers)." );
3303 }
3304 }
3305 }
3306
3307 /**
3308 * @since 1.27
3309 */
3310 abstract class Database extends DatabaseBase {
3311 // B/C until nothing type hints for DatabaseBase
3312 // @TODO: finish renaming DatabaseBase => Database
3313 }