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