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