Merge "Make getLagFromPtHeartbeat() always use the LB cluster master entry"
[lhc/web/wiklou.git] / includes / db / Database.php
1 <?php
2
3 /**
4 * @defgroup Database Database
5 *
6 * This file deals with database interface functions
7 * and query specifics/optimisations.
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 * @ingroup Database
26 */
27
28 /**
29 * Database abstraction object
30 * @ingroup Database
31 */
32 abstract class DatabaseBase implements IDatabase {
33 /** Number of times to re-try an operation in case of deadlock */
34 const DEADLOCK_TRIES = 4;
35
36 /** Minimum time to wait before retry, in microseconds */
37 const DEADLOCK_DELAY_MIN = 500000;
38
39 /** Maximum time to wait before retry */
40 const DEADLOCK_DELAY_MAX = 1500000;
41
42 protected $mLastQuery = '';
43 protected $mDoneWrites = false;
44 protected $mPHPError = false;
45
46 protected $mServer, $mUser, $mPassword, $mDBname;
47
48 /** @var BagOStuff APC cache */
49 protected $srvCache;
50
51 /** @var resource Database connection */
52 protected $mConn = null;
53 protected $mOpened = false;
54
55 /** @var callable[] */
56 protected $mTrxIdleCallbacks = array();
57 /** @var callable[] */
58 protected $mTrxPreCommitCallbacks = array();
59
60 protected $mTablePrefix;
61 protected $mSchema;
62 protected $mFlags;
63 protected $mForeign;
64 protected $mLBInfo = array();
65 protected $mDefaultBigSelects = null;
66 protected $mSchemaVars = false;
67 /** @var array */
68 protected $mSessionVars = array();
69
70 protected $preparedArgs;
71
72 protected $htmlErrors;
73
74 protected $delimiter = ';';
75
76 /**
77 * Either 1 if a transaction is active or 0 otherwise.
78 * The other Trx fields may not be meaningfull if this is 0.
79 *
80 * @var int
81 */
82 protected $mTrxLevel = 0;
83
84 /**
85 * Either a short hexidecimal string if a transaction is active or ""
86 *
87 * @var string
88 * @see DatabaseBase::mTrxLevel
89 */
90 protected $mTrxShortId = '';
91
92 /**
93 * The UNIX time that the transaction started. Callers can assume that if
94 * snapshot isolation is used, then the data is *at least* up to date to that
95 * point (possibly more up-to-date since the first SELECT defines the snapshot).
96 *
97 * @var float|null
98 * @see DatabaseBase::mTrxLevel
99 */
100 private $mTrxTimestamp = null;
101
102 /** @var float Lag estimate at the time of BEGIN */
103 private $mTrxSlaveLag = null;
104
105 /**
106 * Remembers the function name given for starting the most recent transaction via begin().
107 * Used to provide additional context for error reporting.
108 *
109 * @var string
110 * @see DatabaseBase::mTrxLevel
111 */
112 private $mTrxFname = null;
113
114 /**
115 * Record if possible write queries were done in the last transaction started
116 *
117 * @var bool
118 * @see DatabaseBase::mTrxLevel
119 */
120 private $mTrxDoneWrites = false;
121
122 /**
123 * Record if the current transaction was started implicitly due to DBO_TRX being set.
124 *
125 * @var bool
126 * @see DatabaseBase::mTrxLevel
127 */
128 private $mTrxAutomatic = false;
129
130 /**
131 * Array of levels of atomicity within transactions
132 *
133 * @var array
134 */
135 private $mTrxAtomicLevels = array();
136
137 /**
138 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
139 *
140 * @var bool
141 */
142 private $mTrxAutomaticAtomic = false;
143
144 /**
145 * Track the seconds spent in write queries for the current transaction
146 *
147 * @var float
148 */
149 private $mTrxWriteDuration = 0.0;
150
151 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
152 private $lazyMasterHandle;
153
154 /**
155 * @since 1.21
156 * @var resource File handle for upgrade
157 */
158 protected $fileHandle = null;
159
160 /**
161 * @since 1.22
162 * @var string[] Process cache of VIEWs names in the database
163 */
164 protected $allViews = null;
165
166 /** @var TransactionProfiler */
167 protected $trxProfiler;
168
169 /**
170 * A string describing the current software version, and possibly
171 * other details in a user-friendly way. Will be listed on Special:Version, etc.
172 * Use getServerVersion() to get machine-friendly information.
173 *
174 * @return string Version information from the database server
175 */
176 public function getServerInfo() {
177 return $this->getServerVersion();
178 }
179
180 /**
181 * @return string Command delimiter used by this database engine
182 */
183 public function getDelimiter() {
184 return $this->delimiter;
185 }
186
187 /**
188 * Boolean, controls output of large amounts of debug information.
189 * @param bool|null $debug
190 * - true to enable debugging
191 * - false to disable debugging
192 * - omitted or null to do nothing
193 *
194 * @return bool|null Previous value of the flag
195 */
196 public function debug( $debug = null ) {
197 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
198 }
199
200 /**
201 * Turns buffering of SQL result sets on (true) or off (false). Default is
202 * "on".
203 *
204 * Unbuffered queries are very troublesome in MySQL:
205 *
206 * - If another query is executed while the first query is being read
207 * out, the first query is killed. This means you can't call normal
208 * MediaWiki functions while you are reading an unbuffered query result
209 * from a normal wfGetDB() connection.
210 *
211 * - Unbuffered queries cause the MySQL server to use large amounts of
212 * memory and to hold broad locks which block other queries.
213 *
214 * If you want to limit client-side memory, it's almost always better to
215 * split up queries into batches using a LIMIT clause than to switch off
216 * buffering.
217 *
218 * @param null|bool $buffer
219 * @return null|bool The previous value of the flag
220 */
221 public function bufferResults( $buffer = null ) {
222 if ( is_null( $buffer ) ) {
223 return !(bool)( $this->mFlags & DBO_NOBUFFER );
224 } else {
225 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
226 }
227 }
228
229 /**
230 * Turns on (false) or off (true) the automatic generation and sending
231 * of a "we're sorry, but there has been a database error" page on
232 * database errors. Default is on (false). When turned off, the
233 * code should use lastErrno() and lastError() to handle the
234 * situation as appropriate.
235 *
236 * Do not use this function outside of the Database classes.
237 *
238 * @param null|bool $ignoreErrors
239 * @return bool The previous value of the flag.
240 */
241 protected function ignoreErrors( $ignoreErrors = null ) {
242 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
243 }
244
245 /**
246 * Gets the current transaction level.
247 *
248 * Historically, transactions were allowed to be "nested". This is no
249 * longer supported, so this function really only returns a boolean.
250 *
251 * @return int The previous value
252 */
253 public function trxLevel() {
254 return $this->mTrxLevel;
255 }
256
257 /**
258 * Get the UNIX timestamp of the time that the transaction was established
259 *
260 * This can be used to reason about the staleness of SELECT data
261 * in REPEATABLE-READ transaction isolation level.
262 *
263 * @return float|null Returns null if there is not active transaction
264 * @since 1.25
265 */
266 public function trxTimestamp() {
267 return $this->mTrxLevel ? $this->mTrxTimestamp : null;
268 }
269
270 /**
271 * Get/set the table prefix.
272 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
273 * @return string The previous table prefix.
274 */
275 public function tablePrefix( $prefix = null ) {
276 return wfSetVar( $this->mTablePrefix, $prefix );
277 }
278
279 /**
280 * Get/set the db schema.
281 * @param string $schema The database schema to set, or omitted to leave it unchanged.
282 * @return string The previous db schema.
283 */
284 public function dbSchema( $schema = null ) {
285 return wfSetVar( $this->mSchema, $schema );
286 }
287
288 /**
289 * Set the filehandle to copy write statements to.
290 *
291 * @param resource $fh File handle
292 */
293 public function setFileHandle( $fh ) {
294 $this->fileHandle = $fh;
295 }
296
297 /**
298 * Get properties passed down from the server info array of the load
299 * balancer.
300 *
301 * @param string $name The entry of the info array to get, or null to get the
302 * whole array
303 *
304 * @return array|mixed|null
305 */
306 public function getLBInfo( $name = null ) {
307 if ( is_null( $name ) ) {
308 return $this->mLBInfo;
309 } else {
310 if ( array_key_exists( $name, $this->mLBInfo ) ) {
311 return $this->mLBInfo[$name];
312 } else {
313 return null;
314 }
315 }
316 }
317
318 /**
319 * Set the LB info array, or a member of it. If called with one parameter,
320 * the LB info array is set to that parameter. If it is called with two
321 * parameters, the member with the given name is set to the given value.
322 *
323 * @param string $name
324 * @param array $value
325 */
326 public function setLBInfo( $name, $value = null ) {
327 if ( is_null( $value ) ) {
328 $this->mLBInfo = $name;
329 } else {
330 $this->mLBInfo[$name] = $value;
331 }
332 }
333
334 /**
335 * Set a lazy-connecting DB handle to the master DB (for replication status purposes)
336 *
337 * @param IDatabase $conn
338 * @since 1.27
339 */
340 public function setLazyMasterHandle( IDatabase $conn ) {
341 $this->lazyMasterHandle = $conn;
342 }
343
344 /**
345 * @return IDatabase|null
346 * @see setLazyMasterHandle()
347 * @since 1.27
348 */
349 public function getLazyMasterHandle() {
350 return $this->lazyMasterHandle;
351 }
352
353 /**
354 * @return TransactionProfiler
355 */
356 protected function getTransactionProfiler() {
357 return $this->trxProfiler
358 ? $this->trxProfiler
359 : Profiler::instance()->getTransactionProfiler();
360 }
361
362 /**
363 * Returns true if this database supports (and uses) cascading deletes
364 *
365 * @return bool
366 */
367 public function cascadingDeletes() {
368 return false;
369 }
370
371 /**
372 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
373 *
374 * @return bool
375 */
376 public function cleanupTriggers() {
377 return false;
378 }
379
380 /**
381 * Returns true if this database is strict about what can be put into an IP field.
382 * Specifically, it uses a NULL value instead of an empty string.
383 *
384 * @return bool
385 */
386 public function strictIPs() {
387 return false;
388 }
389
390 /**
391 * Returns true if this database uses timestamps rather than integers
392 *
393 * @return bool
394 */
395 public function realTimestamps() {
396 return false;
397 }
398
399 /**
400 * Returns true if this database does an implicit sort when doing GROUP BY
401 *
402 * @return bool
403 */
404 public function implicitGroupby() {
405 return true;
406 }
407
408 /**
409 * Returns true if this database does an implicit order by when the column has an index
410 * For example: SELECT page_title FROM page LIMIT 1
411 *
412 * @return bool
413 */
414 public function implicitOrderby() {
415 return true;
416 }
417
418 /**
419 * Returns true if this database can do a native search on IP columns
420 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
421 *
422 * @return bool
423 */
424 public function searchableIPs() {
425 return false;
426 }
427
428 /**
429 * Returns true if this database can use functional indexes
430 *
431 * @return bool
432 */
433 public function functionalIndexes() {
434 return false;
435 }
436
437 /**
438 * Return the last query that went through DatabaseBase::query()
439 * @return string
440 */
441 public function lastQuery() {
442 return $this->mLastQuery;
443 }
444
445 /**
446 * Returns true if the connection may have been used for write queries.
447 * Should return true if unsure.
448 *
449 * @return bool
450 */
451 public function doneWrites() {
452 return (bool)$this->mDoneWrites;
453 }
454
455 /**
456 * Returns the last time the connection may have been used for write queries.
457 * Should return a timestamp if unsure.
458 *
459 * @return int|float UNIX timestamp or false
460 * @since 1.24
461 */
462 public function lastDoneWrites() {
463 return $this->mDoneWrites ?: false;
464 }
465
466 /**
467 * @return bool Whether there is a transaction open with possible write queries
468 * @since 1.27
469 */
470 public function writesPending() {
471 return $this->mTrxLevel && $this->mTrxDoneWrites;
472 }
473
474 /**
475 * Returns true if there is a transaction open with possible write
476 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
477 *
478 * @return bool
479 */
480 public function writesOrCallbacksPending() {
481 return $this->mTrxLevel && (
482 $this->mTrxDoneWrites || $this->mTrxIdleCallbacks || $this->mTrxPreCommitCallbacks
483 );
484 }
485
486 /**
487 * Get the time spend running write queries for this
488 *
489 * High times could be due to scanning, updates, locking, and such
490 *
491 * @return float|bool Returns false if not transaction is active
492 * @since 1.26
493 */
494 public function pendingWriteQueryDuration() {
495 return $this->mTrxLevel ? $this->mTrxWriteDuration : false;
496 }
497
498 /**
499 * Is a connection to the database open?
500 * @return bool
501 */
502 public function isOpen() {
503 return $this->mOpened;
504 }
505
506 /**
507 * Set a flag for this connection
508 *
509 * @param int $flag DBO_* constants from Defines.php:
510 * - DBO_DEBUG: output some debug info (same as debug())
511 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
512 * - DBO_TRX: automatically start transactions
513 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
514 * and removes it in command line mode
515 * - DBO_PERSISTENT: use persistant database connection
516 */
517 public function setFlag( $flag ) {
518 $this->mFlags |= $flag;
519 }
520
521 /**
522 * Clear a flag for this connection
523 *
524 * @param int $flag DBO_* constants from Defines.php:
525 * - DBO_DEBUG: output some debug info (same as debug())
526 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
527 * - DBO_TRX: automatically start transactions
528 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
529 * and removes it in command line mode
530 * - DBO_PERSISTENT: use persistant database connection
531 */
532 public function clearFlag( $flag ) {
533 $this->mFlags &= ~$flag;
534 }
535
536 /**
537 * Returns a boolean whether the flag $flag is set for this connection
538 *
539 * @param int $flag DBO_* constants from Defines.php:
540 * - DBO_DEBUG: output some debug info (same as debug())
541 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
542 * - DBO_TRX: automatically start transactions
543 * - DBO_PERSISTENT: use persistant database connection
544 * @return bool
545 */
546 public function getFlag( $flag ) {
547 return !!( $this->mFlags & $flag );
548 }
549
550 /**
551 * General read-only accessor
552 *
553 * @param string $name
554 * @return string
555 */
556 public function getProperty( $name ) {
557 return $this->$name;
558 }
559
560 /**
561 * @return string
562 */
563 public function getWikiID() {
564 if ( $this->mTablePrefix ) {
565 return "{$this->mDBname}-{$this->mTablePrefix}";
566 } else {
567 return $this->mDBname;
568 }
569 }
570
571 /**
572 * Return a path to the DBMS-specific SQL file if it exists,
573 * otherwise default SQL file
574 *
575 * @param string $filename
576 * @return string
577 */
578 private function getSqlFilePath( $filename ) {
579 global $IP;
580 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
581 if ( file_exists( $dbmsSpecificFilePath ) ) {
582 return $dbmsSpecificFilePath;
583 } else {
584 return "$IP/maintenance/$filename";
585 }
586 }
587
588 /**
589 * Return a path to the DBMS-specific schema file,
590 * otherwise default to tables.sql
591 *
592 * @return string
593 */
594 public function getSchemaPath() {
595 return $this->getSqlFilePath( 'tables.sql' );
596 }
597
598 /**
599 * Return a path to the DBMS-specific update key file,
600 * otherwise default to update-keys.sql
601 *
602 * @return string
603 */
604 public function getUpdateKeysPath() {
605 return $this->getSqlFilePath( 'update-keys.sql' );
606 }
607
608 /**
609 * Get information about an index into an object
610 * @param string $table Table name
611 * @param string $index Index name
612 * @param string $fname Calling function name
613 * @return mixed Database-specific index description class or false if the index does not exist
614 */
615 abstract function indexInfo( $table, $index, $fname = __METHOD__ );
616
617 /**
618 * Wrapper for addslashes()
619 *
620 * @param string $s String to be slashed.
621 * @return string Slashed string.
622 */
623 abstract function strencode( $s );
624
625 /**
626 * Constructor.
627 *
628 * FIXME: It is possible to construct a Database object with no associated
629 * connection object, by specifying no parameters to __construct(). This
630 * feature is deprecated and should be removed.
631 *
632 * DatabaseBase subclasses should not be constructed directly in external
633 * code. DatabaseBase::factory() should be used instead.
634 *
635 * @param array $params Parameters passed from DatabaseBase::factory()
636 */
637 function __construct( array $params ) {
638 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode;
639
640 $this->srvCache = ObjectCache::getLocalServerInstance( 'hash' );
641
642 $server = $params['host'];
643 $user = $params['user'];
644 $password = $params['password'];
645 $dbName = $params['dbname'];
646 $flags = $params['flags'];
647 $tablePrefix = $params['tablePrefix'];
648 $schema = $params['schema'];
649 $foreign = $params['foreign'];
650
651 $this->mFlags = $flags;
652 if ( $this->mFlags & DBO_DEFAULT ) {
653 if ( $wgCommandLineMode ) {
654 $this->mFlags &= ~DBO_TRX;
655 } else {
656 $this->mFlags |= DBO_TRX;
657 }
658 }
659
660 $this->mSessionVars = $params['variables'];
661
662 /** Get the default table prefix*/
663 if ( $tablePrefix === 'get from global' ) {
664 $this->mTablePrefix = $wgDBprefix;
665 } else {
666 $this->mTablePrefix = $tablePrefix;
667 }
668
669 /** Get the database schema*/
670 if ( $schema === 'get from global' ) {
671 $this->mSchema = $wgDBmwschema;
672 } else {
673 $this->mSchema = $schema;
674 }
675
676 $this->mForeign = $foreign;
677
678 if ( isset( $params['trxProfiler'] ) ) {
679 $this->trxProfiler = $params['trxProfiler']; // override
680 }
681
682 if ( $user ) {
683 $this->open( $server, $user, $password, $dbName );
684 }
685 }
686
687 /**
688 * Called by serialize. Throw an exception when DB connection is serialized.
689 * This causes problems on some database engines because the connection is
690 * not restored on unserialize.
691 */
692 public function __sleep() {
693 throw new MWException( 'Database serialization may cause problems, since ' .
694 'the connection is not restored on wakeup.' );
695 }
696
697 /**
698 * Given a DB type, construct the name of the appropriate child class of
699 * DatabaseBase. This is designed to replace all of the manual stuff like:
700 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
701 * as well as validate against the canonical list of DB types we have
702 *
703 * This factory function is mostly useful for when you need to connect to a
704 * database other than the MediaWiki default (such as for external auth,
705 * an extension, et cetera). Do not use this to connect to the MediaWiki
706 * database. Example uses in core:
707 * @see LoadBalancer::reallyOpenConnection()
708 * @see ForeignDBRepo::getMasterDB()
709 * @see WebInstallerDBConnect::execute()
710 *
711 * @since 1.18
712 *
713 * @param string $dbType A possible DB type
714 * @param array $p An array of options to pass to the constructor.
715 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
716 * @throws MWException If the database driver or extension cannot be found
717 * @return DatabaseBase|null DatabaseBase subclass or null
718 */
719 final public static function factory( $dbType, $p = array() ) {
720 $canonicalDBTypes = array(
721 'mysql' => array( 'mysqli', 'mysql' ),
722 'postgres' => array(),
723 'sqlite' => array(),
724 'oracle' => array(),
725 'mssql' => array(),
726 );
727
728 $driver = false;
729 $dbType = strtolower( $dbType );
730 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
731 $possibleDrivers = $canonicalDBTypes[$dbType];
732 if ( !empty( $p['driver'] ) ) {
733 if ( in_array( $p['driver'], $possibleDrivers ) ) {
734 $driver = $p['driver'];
735 } else {
736 throw new MWException( __METHOD__ .
737 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
738 }
739 } else {
740 foreach ( $possibleDrivers as $posDriver ) {
741 if ( extension_loaded( $posDriver ) ) {
742 $driver = $posDriver;
743 break;
744 }
745 }
746 }
747 } else {
748 $driver = $dbType;
749 }
750 if ( $driver === false ) {
751 throw new MWException( __METHOD__ .
752 " no viable database extension found for type '$dbType'" );
753 }
754
755 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
756 // and everything else doesn't use a schema (e.g. null)
757 // Although postgres and oracle support schemas, we don't use them (yet)
758 // to maintain backwards compatibility
759 $defaultSchemas = array(
760 'mssql' => 'get from global',
761 );
762
763 $class = 'Database' . ucfirst( $driver );
764 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
765 // Resolve some defaults for b/c
766 $p['host'] = isset( $p['host'] ) ? $p['host'] : false;
767 $p['user'] = isset( $p['user'] ) ? $p['user'] : false;
768 $p['password'] = isset( $p['password'] ) ? $p['password'] : false;
769 $p['dbname'] = isset( $p['dbname'] ) ? $p['dbname'] : false;
770 $p['flags'] = isset( $p['flags'] ) ? $p['flags'] : 0;
771 $p['variables'] = isset( $p['variables'] ) ? $p['variables'] : array();
772 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : 'get from global';
773 if ( !isset( $p['schema'] ) ) {
774 $p['schema'] = isset( $defaultSchemas[$dbType] ) ? $defaultSchemas[$dbType] : null;
775 }
776 $p['foreign'] = isset( $p['foreign'] ) ? $p['foreign'] : false;
777
778 return new $class( $p );
779 } else {
780 return null;
781 }
782 }
783
784 protected function installErrorHandler() {
785 $this->mPHPError = false;
786 $this->htmlErrors = ini_set( 'html_errors', '0' );
787 set_error_handler( array( $this, 'connectionErrorHandler' ) );
788 }
789
790 /**
791 * @return bool|string
792 */
793 protected function restoreErrorHandler() {
794 restore_error_handler();
795 if ( $this->htmlErrors !== false ) {
796 ini_set( 'html_errors', $this->htmlErrors );
797 }
798 if ( $this->mPHPError ) {
799 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
800 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
801
802 return $error;
803 } else {
804 return false;
805 }
806 }
807
808 /**
809 * @param int $errno
810 * @param string $errstr
811 */
812 public function connectionErrorHandler( $errno, $errstr ) {
813 $this->mPHPError = $errstr;
814 }
815
816 /**
817 * Create a log context to pass to wfLogDBError or other logging functions.
818 *
819 * @param array $extras Additional data to add to context
820 * @return array
821 */
822 protected function getLogContext( array $extras = array() ) {
823 return array_merge(
824 array(
825 'db_server' => $this->mServer,
826 'db_name' => $this->mDBname,
827 'db_user' => $this->mUser,
828 ),
829 $extras
830 );
831 }
832
833 /**
834 * Closes a database connection.
835 * if it is open : commits any open transactions
836 *
837 * @throws MWException
838 * @return bool Operation success. true if already closed.
839 */
840 public function close() {
841 if ( count( $this->mTrxIdleCallbacks ) ) { // sanity
842 throw new MWException( "Transaction idle callbacks still pending." );
843 }
844 if ( $this->mConn ) {
845 if ( $this->trxLevel() ) {
846 if ( !$this->mTrxAutomatic ) {
847 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
848 " performing implicit commit before closing connection!" );
849 }
850
851 $this->commit( __METHOD__, 'flush' );
852 }
853
854 $closed = $this->closeConnection();
855 $this->mConn = false;
856 } else {
857 $closed = true;
858 }
859 $this->mOpened = false;
860
861 return $closed;
862 }
863
864 /**
865 * Make sure isOpen() returns true as a sanity check
866 *
867 * @throws DBUnexpectedError
868 */
869 protected function assertOpen() {
870 if ( !$this->isOpen() ) {
871 throw new DBUnexpectedError( $this, "DB connection was already closed." );
872 }
873 }
874
875 /**
876 * Closes underlying database connection
877 * @since 1.20
878 * @return bool Whether connection was closed successfully
879 */
880 abstract protected function closeConnection();
881
882 /**
883 * @param string $error Fallback error message, used if none is given by DB
884 * @throws DBConnectionError
885 */
886 function reportConnectionError( $error = 'Unknown error' ) {
887 $myError = $this->lastError();
888 if ( $myError ) {
889 $error = $myError;
890 }
891
892 # New method
893 throw new DBConnectionError( $this, $error );
894 }
895
896 /**
897 * The DBMS-dependent part of query()
898 *
899 * @param string $sql SQL query.
900 * @return ResultWrapper|bool Result object to feed to fetchObject,
901 * fetchRow, ...; or false on failure
902 */
903 abstract protected function doQuery( $sql );
904
905 /**
906 * Determine whether a query writes to the DB.
907 * Should return true if unsure.
908 *
909 * @param string $sql
910 * @return bool
911 */
912 protected function isWriteQuery( $sql ) {
913 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
914 }
915
916 /**
917 * Determine whether a SQL statement is sensitive to isolation level.
918 * A SQL statement is considered transactable if its result could vary
919 * depending on the transaction isolation level. Operational commands
920 * such as 'SET' and 'SHOW' are not considered to be transactable.
921 *
922 * @param string $sql
923 * @return bool
924 */
925 protected function isTransactableQuery( $sql ) {
926 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
927 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
928 }
929
930 /**
931 * Run an SQL query and return the result. Normally throws a DBQueryError
932 * on failure. If errors are ignored, returns false instead.
933 *
934 * In new code, the query wrappers select(), insert(), update(), delete(),
935 * etc. should be used where possible, since they give much better DBMS
936 * independence and automatically quote or validate user input in a variety
937 * of contexts. This function is generally only useful for queries which are
938 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
939 * as CREATE TABLE.
940 *
941 * However, the query wrappers themselves should call this function.
942 *
943 * @param string $sql SQL query
944 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
945 * comment (you can use __METHOD__ or add some extra info)
946 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
947 * maybe best to catch the exception instead?
948 * @throws MWException
949 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
950 * for a successful read query, or false on failure if $tempIgnore set
951 */
952 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
953 global $wgUser;
954
955 $this->mLastQuery = $sql;
956
957 $isWriteQuery = $this->isWriteQuery( $sql );
958 if ( $isWriteQuery ) {
959 $reason = $this->getReadOnlyReason();
960 if ( $reason !== false ) {
961 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
962 }
963 # Set a flag indicating that writes have been done
964 $this->mDoneWrites = microtime( true );
965 }
966
967 # Add a comment for easy SHOW PROCESSLIST interpretation
968 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
969 $userName = $wgUser->getName();
970 if ( mb_strlen( $userName ) > 15 ) {
971 $userName = mb_substr( $userName, 0, 15 ) . '...';
972 }
973 $userName = str_replace( '/', '', $userName );
974 } else {
975 $userName = '';
976 }
977
978 // Add trace comment to the begin of the sql string, right after the operator.
979 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
980 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
981
982 if ( !$this->mTrxLevel && $this->getFlag( DBO_TRX ) && $this->isTransactableQuery( $sql ) ) {
983 $this->begin( __METHOD__ . " ($fname)" );
984 $this->mTrxAutomatic = true;
985 }
986
987 # Keep track of whether the transaction has write queries pending
988 if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $isWriteQuery ) {
989 $this->mTrxDoneWrites = true;
990 $this->getTransactionProfiler()->transactionWritingIn(
991 $this->mServer, $this->mDBname, $this->mTrxShortId );
992 }
993
994 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
995 # generalizeSQL will probably cut down the query to reasonable
996 # logging size most of the time. The substr is really just a sanity check.
997 if ( $isMaster ) {
998 $queryProf = 'query-m: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
999 $totalProf = 'DatabaseBase::query-master';
1000 } else {
1001 $queryProf = 'query: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
1002 $totalProf = 'DatabaseBase::query';
1003 }
1004 # Include query transaction state
1005 $queryProf .= $this->mTrxShortId ? " [TRX#{$this->mTrxShortId}]" : "";
1006
1007 $profiler = Profiler::instance();
1008 if ( !$profiler instanceof ProfilerStub ) {
1009 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
1010 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
1011 }
1012
1013 if ( $this->debug() ) {
1014 wfDebugLog( 'queries', sprintf( "%s: %s", $this->mDBname, $commentedSql ) );
1015 }
1016
1017 $queryId = MWDebug::query( $sql, $fname, $isMaster );
1018
1019 # Avoid fatals if close() was called
1020 $this->assertOpen();
1021
1022 # Do the query and handle errors
1023 $startTime = microtime( true );
1024 $ret = $this->doQuery( $commentedSql );
1025 $queryRuntime = microtime( true ) - $startTime;
1026 # Log the query time and feed it into the DB trx profiler
1027 $this->getTransactionProfiler()->recordQueryCompletion(
1028 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1029
1030 MWDebug::queryTime( $queryId );
1031
1032 # Try reconnecting if the connection was lost
1033 if ( false === $ret && $this->wasErrorReissuable() ) {
1034 # Transaction is gone, like it or not
1035 $hadTrx = $this->mTrxLevel; // possible lost transaction
1036 $this->mTrxLevel = 0;
1037 $this->mTrxIdleCallbacks = array(); // bug 65263
1038 $this->mTrxPreCommitCallbacks = array(); // bug 65263
1039 wfDebug( "Connection lost, reconnecting...\n" );
1040 # Stash the last error values since ping() might clear them
1041 $lastError = $this->lastError();
1042 $lastErrno = $this->lastErrno();
1043 if ( $this->ping() ) {
1044 wfDebug( "Reconnected\n" );
1045 $server = $this->getServer();
1046 $msg = __METHOD__ . ": lost connection to $server; reconnected";
1047 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1048
1049 if ( $hadTrx ) {
1050 # Leave $ret as false and let an error be reported.
1051 # Callers may catch the exception and continue to use the DB.
1052 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1053 } else {
1054 # Should be safe to silently retry (no trx and thus no callbacks)
1055 $startTime = microtime( true );
1056 $ret = $this->doQuery( $commentedSql );
1057 $queryRuntime = microtime( true ) - $startTime;
1058 # Log the query time and feed it into the DB trx profiler
1059 $this->getTransactionProfiler()->recordQueryCompletion(
1060 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1061 }
1062 } else {
1063 wfDebug( "Failed\n" );
1064 }
1065 }
1066
1067 if ( false === $ret ) {
1068 $this->reportQueryError(
1069 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1070 }
1071
1072 $res = $this->resultObject( $ret );
1073
1074 // Destroy profile sections in the opposite order to their creation
1075 ScopedCallback::consume( $queryProfSection );
1076 ScopedCallback::consume( $totalProfSection );
1077
1078 if ( $isWriteQuery && $this->mTrxLevel ) {
1079 $this->mTrxWriteDuration += $queryRuntime;
1080 }
1081
1082 return $res;
1083 }
1084
1085 /**
1086 * Report a query error. Log the error, and if neither the object ignore
1087 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1088 *
1089 * @param string $error
1090 * @param int $errno
1091 * @param string $sql
1092 * @param string $fname
1093 * @param bool $tempIgnore
1094 * @throws DBQueryError
1095 */
1096 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1097 if ( $this->ignoreErrors() || $tempIgnore ) {
1098 wfDebug( "SQL ERROR (ignored): $error\n" );
1099 } else {
1100 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1101 wfLogDBError(
1102 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1103 $this->getLogContext( array(
1104 'method' => __METHOD__,
1105 'errno' => $errno,
1106 'error' => $error,
1107 'sql1line' => $sql1line,
1108 'fname' => $fname,
1109 ) )
1110 );
1111 wfDebug( "SQL ERROR: " . $error . "\n" );
1112 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1113 }
1114 }
1115
1116 /**
1117 * Intended to be compatible with the PEAR::DB wrapper functions.
1118 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1119 *
1120 * ? = scalar value, quoted as necessary
1121 * ! = raw SQL bit (a function for instance)
1122 * & = filename; reads the file and inserts as a blob
1123 * (we don't use this though...)
1124 *
1125 * @param string $sql
1126 * @param string $func
1127 *
1128 * @return array
1129 */
1130 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1131 /* MySQL doesn't support prepared statements (yet), so just
1132 * pack up the query for reference. We'll manually replace
1133 * the bits later.
1134 */
1135 return array( 'query' => $sql, 'func' => $func );
1136 }
1137
1138 /**
1139 * Free a prepared query, generated by prepare().
1140 * @param string $prepared
1141 */
1142 protected function freePrepared( $prepared ) {
1143 /* No-op by default */
1144 }
1145
1146 /**
1147 * Execute a prepared query with the various arguments
1148 * @param string $prepared The prepared sql
1149 * @param mixed $args Either an array here, or put scalars as varargs
1150 *
1151 * @return ResultWrapper
1152 */
1153 public function execute( $prepared, $args = null ) {
1154 if ( !is_array( $args ) ) {
1155 # Pull the var args
1156 $args = func_get_args();
1157 array_shift( $args );
1158 }
1159
1160 $sql = $this->fillPrepared( $prepared['query'], $args );
1161
1162 return $this->query( $sql, $prepared['func'] );
1163 }
1164
1165 /**
1166 * For faking prepared SQL statements on DBs that don't support it directly.
1167 *
1168 * @param string $preparedQuery A 'preparable' SQL statement
1169 * @param array $args Array of Arguments to fill it with
1170 * @return string Executable SQL
1171 */
1172 public function fillPrepared( $preparedQuery, $args ) {
1173 reset( $args );
1174 $this->preparedArgs =& $args;
1175
1176 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1177 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1178 }
1179
1180 /**
1181 * preg_callback func for fillPrepared()
1182 * The arguments should be in $this->preparedArgs and must not be touched
1183 * while we're doing this.
1184 *
1185 * @param array $matches
1186 * @throws DBUnexpectedError
1187 * @return string
1188 */
1189 protected function fillPreparedArg( $matches ) {
1190 switch ( $matches[1] ) {
1191 case '\\?':
1192 return '?';
1193 case '\\!':
1194 return '!';
1195 case '\\&':
1196 return '&';
1197 }
1198
1199 list( /* $n */, $arg ) = each( $this->preparedArgs );
1200
1201 switch ( $matches[1] ) {
1202 case '?':
1203 return $this->addQuotes( $arg );
1204 case '!':
1205 return $arg;
1206 case '&':
1207 # return $this->addQuotes( file_get_contents( $arg ) );
1208 throw new DBUnexpectedError(
1209 $this,
1210 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1211 );
1212 default:
1213 throw new DBUnexpectedError(
1214 $this,
1215 'Received invalid match. This should never happen!'
1216 );
1217 }
1218 }
1219
1220 /**
1221 * Free a result object returned by query() or select(). It's usually not
1222 * necessary to call this, just use unset() or let the variable holding
1223 * the result object go out of scope.
1224 *
1225 * @param mixed $res A SQL result
1226 */
1227 public function freeResult( $res ) {
1228 }
1229
1230 /**
1231 * A SELECT wrapper which returns a single field from a single result row.
1232 *
1233 * Usually throws a DBQueryError on failure. If errors are explicitly
1234 * ignored, returns false on failure.
1235 *
1236 * If no result rows are returned from the query, false is returned.
1237 *
1238 * @param string|array $table Table name. See DatabaseBase::select() for details.
1239 * @param string $var The field name to select. This must be a valid SQL
1240 * fragment: do not use unvalidated user input.
1241 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1242 * @param string $fname The function name of the caller.
1243 * @param string|array $options The query options. See DatabaseBase::select() for details.
1244 *
1245 * @return bool|mixed The value from the field, or false on failure.
1246 * @throws DBUnexpectedError
1247 */
1248 public function selectField(
1249 $table, $var, $cond = '', $fname = __METHOD__, $options = array()
1250 ) {
1251 if ( $var === '*' ) { // sanity
1252 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1253 }
1254
1255 if ( !is_array( $options ) ) {
1256 $options = array( $options );
1257 }
1258
1259 $options['LIMIT'] = 1;
1260
1261 $res = $this->select( $table, $var, $cond, $fname, $options );
1262 if ( $res === false || !$this->numRows( $res ) ) {
1263 return false;
1264 }
1265
1266 $row = $this->fetchRow( $res );
1267
1268 if ( $row !== false ) {
1269 return reset( $row );
1270 } else {
1271 return false;
1272 }
1273 }
1274
1275 /**
1276 * A SELECT wrapper which returns a list of single field values from result rows.
1277 *
1278 * Usually throws a DBQueryError on failure. If errors are explicitly
1279 * ignored, returns false on failure.
1280 *
1281 * If no result rows are returned from the query, false is returned.
1282 *
1283 * @param string|array $table Table name. See DatabaseBase::select() for details.
1284 * @param string $var The field name to select. This must be a valid SQL
1285 * fragment: do not use unvalidated user input.
1286 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1287 * @param string $fname The function name of the caller.
1288 * @param string|array $options The query options. See DatabaseBase::select() for details.
1289 *
1290 * @return bool|array The values from the field, or false on failure
1291 * @throws DBUnexpectedError
1292 * @since 1.25
1293 */
1294 public function selectFieldValues(
1295 $table, $var, $cond = '', $fname = __METHOD__, $options = array()
1296 ) {
1297 if ( $var === '*' ) { // sanity
1298 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1299 }
1300
1301 if ( !is_array( $options ) ) {
1302 $options = array( $options );
1303 }
1304
1305 $res = $this->select( $table, $var, $cond, $fname, $options );
1306 if ( $res === false ) {
1307 return false;
1308 }
1309
1310 $values = array();
1311 foreach ( $res as $row ) {
1312 $values[] = $row->$var;
1313 }
1314
1315 return $values;
1316 }
1317
1318 /**
1319 * Returns an optional USE INDEX clause to go after the table, and a
1320 * string to go at the end of the query.
1321 *
1322 * @param array $options Associative array of options to be turned into
1323 * an SQL query, valid keys are listed in the function.
1324 * @return array
1325 * @see DatabaseBase::select()
1326 */
1327 public function makeSelectOptions( $options ) {
1328 $preLimitTail = $postLimitTail = '';
1329 $startOpts = '';
1330
1331 $noKeyOptions = array();
1332
1333 foreach ( $options as $key => $option ) {
1334 if ( is_numeric( $key ) ) {
1335 $noKeyOptions[$option] = true;
1336 }
1337 }
1338
1339 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1340
1341 $preLimitTail .= $this->makeOrderBy( $options );
1342
1343 // if (isset($options['LIMIT'])) {
1344 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1345 // isset($options['OFFSET']) ? $options['OFFSET']
1346 // : false);
1347 // }
1348
1349 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1350 $postLimitTail .= ' FOR UPDATE';
1351 }
1352
1353 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1354 $postLimitTail .= ' LOCK IN SHARE MODE';
1355 }
1356
1357 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1358 $startOpts .= 'DISTINCT';
1359 }
1360
1361 # Various MySQL extensions
1362 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1363 $startOpts .= ' /*! STRAIGHT_JOIN */';
1364 }
1365
1366 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1367 $startOpts .= ' HIGH_PRIORITY';
1368 }
1369
1370 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1371 $startOpts .= ' SQL_BIG_RESULT';
1372 }
1373
1374 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1375 $startOpts .= ' SQL_BUFFER_RESULT';
1376 }
1377
1378 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1379 $startOpts .= ' SQL_SMALL_RESULT';
1380 }
1381
1382 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1383 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1384 }
1385
1386 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1387 $startOpts .= ' SQL_CACHE';
1388 }
1389
1390 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1391 $startOpts .= ' SQL_NO_CACHE';
1392 }
1393
1394 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1395 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1396 } else {
1397 $useIndex = '';
1398 }
1399
1400 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1401 }
1402
1403 /**
1404 * Returns an optional GROUP BY with an optional HAVING
1405 *
1406 * @param array $options Associative array of options
1407 * @return string
1408 * @see DatabaseBase::select()
1409 * @since 1.21
1410 */
1411 public function makeGroupByWithHaving( $options ) {
1412 $sql = '';
1413 if ( isset( $options['GROUP BY'] ) ) {
1414 $gb = is_array( $options['GROUP BY'] )
1415 ? implode( ',', $options['GROUP BY'] )
1416 : $options['GROUP BY'];
1417 $sql .= ' GROUP BY ' . $gb;
1418 }
1419 if ( isset( $options['HAVING'] ) ) {
1420 $having = is_array( $options['HAVING'] )
1421 ? $this->makeList( $options['HAVING'], LIST_AND )
1422 : $options['HAVING'];
1423 $sql .= ' HAVING ' . $having;
1424 }
1425
1426 return $sql;
1427 }
1428
1429 /**
1430 * Returns an optional ORDER BY
1431 *
1432 * @param array $options Associative array of options
1433 * @return string
1434 * @see DatabaseBase::select()
1435 * @since 1.21
1436 */
1437 public function makeOrderBy( $options ) {
1438 if ( isset( $options['ORDER BY'] ) ) {
1439 $ob = is_array( $options['ORDER BY'] )
1440 ? implode( ',', $options['ORDER BY'] )
1441 : $options['ORDER BY'];
1442
1443 return ' ORDER BY ' . $ob;
1444 }
1445
1446 return '';
1447 }
1448
1449 /**
1450 * Execute a SELECT query constructed using the various parameters provided.
1451 * See below for full details of the parameters.
1452 *
1453 * @param string|array $table Table name
1454 * @param string|array $vars Field names
1455 * @param string|array $conds Conditions
1456 * @param string $fname Caller function name
1457 * @param array $options Query options
1458 * @param array $join_conds Join conditions
1459 *
1460 *
1461 * @param string|array $table
1462 *
1463 * May be either an array of table names, or a single string holding a table
1464 * name. If an array is given, table aliases can be specified, for example:
1465 *
1466 * array( 'a' => 'user' )
1467 *
1468 * This includes the user table in the query, with the alias "a" available
1469 * for use in field names (e.g. a.user_name).
1470 *
1471 * All of the table names given here are automatically run through
1472 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1473 * added, and various other table name mappings to be performed.
1474 *
1475 *
1476 * @param string|array $vars
1477 *
1478 * May be either a field name or an array of field names. The field names
1479 * can be complete fragments of SQL, for direct inclusion into the SELECT
1480 * query. If an array is given, field aliases can be specified, for example:
1481 *
1482 * array( 'maxrev' => 'MAX(rev_id)' )
1483 *
1484 * This includes an expression with the alias "maxrev" in the query.
1485 *
1486 * If an expression is given, care must be taken to ensure that it is
1487 * DBMS-independent.
1488 *
1489 *
1490 * @param string|array $conds
1491 *
1492 * May be either a string containing a single condition, or an array of
1493 * conditions. If an array is given, the conditions constructed from each
1494 * element are combined with AND.
1495 *
1496 * Array elements may take one of two forms:
1497 *
1498 * - Elements with a numeric key are interpreted as raw SQL fragments.
1499 * - Elements with a string key are interpreted as equality conditions,
1500 * where the key is the field name.
1501 * - If the value of such an array element is a scalar (such as a
1502 * string), it will be treated as data and thus quoted appropriately.
1503 * If it is null, an IS NULL clause will be added.
1504 * - If the value is an array, an IN (...) clause will be constructed
1505 * from its non-null elements, and an IS NULL clause will be added
1506 * if null is present, such that the field may match any of the
1507 * elements in the array. The non-null elements will be quoted.
1508 *
1509 * Note that expressions are often DBMS-dependent in their syntax.
1510 * DBMS-independent wrappers are provided for constructing several types of
1511 * expression commonly used in condition queries. See:
1512 * - DatabaseBase::buildLike()
1513 * - DatabaseBase::conditional()
1514 *
1515 *
1516 * @param string|array $options
1517 *
1518 * Optional: Array of query options. Boolean options are specified by
1519 * including them in the array as a string value with a numeric key, for
1520 * example:
1521 *
1522 * array( 'FOR UPDATE' )
1523 *
1524 * The supported options are:
1525 *
1526 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1527 * with LIMIT can theoretically be used for paging through a result set,
1528 * but this is discouraged in MediaWiki for performance reasons.
1529 *
1530 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1531 * and then the first rows are taken until the limit is reached. LIMIT
1532 * is applied to a result set after OFFSET.
1533 *
1534 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1535 * changed until the next COMMIT.
1536 *
1537 * - DISTINCT: Boolean: return only unique result rows.
1538 *
1539 * - GROUP BY: May be either an SQL fragment string naming a field or
1540 * expression to group by, or an array of such SQL fragments.
1541 *
1542 * - HAVING: May be either an string containing a HAVING clause or an array of
1543 * conditions building the HAVING clause. If an array is given, the conditions
1544 * constructed from each element are combined with AND.
1545 *
1546 * - ORDER BY: May be either an SQL fragment giving a field name or
1547 * expression to order by, or an array of such SQL fragments.
1548 *
1549 * - USE INDEX: This may be either a string giving the index name to use
1550 * for the query, or an array. If it is an associative array, each key
1551 * gives the table name (or alias), each value gives the index name to
1552 * use for that table. All strings are SQL fragments and so should be
1553 * validated by the caller.
1554 *
1555 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1556 * instead of SELECT.
1557 *
1558 * And also the following boolean MySQL extensions, see the MySQL manual
1559 * for documentation:
1560 *
1561 * - LOCK IN SHARE MODE
1562 * - STRAIGHT_JOIN
1563 * - HIGH_PRIORITY
1564 * - SQL_BIG_RESULT
1565 * - SQL_BUFFER_RESULT
1566 * - SQL_SMALL_RESULT
1567 * - SQL_CALC_FOUND_ROWS
1568 * - SQL_CACHE
1569 * - SQL_NO_CACHE
1570 *
1571 *
1572 * @param string|array $join_conds
1573 *
1574 * Optional associative array of table-specific join conditions. In the
1575 * most common case, this is unnecessary, since the join condition can be
1576 * in $conds. However, it is useful for doing a LEFT JOIN.
1577 *
1578 * The key of the array contains the table name or alias. The value is an
1579 * array with two elements, numbered 0 and 1. The first gives the type of
1580 * join, the second is an SQL fragment giving the join condition for that
1581 * table. For example:
1582 *
1583 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1584 *
1585 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1586 * with no rows in it will be returned. If there was a query error, a
1587 * DBQueryError exception will be thrown, except if the "ignore errors"
1588 * option was set, in which case false will be returned.
1589 */
1590 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1591 $options = array(), $join_conds = array() ) {
1592 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1593
1594 return $this->query( $sql, $fname );
1595 }
1596
1597 /**
1598 * The equivalent of DatabaseBase::select() except that the constructed SQL
1599 * is returned, instead of being immediately executed. This can be useful for
1600 * doing UNION queries, where the SQL text of each query is needed. In general,
1601 * however, callers outside of Database classes should just use select().
1602 *
1603 * @param string|array $table Table name
1604 * @param string|array $vars Field names
1605 * @param string|array $conds Conditions
1606 * @param string $fname Caller function name
1607 * @param string|array $options Query options
1608 * @param string|array $join_conds Join conditions
1609 *
1610 * @return string SQL query string.
1611 * @see DatabaseBase::select()
1612 */
1613 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1614 $options = array(), $join_conds = array()
1615 ) {
1616 if ( is_array( $vars ) ) {
1617 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1618 }
1619
1620 $options = (array)$options;
1621 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1622 ? $options['USE INDEX']
1623 : array();
1624
1625 if ( is_array( $table ) ) {
1626 $from = ' FROM ' .
1627 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1628 } elseif ( $table != '' ) {
1629 if ( $table[0] == ' ' ) {
1630 $from = ' FROM ' . $table;
1631 } else {
1632 $from = ' FROM ' .
1633 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1634 }
1635 } else {
1636 $from = '';
1637 }
1638
1639 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1640 $this->makeSelectOptions( $options );
1641
1642 if ( !empty( $conds ) ) {
1643 if ( is_array( $conds ) ) {
1644 $conds = $this->makeList( $conds, LIST_AND );
1645 }
1646 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1647 } else {
1648 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1649 }
1650
1651 if ( isset( $options['LIMIT'] ) ) {
1652 $sql = $this->limitResult( $sql, $options['LIMIT'],
1653 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1654 }
1655 $sql = "$sql $postLimitTail";
1656
1657 if ( isset( $options['EXPLAIN'] ) ) {
1658 $sql = 'EXPLAIN ' . $sql;
1659 }
1660
1661 return $sql;
1662 }
1663
1664 /**
1665 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1666 * that a single row object is returned. If the query returns no rows,
1667 * false is returned.
1668 *
1669 * @param string|array $table Table name
1670 * @param string|array $vars Field names
1671 * @param array $conds Conditions
1672 * @param string $fname Caller function name
1673 * @param string|array $options Query options
1674 * @param array|string $join_conds Join conditions
1675 *
1676 * @return stdClass|bool
1677 */
1678 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1679 $options = array(), $join_conds = array()
1680 ) {
1681 $options = (array)$options;
1682 $options['LIMIT'] = 1;
1683 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1684
1685 if ( $res === false ) {
1686 return false;
1687 }
1688
1689 if ( !$this->numRows( $res ) ) {
1690 return false;
1691 }
1692
1693 $obj = $this->fetchObject( $res );
1694
1695 return $obj;
1696 }
1697
1698 /**
1699 * Estimate the number of rows in dataset
1700 *
1701 * MySQL allows you to estimate the number of rows that would be returned
1702 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1703 * index cardinality statistics, and is notoriously inaccurate, especially
1704 * when large numbers of rows have recently been added or deleted.
1705 *
1706 * For DBMSs that don't support fast result size estimation, this function
1707 * will actually perform the SELECT COUNT(*).
1708 *
1709 * Takes the same arguments as DatabaseBase::select().
1710 *
1711 * @param string $table Table name
1712 * @param string $vars Unused
1713 * @param array|string $conds Filters on the table
1714 * @param string $fname Function name for profiling
1715 * @param array $options Options for select
1716 * @return int Row count
1717 */
1718 public function estimateRowCount(
1719 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = array()
1720 ) {
1721 $rows = 0;
1722 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1723
1724 if ( $res ) {
1725 $row = $this->fetchRow( $res );
1726 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1727 }
1728
1729 return $rows;
1730 }
1731
1732 /**
1733 * Get the number of rows in dataset
1734 *
1735 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
1736 *
1737 * Takes the same arguments as DatabaseBase::select().
1738 *
1739 * @since 1.27 Added $join_conds parameter
1740 *
1741 * @param array|string $tables Table names
1742 * @param string $vars Unused
1743 * @param array|string $conds Filters on the table
1744 * @param string $fname Function name for profiling
1745 * @param array $options Options for select
1746 * @param array $join_conds Join conditions (since 1.27)
1747 * @return int Row count
1748 */
1749 public function selectRowCount(
1750 $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = array(), $join_conds = array()
1751 ) {
1752 $rows = 0;
1753 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1754 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1755
1756 if ( $res ) {
1757 $row = $this->fetchRow( $res );
1758 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1759 }
1760
1761 return $rows;
1762 }
1763
1764 /**
1765 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1766 * It's only slightly flawed. Don't use for anything important.
1767 *
1768 * @param string $sql A SQL Query
1769 *
1770 * @return string
1771 */
1772 protected static function generalizeSQL( $sql ) {
1773 # This does the same as the regexp below would do, but in such a way
1774 # as to avoid crashing php on some large strings.
1775 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1776
1777 $sql = str_replace( "\\\\", '', $sql );
1778 $sql = str_replace( "\\'", '', $sql );
1779 $sql = str_replace( "\\\"", '', $sql );
1780 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1781 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1782
1783 # All newlines, tabs, etc replaced by single space
1784 $sql = preg_replace( '/\s+/', ' ', $sql );
1785
1786 # All numbers => N,
1787 # except the ones surrounded by characters, e.g. l10n
1788 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1789 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1790
1791 return $sql;
1792 }
1793
1794 /**
1795 * Determines whether a field exists in a table
1796 *
1797 * @param string $table Table name
1798 * @param string $field Filed to check on that table
1799 * @param string $fname Calling function name (optional)
1800 * @return bool Whether $table has filed $field
1801 */
1802 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1803 $info = $this->fieldInfo( $table, $field );
1804
1805 return (bool)$info;
1806 }
1807
1808 /**
1809 * Determines whether an index exists
1810 * Usually throws a DBQueryError on failure
1811 * If errors are explicitly ignored, returns NULL on failure
1812 *
1813 * @param string $table
1814 * @param string $index
1815 * @param string $fname
1816 * @return bool|null
1817 */
1818 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1819 if ( !$this->tableExists( $table ) ) {
1820 return null;
1821 }
1822
1823 $info = $this->indexInfo( $table, $index, $fname );
1824 if ( is_null( $info ) ) {
1825 return null;
1826 } else {
1827 return $info !== false;
1828 }
1829 }
1830
1831 /**
1832 * Query whether a given table exists
1833 *
1834 * @param string $table
1835 * @param string $fname
1836 * @return bool
1837 */
1838 public function tableExists( $table, $fname = __METHOD__ ) {
1839 $table = $this->tableName( $table );
1840 $old = $this->ignoreErrors( true );
1841 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1842 $this->ignoreErrors( $old );
1843
1844 return (bool)$res;
1845 }
1846
1847 /**
1848 * Determines if a given index is unique
1849 *
1850 * @param string $table
1851 * @param string $index
1852 *
1853 * @return bool
1854 */
1855 public function indexUnique( $table, $index ) {
1856 $indexInfo = $this->indexInfo( $table, $index );
1857
1858 if ( !$indexInfo ) {
1859 return null;
1860 }
1861
1862 return !$indexInfo[0]->Non_unique;
1863 }
1864
1865 /**
1866 * Helper for DatabaseBase::insert().
1867 *
1868 * @param array $options
1869 * @return string
1870 */
1871 protected function makeInsertOptions( $options ) {
1872 return implode( ' ', $options );
1873 }
1874
1875 /**
1876 * INSERT wrapper, inserts an array into a table.
1877 *
1878 * $a may be either:
1879 *
1880 * - A single associative array. The array keys are the field names, and
1881 * the values are the values to insert. The values are treated as data
1882 * and will be quoted appropriately. If NULL is inserted, this will be
1883 * converted to a database NULL.
1884 * - An array with numeric keys, holding a list of associative arrays.
1885 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1886 * each subarray must be identical to each other, and in the same order.
1887 *
1888 * $options is an array of options, with boolean options encoded as values
1889 * with numeric keys, in the same style as $options in
1890 * DatabaseBase::select(). Supported options are:
1891 *
1892 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1893 * any rows which cause duplicate key errors are not inserted. It's
1894 * possible to determine how many rows were successfully inserted using
1895 * DatabaseBase::affectedRows().
1896 *
1897 * @param string $table Table name. This will be passed through
1898 * DatabaseBase::tableName().
1899 * @param array $a Array of rows to insert
1900 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1901 * @param array $options Array of options
1902 *
1903 * @throws DBQueryError Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1904 * returns success.
1905 *
1906 * @return bool
1907 */
1908 public function insert( $table, $a, $fname = __METHOD__, $options = array() ) {
1909 # No rows to insert, easy just return now
1910 if ( !count( $a ) ) {
1911 return true;
1912 }
1913
1914 $table = $this->tableName( $table );
1915
1916 if ( !is_array( $options ) ) {
1917 $options = array( $options );
1918 }
1919
1920 $fh = null;
1921 if ( isset( $options['fileHandle'] ) ) {
1922 $fh = $options['fileHandle'];
1923 }
1924 $options = $this->makeInsertOptions( $options );
1925
1926 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1927 $multi = true;
1928 $keys = array_keys( $a[0] );
1929 } else {
1930 $multi = false;
1931 $keys = array_keys( $a );
1932 }
1933
1934 $sql = 'INSERT ' . $options .
1935 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1936
1937 if ( $multi ) {
1938 $first = true;
1939 foreach ( $a as $row ) {
1940 if ( $first ) {
1941 $first = false;
1942 } else {
1943 $sql .= ',';
1944 }
1945 $sql .= '(' . $this->makeList( $row ) . ')';
1946 }
1947 } else {
1948 $sql .= '(' . $this->makeList( $a ) . ')';
1949 }
1950
1951 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1952 return false;
1953 } elseif ( $fh !== null ) {
1954 return true;
1955 }
1956
1957 return (bool)$this->query( $sql, $fname );
1958 }
1959
1960 /**
1961 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1962 *
1963 * @param array $options
1964 * @return array
1965 */
1966 protected function makeUpdateOptionsArray( $options ) {
1967 if ( !is_array( $options ) ) {
1968 $options = array( $options );
1969 }
1970
1971 $opts = array();
1972
1973 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1974 $opts[] = $this->lowPriorityOption();
1975 }
1976
1977 if ( in_array( 'IGNORE', $options ) ) {
1978 $opts[] = 'IGNORE';
1979 }
1980
1981 return $opts;
1982 }
1983
1984 /**
1985 * Make UPDATE options for the DatabaseBase::update function
1986 *
1987 * @param array $options The options passed to DatabaseBase::update
1988 * @return string
1989 */
1990 protected function makeUpdateOptions( $options ) {
1991 $opts = $this->makeUpdateOptionsArray( $options );
1992
1993 return implode( ' ', $opts );
1994 }
1995
1996 /**
1997 * UPDATE wrapper. Takes a condition array and a SET array.
1998 *
1999 * @param string $table Name of the table to UPDATE. This will be passed through
2000 * DatabaseBase::tableName().
2001 * @param array $values An array of values to SET. For each array element,
2002 * the key gives the field name, and the value gives the data to set
2003 * that field to. The data will be quoted by DatabaseBase::addQuotes().
2004 * @param array $conds An array of conditions (WHERE). See
2005 * DatabaseBase::select() for the details of the format of condition
2006 * arrays. Use '*' to update all rows.
2007 * @param string $fname The function name of the caller (from __METHOD__),
2008 * for logging and profiling.
2009 * @param array $options An array of UPDATE options, can be:
2010 * - IGNORE: Ignore unique key conflicts
2011 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
2012 * @return bool
2013 */
2014 function update( $table, $values, $conds, $fname = __METHOD__, $options = array() ) {
2015 $table = $this->tableName( $table );
2016 $opts = $this->makeUpdateOptions( $options );
2017 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
2018
2019 if ( $conds !== array() && $conds !== '*' ) {
2020 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
2021 }
2022
2023 return $this->query( $sql, $fname );
2024 }
2025
2026 /**
2027 * Makes an encoded list of strings from an array
2028 *
2029 * @param array $a Containing the data
2030 * @param int $mode Constant
2031 * - LIST_COMMA: Comma separated, no field names
2032 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2033 * documentation for $conds in DatabaseBase::select().
2034 * - LIST_OR: ORed WHERE clause (without the WHERE)
2035 * - LIST_SET: Comma separated with field names, like a SET clause
2036 * - LIST_NAMES: Comma separated field names
2037 * @throws MWException|DBUnexpectedError
2038 * @return string
2039 */
2040 public function makeList( $a, $mode = LIST_COMMA ) {
2041 if ( !is_array( $a ) ) {
2042 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2043 }
2044
2045 $first = true;
2046 $list = '';
2047
2048 foreach ( $a as $field => $value ) {
2049 if ( !$first ) {
2050 if ( $mode == LIST_AND ) {
2051 $list .= ' AND ';
2052 } elseif ( $mode == LIST_OR ) {
2053 $list .= ' OR ';
2054 } else {
2055 $list .= ',';
2056 }
2057 } else {
2058 $first = false;
2059 }
2060
2061 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
2062 $list .= "($value)";
2063 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
2064 $list .= "$value";
2065 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
2066 // Remove null from array to be handled separately if found
2067 $includeNull = false;
2068 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2069 $includeNull = true;
2070 unset( $value[$nullKey] );
2071 }
2072 if ( count( $value ) == 0 && !$includeNull ) {
2073 throw new MWException( __METHOD__ . ": empty input for field $field" );
2074 } elseif ( count( $value ) == 0 ) {
2075 // only check if $field is null
2076 $list .= "$field IS NULL";
2077 } else {
2078 // IN clause contains at least one valid element
2079 if ( $includeNull ) {
2080 // Group subconditions to ensure correct precedence
2081 $list .= '(';
2082 }
2083 if ( count( $value ) == 1 ) {
2084 // Special-case single values, as IN isn't terribly efficient
2085 // Don't necessarily assume the single key is 0; we don't
2086 // enforce linear numeric ordering on other arrays here.
2087 $value = array_values( $value );
2088 $list .= $field . " = " . $this->addQuotes( $value[0] );
2089 } else {
2090 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2091 }
2092 // if null present in array, append IS NULL
2093 if ( $includeNull ) {
2094 $list .= " OR $field IS NULL)";
2095 }
2096 }
2097 } elseif ( $value === null ) {
2098 if ( $mode == LIST_AND || $mode == LIST_OR ) {
2099 $list .= "$field IS ";
2100 } elseif ( $mode == LIST_SET ) {
2101 $list .= "$field = ";
2102 }
2103 $list .= 'NULL';
2104 } else {
2105 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
2106 $list .= "$field = ";
2107 }
2108 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
2109 }
2110 }
2111
2112 return $list;
2113 }
2114
2115 /**
2116 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2117 * The keys on each level may be either integers or strings.
2118 *
2119 * @param array $data Organized as 2-d
2120 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2121 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2122 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2123 * @return string|bool SQL fragment, or false if no items in array
2124 */
2125 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2126 $conds = array();
2127
2128 foreach ( $data as $base => $sub ) {
2129 if ( count( $sub ) ) {
2130 $conds[] = $this->makeList(
2131 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2132 LIST_AND );
2133 }
2134 }
2135
2136 if ( $conds ) {
2137 return $this->makeList( $conds, LIST_OR );
2138 } else {
2139 // Nothing to search for...
2140 return false;
2141 }
2142 }
2143
2144 /**
2145 * Return aggregated value alias
2146 *
2147 * @param array $valuedata
2148 * @param string $valuename
2149 *
2150 * @return string
2151 */
2152 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2153 return $valuename;
2154 }
2155
2156 /**
2157 * @param string $field
2158 * @return string
2159 */
2160 public function bitNot( $field ) {
2161 return "(~$field)";
2162 }
2163
2164 /**
2165 * @param string $fieldLeft
2166 * @param string $fieldRight
2167 * @return string
2168 */
2169 public function bitAnd( $fieldLeft, $fieldRight ) {
2170 return "($fieldLeft & $fieldRight)";
2171 }
2172
2173 /**
2174 * @param string $fieldLeft
2175 * @param string $fieldRight
2176 * @return string
2177 */
2178 public function bitOr( $fieldLeft, $fieldRight ) {
2179 return "($fieldLeft | $fieldRight)";
2180 }
2181
2182 /**
2183 * Build a concatenation list to feed into a SQL query
2184 * @param array $stringList List of raw SQL expressions; caller is
2185 * responsible for any quoting
2186 * @return string
2187 */
2188 public function buildConcat( $stringList ) {
2189 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2190 }
2191
2192 /**
2193 * Build a GROUP_CONCAT or equivalent statement for a query.
2194 *
2195 * This is useful for combining a field for several rows into a single string.
2196 * NULL values will not appear in the output, duplicated values will appear,
2197 * and the resulting delimiter-separated values have no defined sort order.
2198 * Code using the results may need to use the PHP unique() or sort() methods.
2199 *
2200 * @param string $delim Glue to bind the results together
2201 * @param string|array $table Table name
2202 * @param string $field Field name
2203 * @param string|array $conds Conditions
2204 * @param string|array $join_conds Join conditions
2205 * @return string SQL text
2206 * @since 1.23
2207 */
2208 public function buildGroupConcatField(
2209 $delim, $table, $field, $conds = '', $join_conds = array()
2210 ) {
2211 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2212
2213 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2214 }
2215
2216 /**
2217 * Change the current database
2218 *
2219 * @todo Explain what exactly will fail if this is not overridden.
2220 *
2221 * @param string $db
2222 *
2223 * @return bool Success or failure
2224 */
2225 public function selectDB( $db ) {
2226 # Stub. Shouldn't cause serious problems if it's not overridden, but
2227 # if your database engine supports a concept similar to MySQL's
2228 # databases you may as well.
2229 $this->mDBname = $db;
2230
2231 return true;
2232 }
2233
2234 /**
2235 * Get the current DB name
2236 * @return string
2237 */
2238 public function getDBname() {
2239 return $this->mDBname;
2240 }
2241
2242 /**
2243 * Get the server hostname or IP address
2244 * @return string
2245 */
2246 public function getServer() {
2247 return $this->mServer;
2248 }
2249
2250 /**
2251 * Format a table name ready for use in constructing an SQL query
2252 *
2253 * This does two important things: it quotes the table names to clean them up,
2254 * and it adds a table prefix if only given a table name with no quotes.
2255 *
2256 * All functions of this object which require a table name call this function
2257 * themselves. Pass the canonical name to such functions. This is only needed
2258 * when calling query() directly.
2259 *
2260 * @param string $name Database table name
2261 * @param string $format One of:
2262 * quoted - Automatically pass the table name through addIdentifierQuotes()
2263 * so that it can be used in a query.
2264 * raw - Do not add identifier quotes to the table name
2265 * @return string Full database name
2266 */
2267 public function tableName( $name, $format = 'quoted' ) {
2268 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2269 # Skip the entire process when we have a string quoted on both ends.
2270 # Note that we check the end so that we will still quote any use of
2271 # use of `database`.table. But won't break things if someone wants
2272 # to query a database table with a dot in the name.
2273 if ( $this->isQuotedIdentifier( $name ) ) {
2274 return $name;
2275 }
2276
2277 # Lets test for any bits of text that should never show up in a table
2278 # name. Basically anything like JOIN or ON which are actually part of
2279 # SQL queries, but may end up inside of the table value to combine
2280 # sql. Such as how the API is doing.
2281 # Note that we use a whitespace test rather than a \b test to avoid
2282 # any remote case where a word like on may be inside of a table name
2283 # surrounded by symbols which may be considered word breaks.
2284 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2285 return $name;
2286 }
2287
2288 # Split database and table into proper variables.
2289 # We reverse the explode so that database.table and table both output
2290 # the correct table.
2291 $dbDetails = explode( '.', $name, 3 );
2292 if ( count( $dbDetails ) == 3 ) {
2293 list( $database, $schema, $table ) = $dbDetails;
2294 # We don't want any prefix added in this case
2295 $prefix = '';
2296 } elseif ( count( $dbDetails ) == 2 ) {
2297 list( $database, $table ) = $dbDetails;
2298 # We don't want any prefix added in this case
2299 # In dbs that support it, $database may actually be the schema
2300 # but that doesn't affect any of the functionality here
2301 $prefix = '';
2302 $schema = null;
2303 } else {
2304 list( $table ) = $dbDetails;
2305 if ( $wgSharedDB !== null # We have a shared database
2306 && $this->mForeign == false # We're not working on a foreign database
2307 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2308 && in_array( $table, $wgSharedTables ) # A shared table is selected
2309 ) {
2310 $database = $wgSharedDB;
2311 $schema = $wgSharedSchema === null ? $this->mSchema : $wgSharedSchema;
2312 $prefix = $wgSharedPrefix === null ? $this->mTablePrefix : $wgSharedPrefix;
2313 } else {
2314 $database = null;
2315 $schema = $this->mSchema; # Default schema
2316 $prefix = $this->mTablePrefix; # Default prefix
2317 }
2318 }
2319
2320 # Quote $table and apply the prefix if not quoted.
2321 # $tableName might be empty if this is called from Database::replaceVars()
2322 $tableName = "{$prefix}{$table}";
2323 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2324 $tableName = $this->addIdentifierQuotes( $tableName );
2325 }
2326
2327 # Quote $schema and merge it with the table name if needed
2328 if ( strlen( $schema ) ) {
2329 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2330 $schema = $this->addIdentifierQuotes( $schema );
2331 }
2332 $tableName = $schema . '.' . $tableName;
2333 }
2334
2335 # Quote $database and merge it with the table name if needed
2336 if ( $database !== null ) {
2337 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2338 $database = $this->addIdentifierQuotes( $database );
2339 }
2340 $tableName = $database . '.' . $tableName;
2341 }
2342
2343 return $tableName;
2344 }
2345
2346 /**
2347 * Fetch a number of table names into an array
2348 * This is handy when you need to construct SQL for joins
2349 *
2350 * Example:
2351 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2352 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2353 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2354 *
2355 * @return array
2356 */
2357 public function tableNames() {
2358 $inArray = func_get_args();
2359 $retVal = array();
2360
2361 foreach ( $inArray as $name ) {
2362 $retVal[$name] = $this->tableName( $name );
2363 }
2364
2365 return $retVal;
2366 }
2367
2368 /**
2369 * Fetch a number of table names into an zero-indexed numerical array
2370 * This is handy when you need to construct SQL for joins
2371 *
2372 * Example:
2373 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2374 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2375 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2376 *
2377 * @return array
2378 */
2379 public function tableNamesN() {
2380 $inArray = func_get_args();
2381 $retVal = array();
2382
2383 foreach ( $inArray as $name ) {
2384 $retVal[] = $this->tableName( $name );
2385 }
2386
2387 return $retVal;
2388 }
2389
2390 /**
2391 * Get an aliased table name
2392 * e.g. tableName AS newTableName
2393 *
2394 * @param string $name Table name, see tableName()
2395 * @param string|bool $alias Alias (optional)
2396 * @return string SQL name for aliased table. Will not alias a table to its own name
2397 */
2398 public function tableNameWithAlias( $name, $alias = false ) {
2399 if ( !$alias || $alias == $name ) {
2400 return $this->tableName( $name );
2401 } else {
2402 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2403 }
2404 }
2405
2406 /**
2407 * Gets an array of aliased table names
2408 *
2409 * @param array $tables Array( [alias] => table )
2410 * @return string[] See tableNameWithAlias()
2411 */
2412 public function tableNamesWithAlias( $tables ) {
2413 $retval = array();
2414 foreach ( $tables as $alias => $table ) {
2415 if ( is_numeric( $alias ) ) {
2416 $alias = $table;
2417 }
2418 $retval[] = $this->tableNameWithAlias( $table, $alias );
2419 }
2420
2421 return $retval;
2422 }
2423
2424 /**
2425 * Get an aliased field name
2426 * e.g. fieldName AS newFieldName
2427 *
2428 * @param string $name Field name
2429 * @param string|bool $alias Alias (optional)
2430 * @return string SQL name for aliased field. Will not alias a field to its own name
2431 */
2432 public function fieldNameWithAlias( $name, $alias = false ) {
2433 if ( !$alias || (string)$alias === (string)$name ) {
2434 return $name;
2435 } else {
2436 return $name . ' AS ' . $alias; // PostgreSQL needs AS
2437 }
2438 }
2439
2440 /**
2441 * Gets an array of aliased field names
2442 *
2443 * @param array $fields Array( [alias] => field )
2444 * @return string[] See fieldNameWithAlias()
2445 */
2446 public function fieldNamesWithAlias( $fields ) {
2447 $retval = array();
2448 foreach ( $fields as $alias => $field ) {
2449 if ( is_numeric( $alias ) ) {
2450 $alias = $field;
2451 }
2452 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2453 }
2454
2455 return $retval;
2456 }
2457
2458 /**
2459 * Get the aliased table name clause for a FROM clause
2460 * which might have a JOIN and/or USE INDEX clause
2461 *
2462 * @param array $tables ( [alias] => table )
2463 * @param array $use_index Same as for select()
2464 * @param array $join_conds Same as for select()
2465 * @return string
2466 */
2467 protected function tableNamesWithUseIndexOrJOIN(
2468 $tables, $use_index = array(), $join_conds = array()
2469 ) {
2470 $ret = array();
2471 $retJOIN = array();
2472 $use_index = (array)$use_index;
2473 $join_conds = (array)$join_conds;
2474
2475 foreach ( $tables as $alias => $table ) {
2476 if ( !is_string( $alias ) ) {
2477 // No alias? Set it equal to the table name
2478 $alias = $table;
2479 }
2480 // Is there a JOIN clause for this table?
2481 if ( isset( $join_conds[$alias] ) ) {
2482 list( $joinType, $conds ) = $join_conds[$alias];
2483 $tableClause = $joinType;
2484 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2485 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2486 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2487 if ( $use != '' ) {
2488 $tableClause .= ' ' . $use;
2489 }
2490 }
2491 $on = $this->makeList( (array)$conds, LIST_AND );
2492 if ( $on != '' ) {
2493 $tableClause .= ' ON (' . $on . ')';
2494 }
2495
2496 $retJOIN[] = $tableClause;
2497 } elseif ( isset( $use_index[$alias] ) ) {
2498 // Is there an INDEX clause for this table?
2499 $tableClause = $this->tableNameWithAlias( $table, $alias );
2500 $tableClause .= ' ' . $this->useIndexClause(
2501 implode( ',', (array)$use_index[$alias] )
2502 );
2503
2504 $ret[] = $tableClause;
2505 } else {
2506 $tableClause = $this->tableNameWithAlias( $table, $alias );
2507
2508 $ret[] = $tableClause;
2509 }
2510 }
2511
2512 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2513 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
2514 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
2515
2516 // Compile our final table clause
2517 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2518 }
2519
2520 /**
2521 * Get the name of an index in a given table.
2522 *
2523 * @protected Don't use outside of DatabaseBase and childs
2524 * @param string $index
2525 * @return string
2526 */
2527 public function indexName( $index ) {
2528 // @FIXME: Make this protected once we move away from PHP 5.3
2529 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
2530
2531 // Backwards-compatibility hack
2532 $renamed = array(
2533 'ar_usertext_timestamp' => 'usertext_timestamp',
2534 'un_user_id' => 'user_id',
2535 'un_user_ip' => 'user_ip',
2536 );
2537
2538 if ( isset( $renamed[$index] ) ) {
2539 return $renamed[$index];
2540 } else {
2541 return $index;
2542 }
2543 }
2544
2545 /**
2546 * Adds quotes and backslashes.
2547 *
2548 * @param string|Blob $s
2549 * @return string
2550 */
2551 public function addQuotes( $s ) {
2552 if ( $s instanceof Blob ) {
2553 $s = $s->fetch();
2554 }
2555 if ( $s === null ) {
2556 return 'NULL';
2557 } else {
2558 # This will also quote numeric values. This should be harmless,
2559 # and protects against weird problems that occur when they really
2560 # _are_ strings such as article titles and string->number->string
2561 # conversion is not 1:1.
2562 return "'" . $this->strencode( $s ) . "'";
2563 }
2564 }
2565
2566 /**
2567 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2568 * MySQL uses `backticks` while basically everything else uses double quotes.
2569 * Since MySQL is the odd one out here the double quotes are our generic
2570 * and we implement backticks in DatabaseMysql.
2571 *
2572 * @param string $s
2573 * @return string
2574 */
2575 public function addIdentifierQuotes( $s ) {
2576 return '"' . str_replace( '"', '""', $s ) . '"';
2577 }
2578
2579 /**
2580 * Returns if the given identifier looks quoted or not according to
2581 * the database convention for quoting identifiers .
2582 *
2583 * @param string $name
2584 * @return bool
2585 */
2586 public function isQuotedIdentifier( $name ) {
2587 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2588 }
2589
2590 /**
2591 * @param string $s
2592 * @return string
2593 */
2594 protected function escapeLikeInternal( $s ) {
2595 return addcslashes( $s, '\%_' );
2596 }
2597
2598 /**
2599 * LIKE statement wrapper, receives a variable-length argument list with
2600 * parts of pattern to match containing either string literals that will be
2601 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2602 * the function could be provided with an array of aforementioned
2603 * parameters.
2604 *
2605 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2606 * a LIKE clause that searches for subpages of 'My page title'.
2607 * Alternatively:
2608 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2609 * $query .= $dbr->buildLike( $pattern );
2610 *
2611 * @since 1.16
2612 * @return string Fully built LIKE statement
2613 */
2614 public function buildLike() {
2615 $params = func_get_args();
2616
2617 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2618 $params = $params[0];
2619 }
2620
2621 $s = '';
2622
2623 foreach ( $params as $value ) {
2624 if ( $value instanceof LikeMatch ) {
2625 $s .= $value->toString();
2626 } else {
2627 $s .= $this->escapeLikeInternal( $value );
2628 }
2629 }
2630
2631 return " LIKE {$this->addQuotes( $s )} ";
2632 }
2633
2634 /**
2635 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2636 *
2637 * @return LikeMatch
2638 */
2639 public function anyChar() {
2640 return new LikeMatch( '_' );
2641 }
2642
2643 /**
2644 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2645 *
2646 * @return LikeMatch
2647 */
2648 public function anyString() {
2649 return new LikeMatch( '%' );
2650 }
2651
2652 /**
2653 * Returns an appropriately quoted sequence value for inserting a new row.
2654 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2655 * subclass will return an integer, and save the value for insertId()
2656 *
2657 * Any implementation of this function should *not* involve reusing
2658 * sequence numbers created for rolled-back transactions.
2659 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2660 * @param string $seqName
2661 * @return null|int
2662 */
2663 public function nextSequenceValue( $seqName ) {
2664 return null;
2665 }
2666
2667 /**
2668 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2669 * is only needed because a) MySQL must be as efficient as possible due to
2670 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2671 * which index to pick. Anyway, other databases might have different
2672 * indexes on a given table. So don't bother overriding this unless you're
2673 * MySQL.
2674 * @param string $index
2675 * @return string
2676 */
2677 public function useIndexClause( $index ) {
2678 return '';
2679 }
2680
2681 /**
2682 * REPLACE query wrapper.
2683 *
2684 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2685 * except that when there is a duplicate key error, the old row is deleted
2686 * and the new row is inserted in its place.
2687 *
2688 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2689 * perform the delete, we need to know what the unique indexes are so that
2690 * we know how to find the conflicting rows.
2691 *
2692 * It may be more efficient to leave off unique indexes which are unlikely
2693 * to collide. However if you do this, you run the risk of encountering
2694 * errors which wouldn't have occurred in MySQL.
2695 *
2696 * @param string $table The table to replace the row(s) in.
2697 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2698 * a field name or an array of field names
2699 * @param array $rows Can be either a single row to insert, or multiple rows,
2700 * in the same format as for DatabaseBase::insert()
2701 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2702 */
2703 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2704 $quotedTable = $this->tableName( $table );
2705
2706 if ( count( $rows ) == 0 ) {
2707 return;
2708 }
2709
2710 # Single row case
2711 if ( !is_array( reset( $rows ) ) ) {
2712 $rows = array( $rows );
2713 }
2714
2715 // @FXIME: this is not atomic, but a trx would break affectedRows()
2716 foreach ( $rows as $row ) {
2717 # Delete rows which collide
2718 if ( $uniqueIndexes ) {
2719 $sql = "DELETE FROM $quotedTable WHERE ";
2720 $first = true;
2721 foreach ( $uniqueIndexes as $index ) {
2722 if ( $first ) {
2723 $first = false;
2724 $sql .= '( ';
2725 } else {
2726 $sql .= ' ) OR ( ';
2727 }
2728 if ( is_array( $index ) ) {
2729 $first2 = true;
2730 foreach ( $index as $col ) {
2731 if ( $first2 ) {
2732 $first2 = false;
2733 } else {
2734 $sql .= ' AND ';
2735 }
2736 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2737 }
2738 } else {
2739 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2740 }
2741 }
2742 $sql .= ' )';
2743 $this->query( $sql, $fname );
2744 }
2745
2746 # Now insert the row
2747 $this->insert( $table, $row, $fname );
2748 }
2749 }
2750
2751 /**
2752 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2753 * statement.
2754 *
2755 * @param string $table Table name
2756 * @param array|string $rows Row(s) to insert
2757 * @param string $fname Caller function name
2758 *
2759 * @return ResultWrapper
2760 */
2761 protected function nativeReplace( $table, $rows, $fname ) {
2762 $table = $this->tableName( $table );
2763
2764 # Single row case
2765 if ( !is_array( reset( $rows ) ) ) {
2766 $rows = array( $rows );
2767 }
2768
2769 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2770 $first = true;
2771
2772 foreach ( $rows as $row ) {
2773 if ( $first ) {
2774 $first = false;
2775 } else {
2776 $sql .= ',';
2777 }
2778
2779 $sql .= '(' . $this->makeList( $row ) . ')';
2780 }
2781
2782 return $this->query( $sql, $fname );
2783 }
2784
2785 /**
2786 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2787 *
2788 * This updates any conflicting rows (according to the unique indexes) using
2789 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2790 *
2791 * $rows may be either:
2792 * - A single associative array. The array keys are the field names, and
2793 * the values are the values to insert. The values are treated as data
2794 * and will be quoted appropriately. If NULL is inserted, this will be
2795 * converted to a database NULL.
2796 * - An array with numeric keys, holding a list of associative arrays.
2797 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2798 * each subarray must be identical to each other, and in the same order.
2799 *
2800 * It may be more efficient to leave off unique indexes which are unlikely
2801 * to collide. However if you do this, you run the risk of encountering
2802 * errors which wouldn't have occurred in MySQL.
2803 *
2804 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2805 * returns success.
2806 *
2807 * @since 1.22
2808 *
2809 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2810 * @param array $rows A single row or list of rows to insert
2811 * @param array $uniqueIndexes List of single field names or field name tuples
2812 * @param array $set An array of values to SET. For each array element, the
2813 * key gives the field name, and the value gives the data to set that
2814 * field to. The data will be quoted by DatabaseBase::addQuotes().
2815 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2816 * @throws Exception
2817 * @return bool
2818 */
2819 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2820 $fname = __METHOD__
2821 ) {
2822 if ( !count( $rows ) ) {
2823 return true; // nothing to do
2824 }
2825
2826 if ( !is_array( reset( $rows ) ) ) {
2827 $rows = array( $rows );
2828 }
2829
2830 if ( count( $uniqueIndexes ) ) {
2831 $clauses = array(); // list WHERE clauses that each identify a single row
2832 foreach ( $rows as $row ) {
2833 foreach ( $uniqueIndexes as $index ) {
2834 $index = is_array( $index ) ? $index : array( $index ); // columns
2835 $rowKey = array(); // unique key to this row
2836 foreach ( $index as $column ) {
2837 $rowKey[$column] = $row[$column];
2838 }
2839 $clauses[] = $this->makeList( $rowKey, LIST_AND );
2840 }
2841 }
2842 $where = array( $this->makeList( $clauses, LIST_OR ) );
2843 } else {
2844 $where = false;
2845 }
2846
2847 $useTrx = !$this->mTrxLevel;
2848 if ( $useTrx ) {
2849 $this->begin( $fname );
2850 }
2851 try {
2852 # Update any existing conflicting row(s)
2853 if ( $where !== false ) {
2854 $ok = $this->update( $table, $set, $where, $fname );
2855 } else {
2856 $ok = true;
2857 }
2858 # Now insert any non-conflicting row(s)
2859 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2860 } catch ( Exception $e ) {
2861 if ( $useTrx ) {
2862 $this->rollback( $fname );
2863 }
2864 throw $e;
2865 }
2866 if ( $useTrx ) {
2867 $this->commit( $fname );
2868 }
2869
2870 return $ok;
2871 }
2872
2873 /**
2874 * DELETE where the condition is a join.
2875 *
2876 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2877 * we use sub-selects
2878 *
2879 * For safety, an empty $conds will not delete everything. If you want to
2880 * delete all rows where the join condition matches, set $conds='*'.
2881 *
2882 * DO NOT put the join condition in $conds.
2883 *
2884 * @param string $delTable The table to delete from.
2885 * @param string $joinTable The other table.
2886 * @param string $delVar The variable to join on, in the first table.
2887 * @param string $joinVar The variable to join on, in the second table.
2888 * @param array $conds Condition array of field names mapped to variables,
2889 * ANDed together in the WHERE clause
2890 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2891 * @throws DBUnexpectedError
2892 */
2893 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2894 $fname = __METHOD__
2895 ) {
2896 if ( !$conds ) {
2897 throw new DBUnexpectedError( $this,
2898 'DatabaseBase::deleteJoin() called with empty $conds' );
2899 }
2900
2901 $delTable = $this->tableName( $delTable );
2902 $joinTable = $this->tableName( $joinTable );
2903 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2904 if ( $conds != '*' ) {
2905 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
2906 }
2907 $sql .= ')';
2908
2909 $this->query( $sql, $fname );
2910 }
2911
2912 /**
2913 * Returns the size of a text field, or -1 for "unlimited"
2914 *
2915 * @param string $table
2916 * @param string $field
2917 * @return int
2918 */
2919 public function textFieldSize( $table, $field ) {
2920 $table = $this->tableName( $table );
2921 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2922 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2923 $row = $this->fetchObject( $res );
2924
2925 $m = array();
2926
2927 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2928 $size = $m[1];
2929 } else {
2930 $size = -1;
2931 }
2932
2933 return $size;
2934 }
2935
2936 /**
2937 * A string to insert into queries to show that they're low-priority, like
2938 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2939 * string and nothing bad should happen.
2940 *
2941 * @return string Returns the text of the low priority option if it is
2942 * supported, or a blank string otherwise
2943 */
2944 public function lowPriorityOption() {
2945 return '';
2946 }
2947
2948 /**
2949 * DELETE query wrapper.
2950 *
2951 * @param array $table Table name
2952 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
2953 * for the format. Use $conds == "*" to delete all rows
2954 * @param string $fname Name of the calling function
2955 * @throws DBUnexpectedError
2956 * @return bool|ResultWrapper
2957 */
2958 public function delete( $table, $conds, $fname = __METHOD__ ) {
2959 if ( !$conds ) {
2960 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2961 }
2962
2963 $table = $this->tableName( $table );
2964 $sql = "DELETE FROM $table";
2965
2966 if ( $conds != '*' ) {
2967 if ( is_array( $conds ) ) {
2968 $conds = $this->makeList( $conds, LIST_AND );
2969 }
2970 $sql .= ' WHERE ' . $conds;
2971 }
2972
2973 return $this->query( $sql, $fname );
2974 }
2975
2976 /**
2977 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2978 * into another table.
2979 *
2980 * @param string $destTable The table name to insert into
2981 * @param string|array $srcTable May be either a table name, or an array of table names
2982 * to include in a join.
2983 *
2984 * @param array $varMap Must be an associative array of the form
2985 * array( 'dest1' => 'source1', ...). Source items may be literals
2986 * rather than field names, but strings should be quoted with
2987 * DatabaseBase::addQuotes()
2988 *
2989 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
2990 * the details of the format of condition arrays. May be "*" to copy the
2991 * whole table.
2992 *
2993 * @param string $fname The function name of the caller, from __METHOD__
2994 *
2995 * @param array $insertOptions Options for the INSERT part of the query, see
2996 * DatabaseBase::insert() for details.
2997 * @param array $selectOptions Options for the SELECT part of the query, see
2998 * DatabaseBase::select() for details.
2999 *
3000 * @return ResultWrapper
3001 */
3002 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
3003 $fname = __METHOD__,
3004 $insertOptions = array(), $selectOptions = array()
3005 ) {
3006 $destTable = $this->tableName( $destTable );
3007
3008 if ( !is_array( $insertOptions ) ) {
3009 $insertOptions = array( $insertOptions );
3010 }
3011
3012 $insertOptions = $this->makeInsertOptions( $insertOptions );
3013
3014 if ( !is_array( $selectOptions ) ) {
3015 $selectOptions = array( $selectOptions );
3016 }
3017
3018 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
3019
3020 if ( is_array( $srcTable ) ) {
3021 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
3022 } else {
3023 $srcTable = $this->tableName( $srcTable );
3024 }
3025
3026 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
3027 " SELECT $startOpts " . implode( ',', $varMap ) .
3028 " FROM $srcTable $useIndex ";
3029
3030 if ( $conds != '*' ) {
3031 if ( is_array( $conds ) ) {
3032 $conds = $this->makeList( $conds, LIST_AND );
3033 }
3034 $sql .= " WHERE $conds";
3035 }
3036
3037 $sql .= " $tailOpts";
3038
3039 return $this->query( $sql, $fname );
3040 }
3041
3042 /**
3043 * Construct a LIMIT query with optional offset. This is used for query
3044 * pages. The SQL should be adjusted so that only the first $limit rows
3045 * are returned. If $offset is provided as well, then the first $offset
3046 * rows should be discarded, and the next $limit rows should be returned.
3047 * If the result of the query is not ordered, then the rows to be returned
3048 * are theoretically arbitrary.
3049 *
3050 * $sql is expected to be a SELECT, if that makes a difference.
3051 *
3052 * The version provided by default works in MySQL and SQLite. It will very
3053 * likely need to be overridden for most other DBMSes.
3054 *
3055 * @param string $sql SQL query we will append the limit too
3056 * @param int $limit The SQL limit
3057 * @param int|bool $offset The SQL offset (default false)
3058 * @throws DBUnexpectedError
3059 * @return string
3060 */
3061 public function limitResult( $sql, $limit, $offset = false ) {
3062 if ( !is_numeric( $limit ) ) {
3063 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3064 }
3065
3066 return "$sql LIMIT "
3067 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
3068 . "{$limit} ";
3069 }
3070
3071 /**
3072 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3073 * within the UNION construct.
3074 * @return bool
3075 */
3076 public function unionSupportsOrderAndLimit() {
3077 return true; // True for almost every DB supported
3078 }
3079
3080 /**
3081 * Construct a UNION query
3082 * This is used for providing overload point for other DB abstractions
3083 * not compatible with the MySQL syntax.
3084 * @param array $sqls SQL statements to combine
3085 * @param bool $all Use UNION ALL
3086 * @return string SQL fragment
3087 */
3088 public function unionQueries( $sqls, $all ) {
3089 $glue = $all ? ') UNION ALL (' : ') UNION (';
3090
3091 return '(' . implode( $glue, $sqls ) . ')';
3092 }
3093
3094 /**
3095 * Returns an SQL expression for a simple conditional. This doesn't need
3096 * to be overridden unless CASE isn't supported in your DBMS.
3097 *
3098 * @param string|array $cond SQL expression which will result in a boolean value
3099 * @param string $trueVal SQL expression to return if true
3100 * @param string $falseVal SQL expression to return if false
3101 * @return string SQL fragment
3102 */
3103 public function conditional( $cond, $trueVal, $falseVal ) {
3104 if ( is_array( $cond ) ) {
3105 $cond = $this->makeList( $cond, LIST_AND );
3106 }
3107
3108 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3109 }
3110
3111 /**
3112 * Returns a comand for str_replace function in SQL query.
3113 * Uses REPLACE() in MySQL
3114 *
3115 * @param string $orig Column to modify
3116 * @param string $old Column to seek
3117 * @param string $new Column to replace with
3118 *
3119 * @return string
3120 */
3121 public function strreplace( $orig, $old, $new ) {
3122 return "REPLACE({$orig}, {$old}, {$new})";
3123 }
3124
3125 /**
3126 * Determines how long the server has been up
3127 * STUB
3128 *
3129 * @return int
3130 */
3131 public function getServerUptime() {
3132 return 0;
3133 }
3134
3135 /**
3136 * Determines if the last failure was due to a deadlock
3137 * STUB
3138 *
3139 * @return bool
3140 */
3141 public function wasDeadlock() {
3142 return false;
3143 }
3144
3145 /**
3146 * Determines if the last failure was due to a lock timeout
3147 * STUB
3148 *
3149 * @return bool
3150 */
3151 public function wasLockTimeout() {
3152 return false;
3153 }
3154
3155 /**
3156 * Determines if the last query error was something that should be dealt
3157 * with by pinging the connection and reissuing the query.
3158 * STUB
3159 *
3160 * @return bool
3161 */
3162 public function wasErrorReissuable() {
3163 return false;
3164 }
3165
3166 /**
3167 * Determines if the last failure was due to the database being read-only.
3168 * STUB
3169 *
3170 * @return bool
3171 */
3172 public function wasReadOnlyError() {
3173 return false;
3174 }
3175
3176 /**
3177 * Determines if the given query error was a connection drop
3178 * STUB
3179 *
3180 * @param integer|string $errno
3181 * @return bool
3182 */
3183 public function wasConnectionError( $errno ) {
3184 return false;
3185 }
3186
3187 /**
3188 * Perform a deadlock-prone transaction.
3189 *
3190 * This function invokes a callback function to perform a set of write
3191 * queries. If a deadlock occurs during the processing, the transaction
3192 * will be rolled back and the callback function will be called again.
3193 *
3194 * Usage:
3195 * $dbw->deadlockLoop( callback, ... );
3196 *
3197 * Extra arguments are passed through to the specified callback function.
3198 *
3199 * Returns whatever the callback function returned on its successful,
3200 * iteration, or false on error, for example if the retry limit was
3201 * reached.
3202 *
3203 * @return mixed
3204 * @throws DBQueryError
3205 */
3206 public function deadlockLoop() {
3207 $args = func_get_args();
3208 $function = array_shift( $args );
3209 $tries = self::DEADLOCK_TRIES;
3210
3211 $this->begin( __METHOD__ );
3212
3213 $retVal = null;
3214 $e = null;
3215 do {
3216 try {
3217 $retVal = call_user_func_array( $function, $args );
3218 break;
3219 } catch ( DBQueryError $e ) {
3220 if ( $this->wasDeadlock() ) {
3221 // Retry after a randomized delay
3222 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
3223 } else {
3224 // Throw the error back up
3225 throw $e;
3226 }
3227 }
3228 } while ( --$tries > 0 );
3229
3230 if ( $tries <= 0 ) {
3231 // Too many deadlocks; give up
3232 $this->rollback( __METHOD__ );
3233 throw $e;
3234 } else {
3235 $this->commit( __METHOD__ );
3236
3237 return $retVal;
3238 }
3239 }
3240
3241 /**
3242 * Wait for the slave to catch up to a given master position.
3243 *
3244 * @param DBMasterPos $pos
3245 * @param int $timeout The maximum number of seconds to wait for
3246 * synchronisation
3247 * @return int Zero if the slave was past that position already,
3248 * greater than zero if we waited for some period of time, less than
3249 * zero if we timed out.
3250 */
3251 public function masterPosWait( DBMasterPos $pos, $timeout ) {
3252 # Real waits are implemented in the subclass.
3253 return 0;
3254 }
3255
3256 /**
3257 * Get the replication position of this slave
3258 *
3259 * @return DBMasterPos|bool False if this is not a slave.
3260 */
3261 public function getSlavePos() {
3262 # Stub
3263 return false;
3264 }
3265
3266 /**
3267 * Get the position of this master
3268 *
3269 * @return DBMasterPos|bool False if this is not a master
3270 */
3271 public function getMasterPos() {
3272 # Stub
3273 return false;
3274 }
3275
3276 /**
3277 * Run an anonymous function as soon as there is no transaction pending.
3278 * If there is a transaction and it is rolled back, then the callback is cancelled.
3279 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3280 * Callbacks must commit any transactions that they begin.
3281 *
3282 * This is useful for updates to different systems or when separate transactions are needed.
3283 * For example, one might want to enqueue jobs into a system outside the database, but only
3284 * after the database is updated so that the jobs will see the data when they actually run.
3285 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3286 *
3287 * @param callable $callback
3288 * @since 1.20
3289 */
3290 final public function onTransactionIdle( $callback ) {
3291 $this->mTrxIdleCallbacks[] = array( $callback, wfGetCaller() );
3292 if ( !$this->mTrxLevel ) {
3293 $this->runOnTransactionIdleCallbacks();
3294 }
3295 }
3296
3297 /**
3298 * Run an anonymous function before the current transaction commits or now if there is none.
3299 * If there is a transaction and it is rolled back, then the callback is cancelled.
3300 * Callbacks must not start nor commit any transactions.
3301 *
3302 * This is useful for updates that easily cause deadlocks if locks are held too long
3303 * but where atomicity is strongly desired for these updates and some related updates.
3304 *
3305 * @param callable $callback
3306 * @since 1.22
3307 */
3308 final public function onTransactionPreCommitOrIdle( $callback ) {
3309 if ( $this->mTrxLevel ) {
3310 $this->mTrxPreCommitCallbacks[] = array( $callback, wfGetCaller() );
3311 } else {
3312 $this->onTransactionIdle( $callback ); // this will trigger immediately
3313 }
3314 }
3315
3316 /**
3317 * Actually any "on transaction idle" callbacks.
3318 *
3319 * @since 1.20
3320 */
3321 protected function runOnTransactionIdleCallbacks() {
3322 $autoTrx = $this->getFlag( DBO_TRX ); // automatic begin() enabled?
3323
3324 $e = $ePrior = null; // last exception
3325 do { // callbacks may add callbacks :)
3326 $callbacks = $this->mTrxIdleCallbacks;
3327 $this->mTrxIdleCallbacks = array(); // recursion guard
3328 foreach ( $callbacks as $callback ) {
3329 try {
3330 list( $phpCallback ) = $callback;
3331 $this->clearFlag( DBO_TRX ); // make each query its own transaction
3332 call_user_func( $phpCallback );
3333 if ( $autoTrx ) {
3334 $this->setFlag( DBO_TRX ); // restore automatic begin()
3335 } else {
3336 $this->clearFlag( DBO_TRX ); // restore auto-commit
3337 }
3338 } catch ( Exception $e ) {
3339 if ( $ePrior ) {
3340 MWExceptionHandler::logException( $ePrior );
3341 }
3342 $ePrior = $e;
3343 // Some callbacks may use startAtomic/endAtomic, so make sure
3344 // their transactions are ended so other callbacks don't fail
3345 if ( $this->trxLevel() ) {
3346 $this->rollback( __METHOD__ );
3347 }
3348 }
3349 }
3350 } while ( count( $this->mTrxIdleCallbacks ) );
3351
3352 if ( $e instanceof Exception ) {
3353 throw $e; // re-throw any last exception
3354 }
3355 }
3356
3357 /**
3358 * Actually any "on transaction pre-commit" callbacks.
3359 *
3360 * @since 1.22
3361 */
3362 protected function runOnTransactionPreCommitCallbacks() {
3363 $e = $ePrior = null; // last exception
3364 do { // callbacks may add callbacks :)
3365 $callbacks = $this->mTrxPreCommitCallbacks;
3366 $this->mTrxPreCommitCallbacks = array(); // recursion guard
3367 foreach ( $callbacks as $callback ) {
3368 try {
3369 list( $phpCallback ) = $callback;
3370 call_user_func( $phpCallback );
3371 } catch ( Exception $e ) {
3372 if ( $ePrior ) {
3373 MWExceptionHandler::logException( $ePrior );
3374 }
3375 $ePrior = $e;
3376 }
3377 }
3378 } while ( count( $this->mTrxPreCommitCallbacks ) );
3379
3380 if ( $e instanceof Exception ) {
3381 throw $e; // re-throw any last exception
3382 }
3383 }
3384
3385 /**
3386 * Begin an atomic section of statements
3387 *
3388 * If a transaction has been started already, just keep track of the given
3389 * section name to make sure the transaction is not committed pre-maturely.
3390 * This function can be used in layers (with sub-sections), so use a stack
3391 * to keep track of the different atomic sections. If there is no transaction,
3392 * start one implicitly.
3393 *
3394 * The goal of this function is to create an atomic section of SQL queries
3395 * without having to start a new transaction if it already exists.
3396 *
3397 * Atomic sections are more strict than transactions. With transactions,
3398 * attempting to begin a new transaction when one is already running results
3399 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3400 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3401 * and any database transactions cannot be began or committed until all atomic
3402 * levels are closed. There is no such thing as implicitly opening or closing
3403 * an atomic section.
3404 *
3405 * @since 1.23
3406 * @param string $fname
3407 * @throws DBError
3408 */
3409 final public function startAtomic( $fname = __METHOD__ ) {
3410 if ( !$this->mTrxLevel ) {
3411 $this->begin( $fname );
3412 $this->mTrxAutomatic = true;
3413 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3414 // in all changes being in one transaction to keep requests transactional.
3415 if ( !$this->getFlag( DBO_TRX ) ) {
3416 $this->mTrxAutomaticAtomic = true;
3417 }
3418 }
3419
3420 $this->mTrxAtomicLevels[] = $fname;
3421 }
3422
3423 /**
3424 * Ends an atomic section of SQL statements
3425 *
3426 * Ends the next section of atomic SQL statements and commits the transaction
3427 * if necessary.
3428 *
3429 * @since 1.23
3430 * @see DatabaseBase::startAtomic
3431 * @param string $fname
3432 * @throws DBError
3433 */
3434 final public function endAtomic( $fname = __METHOD__ ) {
3435 if ( !$this->mTrxLevel ) {
3436 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3437 }
3438 if ( !$this->mTrxAtomicLevels ||
3439 array_pop( $this->mTrxAtomicLevels ) !== $fname
3440 ) {
3441 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3442 }
3443
3444 if ( !$this->mTrxAtomicLevels && $this->mTrxAutomaticAtomic ) {
3445 $this->commit( $fname, 'flush' );
3446 }
3447 }
3448
3449 /**
3450 * Begin a transaction. If a transaction is already in progress,
3451 * that transaction will be committed before the new transaction is started.
3452 *
3453 * Note that when the DBO_TRX flag is set (which is usually the case for web
3454 * requests, but not for maintenance scripts), any previous database query
3455 * will have started a transaction automatically.
3456 *
3457 * Nesting of transactions is not supported. Attempts to nest transactions
3458 * will cause a warning, unless the current transaction was started
3459 * automatically because of the DBO_TRX flag.
3460 *
3461 * @param string $fname
3462 * @throws DBError
3463 */
3464 final public function begin( $fname = __METHOD__ ) {
3465 if ( $this->mTrxLevel ) { // implicit commit
3466 if ( $this->mTrxAtomicLevels ) {
3467 // If the current transaction was an automatic atomic one, then we definitely have
3468 // a problem. Same if there is any unclosed atomic level.
3469 $levels = implode( ', ', $this->mTrxAtomicLevels );
3470 throw new DBUnexpectedError(
3471 $this,
3472 "Got explicit BEGIN from $fname while atomic section(s) $levels are open."
3473 );
3474 } elseif ( !$this->mTrxAutomatic ) {
3475 // We want to warn about inadvertently nested begin/commit pairs, but not about
3476 // auto-committing implicit transactions that were started by query() via DBO_TRX
3477 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3478 " performing implicit commit!";
3479 wfWarn( $msg );
3480 wfLogDBError( $msg,
3481 $this->getLogContext( array(
3482 'method' => __METHOD__,
3483 'fname' => $fname,
3484 ) )
3485 );
3486 } else {
3487 // if the transaction was automatic and has done write operations
3488 if ( $this->mTrxDoneWrites ) {
3489 wfDebug( "$fname: Automatic transaction with writes in progress" .
3490 " (from {$this->mTrxFname}), performing implicit commit!\n"
3491 );
3492 }
3493 }
3494
3495 $this->runOnTransactionPreCommitCallbacks();
3496 $writeTime = $this->pendingWriteQueryDuration();
3497 $this->doCommit( $fname );
3498 if ( $this->mTrxDoneWrites ) {
3499 $this->mDoneWrites = microtime( true );
3500 $this->getTransactionProfiler()->transactionWritingOut(
3501 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
3502 }
3503 $this->runOnTransactionIdleCallbacks();
3504 }
3505
3506 # Avoid fatals if close() was called
3507 $this->assertOpen();
3508
3509 $this->doBegin( $fname );
3510 $this->mTrxTimestamp = microtime( true );
3511 $this->mTrxFname = $fname;
3512 $this->mTrxDoneWrites = false;
3513 $this->mTrxAutomatic = false;
3514 $this->mTrxAutomaticAtomic = false;
3515 $this->mTrxAtomicLevels = array();
3516 $this->mTrxIdleCallbacks = array();
3517 $this->mTrxPreCommitCallbacks = array();
3518 $this->mTrxShortId = wfRandomString( 12 );
3519 $this->mTrxWriteDuration = 0.0;
3520 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3521 // Get an estimate of the slave lag before then, treating estimate staleness
3522 // as lag itself just to be safe
3523 $status = $this->getApproximateLagStatus();
3524 $this->mTrxSlaveLag = $status['lag'] + ( microtime( true ) - $status['since'] );
3525 }
3526
3527 /**
3528 * Issues the BEGIN command to the database server.
3529 *
3530 * @see DatabaseBase::begin()
3531 * @param string $fname
3532 */
3533 protected function doBegin( $fname ) {
3534 $this->query( 'BEGIN', $fname );
3535 $this->mTrxLevel = 1;
3536 }
3537
3538 /**
3539 * Commits a transaction previously started using begin().
3540 * If no transaction is in progress, a warning is issued.
3541 *
3542 * Nesting of transactions is not supported.
3543 *
3544 * @param string $fname
3545 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3546 * explicitly committing implicit transactions, or calling commit when no
3547 * transaction is in progress. This will silently break any ongoing
3548 * explicit transaction. Only set the flush flag if you are sure that it
3549 * is safe to ignore these warnings in your context.
3550 * @throws DBUnexpectedError
3551 */
3552 final public function commit( $fname = __METHOD__, $flush = '' ) {
3553 if ( $this->mTrxLevel && $this->mTrxAtomicLevels ) {
3554 // There are still atomic sections open. This cannot be ignored
3555 $levels = implode( ', ', $this->mTrxAtomicLevels );
3556 throw new DBUnexpectedError(
3557 $this,
3558 "Got COMMIT while atomic sections $levels are still open"
3559 );
3560 }
3561
3562 if ( $flush === 'flush' ) {
3563 if ( !$this->mTrxLevel ) {
3564 return; // nothing to do
3565 } elseif ( !$this->mTrxAutomatic ) {
3566 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3567 }
3568 } else {
3569 if ( !$this->mTrxLevel ) {
3570 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3571 return; // nothing to do
3572 } elseif ( $this->mTrxAutomatic ) {
3573 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3574 }
3575 }
3576
3577 # Avoid fatals if close() was called
3578 $this->assertOpen();
3579
3580 $this->runOnTransactionPreCommitCallbacks();
3581 $writeTime = $this->pendingWriteQueryDuration();
3582 $this->doCommit( $fname );
3583 if ( $this->mTrxDoneWrites ) {
3584 $this->mDoneWrites = microtime( true );
3585 $this->getTransactionProfiler()->transactionWritingOut(
3586 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
3587 }
3588 $this->runOnTransactionIdleCallbacks();
3589 }
3590
3591 /**
3592 * Issues the COMMIT command to the database server.
3593 *
3594 * @see DatabaseBase::commit()
3595 * @param string $fname
3596 */
3597 protected function doCommit( $fname ) {
3598 if ( $this->mTrxLevel ) {
3599 $this->query( 'COMMIT', $fname );
3600 $this->mTrxLevel = 0;
3601 }
3602 }
3603
3604 /**
3605 * Rollback a transaction previously started using begin().
3606 * If no transaction is in progress, a warning is issued.
3607 *
3608 * No-op on non-transactional databases.
3609 *
3610 * @param string $fname
3611 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3612 * calling rollback when no transaction is in progress. This will silently
3613 * break any ongoing explicit transaction. Only set the flush flag if you
3614 * are sure that it is safe to ignore these warnings in your context.
3615 * @throws DBUnexpectedError
3616 * @since 1.23 Added $flush parameter
3617 */
3618 final public function rollback( $fname = __METHOD__, $flush = '' ) {
3619 if ( $flush !== 'flush' ) {
3620 if ( !$this->mTrxLevel ) {
3621 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3622 return; // nothing to do
3623 } elseif ( $this->mTrxAutomatic ) {
3624 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3625 }
3626 } else {
3627 if ( !$this->mTrxLevel ) {
3628 return; // nothing to do
3629 } elseif ( !$this->mTrxAutomatic ) {
3630 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3631 }
3632 }
3633
3634 # Avoid fatals if close() was called
3635 $this->assertOpen();
3636
3637 $this->doRollback( $fname );
3638 $this->mTrxIdleCallbacks = array(); // cancel
3639 $this->mTrxPreCommitCallbacks = array(); // cancel
3640 $this->mTrxAtomicLevels = array();
3641 if ( $this->mTrxDoneWrites ) {
3642 $this->getTransactionProfiler()->transactionWritingOut(
3643 $this->mServer, $this->mDBname, $this->mTrxShortId );
3644 }
3645 }
3646
3647 /**
3648 * Issues the ROLLBACK command to the database server.
3649 *
3650 * @see DatabaseBase::rollback()
3651 * @param string $fname
3652 */
3653 protected function doRollback( $fname ) {
3654 if ( $this->mTrxLevel ) {
3655 $this->query( 'ROLLBACK', $fname, true );
3656 $this->mTrxLevel = 0;
3657 }
3658 }
3659
3660 /**
3661 * Creates a new table with structure copied from existing table
3662 * Note that unlike most database abstraction functions, this function does not
3663 * automatically append database prefix, because it works at a lower
3664 * abstraction level.
3665 * The table names passed to this function shall not be quoted (this
3666 * function calls addIdentifierQuotes when needed).
3667 *
3668 * @param string $oldName Name of table whose structure should be copied
3669 * @param string $newName Name of table to be created
3670 * @param bool $temporary Whether the new table should be temporary
3671 * @param string $fname Calling function name
3672 * @throws MWException
3673 * @return bool True if operation was successful
3674 */
3675 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3676 $fname = __METHOD__
3677 ) {
3678 throw new MWException(
3679 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3680 }
3681
3682 /**
3683 * List all tables on the database
3684 *
3685 * @param string $prefix Only show tables with this prefix, e.g. mw_
3686 * @param string $fname Calling function name
3687 * @throws MWException
3688 * @return array
3689 */
3690 function listTables( $prefix = null, $fname = __METHOD__ ) {
3691 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3692 }
3693
3694 /**
3695 * Reset the views process cache set by listViews()
3696 * @since 1.22
3697 */
3698 final public function clearViewsCache() {
3699 $this->allViews = null;
3700 }
3701
3702 /**
3703 * Lists all the VIEWs in the database
3704 *
3705 * For caching purposes the list of all views should be stored in
3706 * $this->allViews. The process cache can be cleared with clearViewsCache()
3707 *
3708 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3709 * @param string $fname Name of calling function
3710 * @throws MWException
3711 * @return array
3712 * @since 1.22
3713 */
3714 public function listViews( $prefix = null, $fname = __METHOD__ ) {
3715 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3716 }
3717
3718 /**
3719 * Differentiates between a TABLE and a VIEW
3720 *
3721 * @param string $name Name of the database-structure to test.
3722 * @throws MWException
3723 * @return bool
3724 * @since 1.22
3725 */
3726 public function isView( $name ) {
3727 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3728 }
3729
3730 /**
3731 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3732 * to the format used for inserting into timestamp fields in this DBMS.
3733 *
3734 * The result is unquoted, and needs to be passed through addQuotes()
3735 * before it can be included in raw SQL.
3736 *
3737 * @param string|int $ts
3738 *
3739 * @return string
3740 */
3741 public function timestamp( $ts = 0 ) {
3742 return wfTimestamp( TS_MW, $ts );
3743 }
3744
3745 /**
3746 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3747 * to the format used for inserting into timestamp fields in this DBMS. If
3748 * NULL is input, it is passed through, allowing NULL values to be inserted
3749 * into timestamp fields.
3750 *
3751 * The result is unquoted, and needs to be passed through addQuotes()
3752 * before it can be included in raw SQL.
3753 *
3754 * @param string|int $ts
3755 *
3756 * @return string
3757 */
3758 public function timestampOrNull( $ts = null ) {
3759 if ( is_null( $ts ) ) {
3760 return null;
3761 } else {
3762 return $this->timestamp( $ts );
3763 }
3764 }
3765
3766 /**
3767 * Take the result from a query, and wrap it in a ResultWrapper if
3768 * necessary. Boolean values are passed through as is, to indicate success
3769 * of write queries or failure.
3770 *
3771 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3772 * resource, and it was necessary to call this function to convert it to
3773 * a wrapper. Nowadays, raw database objects are never exposed to external
3774 * callers, so this is unnecessary in external code.
3775 *
3776 * @param bool|ResultWrapper|resource|object $result
3777 * @return bool|ResultWrapper
3778 */
3779 protected function resultObject( $result ) {
3780 if ( !$result ) {
3781 return false;
3782 } elseif ( $result instanceof ResultWrapper ) {
3783 return $result;
3784 } elseif ( $result === true ) {
3785 // Successful write query
3786 return $result;
3787 } else {
3788 return new ResultWrapper( $this, $result );
3789 }
3790 }
3791
3792 /**
3793 * Ping the server and try to reconnect if it there is no connection
3794 *
3795 * @return bool Success or failure
3796 */
3797 public function ping() {
3798 # Stub. Not essential to override.
3799 return true;
3800 }
3801
3802 public function getSessionLagStatus() {
3803 return $this->getTransactionLagStatus() ?: $this->getApproximateLagStatus();
3804 }
3805
3806 /**
3807 * Get the slave lag when the current transaction started
3808 *
3809 * This is useful when transactions might use snapshot isolation
3810 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3811 * is this lag plus transaction duration. If they don't, it is still
3812 * safe to be pessimistic. This returns null if there is no transaction.
3813 *
3814 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3815 * @since 1.27
3816 */
3817 public function getTransactionLagStatus() {
3818 return $this->mTrxLevel
3819 ? array( 'lag' => $this->mTrxSlaveLag, 'since' => $this->trxTimestamp() )
3820 : null;
3821 }
3822
3823 /**
3824 * Get a slave lag estimate for this server
3825 *
3826 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3827 * @since 1.27
3828 */
3829 public function getApproximateLagStatus() {
3830 return array(
3831 'lag' => $this->getLBInfo( 'slave' ) ? $this->getLag() : 0,
3832 'since' => microtime( true )
3833 );
3834 }
3835
3836 /**
3837 * Merge the result of getSessionLagStatus() for several DBs
3838 * using the most pessimistic values to estimate the lag of
3839 * any data derived from them in combination
3840 *
3841 * This is information is useful for caching modules
3842 *
3843 * @see WANObjectCache::set()
3844 * @see WANObjectCache::getWithSetCallback()
3845 *
3846 * @param IDatabase $db1
3847 * @param IDatabase ...
3848 * @return array Map of values:
3849 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3850 * - since: oldest UNIX timestamp of any of the DB lag estimates
3851 * - pending: whether any of the DBs have uncommitted changes
3852 * @since 1.27
3853 */
3854 public static function getCacheSetOptions( IDatabase $db1 ) {
3855 $res = array( 'lag' => 0, 'since' => INF, 'pending' => false );
3856 foreach ( func_get_args() as $db ) {
3857 /** @var IDatabase $db */
3858 $status = $db->getSessionLagStatus();
3859 if ( $status['lag'] === false ) {
3860 $res['lag'] = false;
3861 } elseif ( $res['lag'] !== false ) {
3862 $res['lag'] = max( $res['lag'], $status['lag'] );
3863 }
3864 $res['since'] = min( $res['since'], $status['since'] );
3865 $res['pending'] = $res['pending'] ?: $db->writesPending();
3866 }
3867
3868 return $res;
3869 }
3870
3871 public function getLag() {
3872 return 0;
3873 }
3874
3875 /**
3876 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3877 *
3878 * @return int
3879 */
3880 function maxListLen() {
3881 return 0;
3882 }
3883
3884 /**
3885 * Some DBMSs have a special format for inserting into blob fields, they
3886 * don't allow simple quoted strings to be inserted. To insert into such
3887 * a field, pass the data through this function before passing it to
3888 * DatabaseBase::insert().
3889 *
3890 * @param string $b
3891 * @return string
3892 */
3893 public function encodeBlob( $b ) {
3894 return $b;
3895 }
3896
3897 /**
3898 * Some DBMSs return a special placeholder object representing blob fields
3899 * in result objects. Pass the object through this function to return the
3900 * original string.
3901 *
3902 * @param string|Blob $b
3903 * @return string
3904 */
3905 public function decodeBlob( $b ) {
3906 if ( $b instanceof Blob ) {
3907 $b = $b->fetch();
3908 }
3909 return $b;
3910 }
3911
3912 /**
3913 * Override database's default behavior. $options include:
3914 * 'connTimeout' : Set the connection timeout value in seconds.
3915 * May be useful for very long batch queries such as
3916 * full-wiki dumps, where a single query reads out over
3917 * hours or days.
3918 *
3919 * @param array $options
3920 * @return void
3921 */
3922 public function setSessionOptions( array $options ) {
3923 }
3924
3925 /**
3926 * Read and execute SQL commands from a file.
3927 *
3928 * Returns true on success, error string or exception on failure (depending
3929 * on object's error ignore settings).
3930 *
3931 * @param string $filename File name to open
3932 * @param bool|callable $lineCallback Optional function called before reading each line
3933 * @param bool|callable $resultCallback Optional function called for each MySQL result
3934 * @param bool|string $fname Calling function name or false if name should be
3935 * generated dynamically using $filename
3936 * @param bool|callable $inputCallback Optional function called for each
3937 * complete line sent
3938 * @throws Exception|MWException
3939 * @return bool|string
3940 */
3941 public function sourceFile(
3942 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3943 ) {
3944 MediaWiki\suppressWarnings();
3945 $fp = fopen( $filename, 'r' );
3946 MediaWiki\restoreWarnings();
3947
3948 if ( false === $fp ) {
3949 throw new MWException( "Could not open \"{$filename}\".\n" );
3950 }
3951
3952 if ( !$fname ) {
3953 $fname = __METHOD__ . "( $filename )";
3954 }
3955
3956 try {
3957 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3958 } catch ( Exception $e ) {
3959 fclose( $fp );
3960 throw $e;
3961 }
3962
3963 fclose( $fp );
3964
3965 return $error;
3966 }
3967
3968 /**
3969 * Get the full path of a patch file. Originally based on archive()
3970 * from updaters.inc. Keep in mind this always returns a patch, as
3971 * it fails back to MySQL if no DB-specific patch can be found
3972 *
3973 * @param string $patch The name of the patch, like patch-something.sql
3974 * @return string Full path to patch file
3975 */
3976 public function patchPath( $patch ) {
3977 global $IP;
3978
3979 $dbType = $this->getType();
3980 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3981 return "$IP/maintenance/$dbType/archives/$patch";
3982 } else {
3983 return "$IP/maintenance/archives/$patch";
3984 }
3985 }
3986
3987 /**
3988 * Set variables to be used in sourceFile/sourceStream, in preference to the
3989 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3990 * all. If it's set to false, $GLOBALS will be used.
3991 *
3992 * @param bool|array $vars Mapping variable name to value.
3993 */
3994 public function setSchemaVars( $vars ) {
3995 $this->mSchemaVars = $vars;
3996 }
3997
3998 /**
3999 * Read and execute commands from an open file handle.
4000 *
4001 * Returns true on success, error string or exception on failure (depending
4002 * on object's error ignore settings).
4003 *
4004 * @param resource $fp File handle
4005 * @param bool|callable $lineCallback Optional function called before reading each query
4006 * @param bool|callable $resultCallback Optional function called for each MySQL result
4007 * @param string $fname Calling function name
4008 * @param bool|callable $inputCallback Optional function called for each complete query sent
4009 * @return bool|string
4010 */
4011 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
4012 $fname = __METHOD__, $inputCallback = false
4013 ) {
4014 $cmd = '';
4015
4016 while ( !feof( $fp ) ) {
4017 if ( $lineCallback ) {
4018 call_user_func( $lineCallback );
4019 }
4020
4021 $line = trim( fgets( $fp ) );
4022
4023 if ( $line == '' ) {
4024 continue;
4025 }
4026
4027 if ( '-' == $line[0] && '-' == $line[1] ) {
4028 continue;
4029 }
4030
4031 if ( $cmd != '' ) {
4032 $cmd .= ' ';
4033 }
4034
4035 $done = $this->streamStatementEnd( $cmd, $line );
4036
4037 $cmd .= "$line\n";
4038
4039 if ( $done || feof( $fp ) ) {
4040 $cmd = $this->replaceVars( $cmd );
4041
4042 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) || !$inputCallback ) {
4043 $res = $this->query( $cmd, $fname );
4044
4045 if ( $resultCallback ) {
4046 call_user_func( $resultCallback, $res, $this );
4047 }
4048
4049 if ( false === $res ) {
4050 $err = $this->lastError();
4051
4052 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4053 }
4054 }
4055 $cmd = '';
4056 }
4057 }
4058
4059 return true;
4060 }
4061
4062 /**
4063 * Called by sourceStream() to check if we've reached a statement end
4064 *
4065 * @param string $sql SQL assembled so far
4066 * @param string $newLine New line about to be added to $sql
4067 * @return bool Whether $newLine contains end of the statement
4068 */
4069 public function streamStatementEnd( &$sql, &$newLine ) {
4070 if ( $this->delimiter ) {
4071 $prev = $newLine;
4072 $newLine = preg_replace( '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
4073 if ( $newLine != $prev ) {
4074 return true;
4075 }
4076 }
4077
4078 return false;
4079 }
4080
4081 /**
4082 * Database independent variable replacement. Replaces a set of variables
4083 * in an SQL statement with their contents as given by $this->getSchemaVars().
4084 *
4085 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4086 *
4087 * - '{$var}' should be used for text and is passed through the database's
4088 * addQuotes method.
4089 * - `{$var}` should be used for identifiers (e.g. table and database names).
4090 * It is passed through the database's addIdentifierQuotes method which
4091 * can be overridden if the database uses something other than backticks.
4092 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4093 * database's tableName method.
4094 * - / *i* / passes the name that follows through the database's indexName method.
4095 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4096 * its use should be avoided. In 1.24 and older, string encoding was applied.
4097 *
4098 * @param string $ins SQL statement to replace variables in
4099 * @return string The new SQL statement with variables replaced
4100 */
4101 protected function replaceVars( $ins ) {
4102 $that = $this;
4103 $vars = $this->getSchemaVars();
4104 return preg_replace_callback(
4105 '!
4106 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4107 \'\{\$ (\w+) }\' | # 3. addQuotes
4108 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4109 /\*\$ (\w+) \*/ # 5. leave unencoded
4110 !x',
4111 function ( $m ) use ( $that, $vars ) {
4112 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4113 // check for both nonexistent keys *and* the empty string.
4114 if ( isset( $m[1] ) && $m[1] !== '' ) {
4115 if ( $m[1] === 'i' ) {
4116 return $that->indexName( $m[2] );
4117 } else {
4118 return $that->tableName( $m[2] );
4119 }
4120 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4121 return $that->addQuotes( $vars[$m[3]] );
4122 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4123 return $that->addIdentifierQuotes( $vars[$m[4]] );
4124 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4125 return $vars[$m[5]];
4126 } else {
4127 return $m[0];
4128 }
4129 },
4130 $ins
4131 );
4132 }
4133
4134 /**
4135 * Get schema variables. If none have been set via setSchemaVars(), then
4136 * use some defaults from the current object.
4137 *
4138 * @return array
4139 */
4140 protected function getSchemaVars() {
4141 if ( $this->mSchemaVars ) {
4142 return $this->mSchemaVars;
4143 } else {
4144 return $this->getDefaultSchemaVars();
4145 }
4146 }
4147
4148 /**
4149 * Get schema variables to use if none have been set via setSchemaVars().
4150 *
4151 * Override this in derived classes to provide variables for tables.sql
4152 * and SQL patch files.
4153 *
4154 * @return array
4155 */
4156 protected function getDefaultSchemaVars() {
4157 return array();
4158 }
4159
4160 /**
4161 * Check to see if a named lock is available (non-blocking)
4162 *
4163 * @param string $lockName Name of lock to poll
4164 * @param string $method Name of method calling us
4165 * @return bool
4166 * @since 1.20
4167 */
4168 public function lockIsFree( $lockName, $method ) {
4169 return true;
4170 }
4171
4172 /**
4173 * Acquire a named lock
4174 *
4175 * Named locks are not related to transactions
4176 *
4177 * @param string $lockName Name of lock to aquire
4178 * @param string $method Name of method calling us
4179 * @param int $timeout
4180 * @return bool
4181 */
4182 public function lock( $lockName, $method, $timeout = 5 ) {
4183 return true;
4184 }
4185
4186 /**
4187 * Release a lock
4188 *
4189 * Named locks are not related to transactions
4190 *
4191 * @param string $lockName Name of lock to release
4192 * @param string $method Name of method calling us
4193 *
4194 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4195 * by this thread (in which case the lock is not released), and NULL if the named
4196 * lock did not exist
4197 */
4198 public function unlock( $lockName, $method ) {
4199 return true;
4200 }
4201
4202 /**
4203 * Check to see if a named lock used by lock() use blocking queues
4204 *
4205 * @return bool
4206 * @since 1.26
4207 */
4208 public function namedLocksEnqueue() {
4209 return false;
4210 }
4211
4212 /**
4213 * Lock specific tables
4214 *
4215 * @param array $read Array of tables to lock for read access
4216 * @param array $write Array of tables to lock for write access
4217 * @param string $method Name of caller
4218 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4219 * @return bool
4220 */
4221 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4222 return true;
4223 }
4224
4225 /**
4226 * Unlock specific tables
4227 *
4228 * @param string $method The caller
4229 * @return bool
4230 */
4231 public function unlockTables( $method ) {
4232 return true;
4233 }
4234
4235 /**
4236 * Delete a table
4237 * @param string $tableName
4238 * @param string $fName
4239 * @return bool|ResultWrapper
4240 * @since 1.18
4241 */
4242 public function dropTable( $tableName, $fName = __METHOD__ ) {
4243 if ( !$this->tableExists( $tableName, $fName ) ) {
4244 return false;
4245 }
4246 $sql = "DROP TABLE " . $this->tableName( $tableName );
4247 if ( $this->cascadingDeletes() ) {
4248 $sql .= " CASCADE";
4249 }
4250
4251 return $this->query( $sql, $fName );
4252 }
4253
4254 /**
4255 * Get search engine class. All subclasses of this need to implement this
4256 * if they wish to use searching.
4257 *
4258 * @return string
4259 */
4260 public function getSearchEngine() {
4261 return 'SearchEngineDummy';
4262 }
4263
4264 /**
4265 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4266 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4267 * because "i" sorts after all numbers.
4268 *
4269 * @return string
4270 */
4271 public function getInfinity() {
4272 return 'infinity';
4273 }
4274
4275 /**
4276 * Encode an expiry time into the DBMS dependent format
4277 *
4278 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4279 * @return string
4280 */
4281 public function encodeExpiry( $expiry ) {
4282 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4283 ? $this->getInfinity()
4284 : $this->timestamp( $expiry );
4285 }
4286
4287 /**
4288 * Decode an expiry time into a DBMS independent format
4289 *
4290 * @param string $expiry DB timestamp field value for expiry
4291 * @param int $format TS_* constant, defaults to TS_MW
4292 * @return string
4293 */
4294 public function decodeExpiry( $expiry, $format = TS_MW ) {
4295 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4296 ? 'infinity'
4297 : wfTimestamp( $format, $expiry );
4298 }
4299
4300 /**
4301 * Allow or deny "big selects" for this session only. This is done by setting
4302 * the sql_big_selects session variable.
4303 *
4304 * This is a MySQL-specific feature.
4305 *
4306 * @param bool|string $value True for allow, false for deny, or "default" to
4307 * restore the initial value
4308 */
4309 public function setBigSelects( $value = true ) {
4310 // no-op
4311 }
4312
4313 public function isReadOnly() {
4314 return ( $this->getReadOnlyReason() !== false );
4315 }
4316
4317 /**
4318 * @return string|bool Reason this DB is read-only or false if it is not
4319 */
4320 protected function getReadOnlyReason() {
4321 $reason = $this->getLBInfo( 'readOnlyReason' );
4322
4323 return is_string( $reason ) ? $reason : false;
4324 }
4325
4326 /**
4327 * @since 1.19
4328 * @return string
4329 */
4330 public function __toString() {
4331 return (string)$this->mConn;
4332 }
4333
4334 /**
4335 * Run a few simple sanity checks
4336 */
4337 public function __destruct() {
4338 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
4339 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4340 }
4341 if ( count( $this->mTrxIdleCallbacks ) || count( $this->mTrxPreCommitCallbacks ) ) {
4342 $callers = array();
4343 foreach ( $this->mTrxIdleCallbacks as $callbackInfo ) {
4344 $callers[] = $callbackInfo[1];
4345 }
4346 $callers = implode( ', ', $callers );
4347 trigger_error( "DB transaction callbacks still pending (from $callers)." );
4348 }
4349 }
4350 }
4351
4352 /**
4353 * @since 1.27
4354 */
4355 abstract class Database extends DatabaseBase {
4356 // B/C until nothing type hints for DatabaseBase
4357 // @TODO: finish renaming DatabaseBase => Database
4358 }