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