4 * @defgroup Database Database
6 * This file deals with database interface functions
7 * and query specifics/optimisations.
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.
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.
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
29 * Interface for classes that implement or wrap DatabaseBase
36 * Database abstraction object
39 abstract class DatabaseBase
implements IDatabase
{
40 /** Number of times to re-try an operation in case of deadlock */
41 const DEADLOCK_TRIES
= 4;
43 /** Minimum time to wait before retry, in microseconds */
44 const DEADLOCK_DELAY_MIN
= 500000;
46 /** Maximum time to wait before retry */
47 const DEADLOCK_DELAY_MAX
= 1500000;
49 protected $mLastQuery = '';
50 protected $mDoneWrites = false;
51 protected $mPHPError = false;
53 protected $mServer, $mUser, $mPassword, $mDBname;
55 /** @var resource Database connection */
56 protected $mConn = null;
57 protected $mOpened = false;
59 /** @var callable[] */
60 protected $mTrxIdleCallbacks = array();
61 /** @var callable[] */
62 protected $mTrxPreCommitCallbacks = array();
64 protected $mTablePrefix;
68 protected $mErrorCount = 0;
69 protected $mLBInfo = array();
70 protected $mDefaultBigSelects = null;
71 protected $mSchemaVars = false;
73 protected $preparedArgs;
75 protected $htmlErrors;
77 protected $delimiter = ';';
80 * Either 1 if a transaction is active or 0 otherwise.
81 * The other Trx fields may not be meaningfull if this is 0.
85 protected $mTrxLevel = 0;
88 * Either a short hexidecimal string if a transaction is active or ""
91 * @see DatabaseBase::mTrxLevel
93 protected $mTrxShortId = '';
96 * The UNIX time that the transaction started. Callers can assume that if
97 * snapshot isolation is used, then the data is *at least* up to date to that
98 * point (possibly more up-to-date since the first SELECT defines the snapshot).
101 * @see DatabaseBase::mTrxLevel
103 private $mTrxTimestamp = null;
106 * Remembers the function name given for starting the most recent transaction via begin().
107 * Used to provide additional context for error reporting.
110 * @see DatabaseBase::mTrxLevel
112 private $mTrxFname = null;
115 * Record if possible write queries were done in the last transaction started
118 * @see DatabaseBase::mTrxLevel
120 private $mTrxDoneWrites = false;
123 * Record if the current transaction was started implicitly due to DBO_TRX being set.
126 * @see DatabaseBase::mTrxLevel
128 private $mTrxAutomatic = false;
131 * Array of levels of atomicity within transactions
135 private $mTrxAtomicLevels;
138 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
142 private $mTrxAutomaticAtomic = false;
145 * Track the seconds spent in write queries for the current transaction
149 private $mTrxWriteDuration = 0.0;
153 * @var resource File handle for upgrade
155 protected $fileHandle = null;
159 * @var string[] Process cache of VIEWs names in the database
161 protected $allViews = null;
163 /** @var TransactionProfiler */
164 protected $trxProfiler;
167 * A string describing the current software version, and possibly
168 * other details in a user-friendly way. Will be listed on Special:Version, etc.
169 * Use getServerVersion() to get machine-friendly information.
171 * @return string Version information from the database server
173 public function getServerInfo() {
174 return $this->getServerVersion();
178 * @return string Command delimiter used by this database engine
180 public function getDelimiter() {
181 return $this->delimiter
;
185 * Boolean, controls output of large amounts of debug information.
186 * @param bool|null $debug
187 * - true to enable debugging
188 * - false to disable debugging
189 * - omitted or null to do nothing
191 * @return bool|null Previous value of the flag
193 public function debug( $debug = null ) {
194 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
198 * Turns buffering of SQL result sets on (true) or off (false). Default is
201 * Unbuffered queries are very troublesome in MySQL:
203 * - If another query is executed while the first query is being read
204 * out, the first query is killed. This means you can't call normal
205 * MediaWiki functions while you are reading an unbuffered query result
206 * from a normal wfGetDB() connection.
208 * - Unbuffered queries cause the MySQL server to use large amounts of
209 * memory and to hold broad locks which block other queries.
211 * If you want to limit client-side memory, it's almost always better to
212 * split up queries into batches using a LIMIT clause than to switch off
215 * @param null|bool $buffer
216 * @return null|bool The previous value of the flag
218 public function bufferResults( $buffer = null ) {
219 if ( is_null( $buffer ) ) {
220 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
222 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
227 * Turns on (false) or off (true) the automatic generation and sending
228 * of a "we're sorry, but there has been a database error" page on
229 * database errors. Default is on (false). When turned off, the
230 * code should use lastErrno() and lastError() to handle the
231 * situation as appropriate.
233 * Do not use this function outside of the Database classes.
235 * @param null|bool $ignoreErrors
236 * @return bool The previous value of the flag.
238 public function ignoreErrors( $ignoreErrors = null ) {
239 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
243 * Gets the current transaction level.
245 * Historically, transactions were allowed to be "nested". This is no
246 * longer supported, so this function really only returns a boolean.
248 * @return int The previous value
250 public function trxLevel() {
251 return $this->mTrxLevel
;
255 * Get the UNIX timestamp of the time that the transaction was established
257 * This can be used to reason about the staleness of SELECT data
258 * in REPEATABLE-READ transaction isolation level.
260 * @return float|null Returns null if there is not active transaction
263 public function trxTimestamp() {
264 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
268 * Get/set the number of errors logged. Only useful when errors are ignored
269 * @param int $count The count to set, or omitted to leave it unchanged.
270 * @return int The error count
272 public function errorCount( $count = null ) {
273 return wfSetVar( $this->mErrorCount
, $count );
277 * Get/set the table prefix.
278 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
279 * @return string The previous table prefix.
281 public function tablePrefix( $prefix = null ) {
282 return wfSetVar( $this->mTablePrefix
, $prefix );
286 * Get/set the db schema.
287 * @param string $schema The database schema to set, or omitted to leave it unchanged.
288 * @return string The previous db schema.
290 public function dbSchema( $schema = null ) {
291 return wfSetVar( $this->mSchema
, $schema );
295 * Set the filehandle to copy write statements to.
297 * @param resource $fh File handle
299 public function setFileHandle( $fh ) {
300 $this->fileHandle
= $fh;
304 * Get properties passed down from the server info array of the load
307 * @param string $name The entry of the info array to get, or null to get the
310 * @return array|mixed|null
312 public function getLBInfo( $name = null ) {
313 if ( is_null( $name ) ) {
314 return $this->mLBInfo
;
316 if ( array_key_exists( $name, $this->mLBInfo
) ) {
317 return $this->mLBInfo
[$name];
325 * Set the LB info array, or a member of it. If called with one parameter,
326 * the LB info array is set to that parameter. If it is called with two
327 * parameters, the member with the given name is set to the given value.
329 * @param string $name
330 * @param array $value
332 public function setLBInfo( $name, $value = null ) {
333 if ( is_null( $value ) ) {
334 $this->mLBInfo
= $name;
336 $this->mLBInfo
[$name] = $value;
341 * Set lag time in seconds for a fake slave
343 * @param mixed $lag Valid values for this parameter are determined by the
344 * subclass, but should be a PHP scalar or array that would be sensible
345 * as part of $wgLBFactoryConf.
347 public function setFakeSlaveLag( $lag ) {
351 * Make this connection a fake master
353 * @param bool $enabled
355 public function setFakeMaster( $enabled = true ) {
359 * @return TransactionProfiler
361 protected function getTransactionProfiler() {
362 return $this->trxProfiler
364 : Profiler
::instance()->getTransactionProfiler();
368 * Returns true if this database supports (and uses) cascading deletes
372 public function cascadingDeletes() {
377 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
381 public function cleanupTriggers() {
386 * Returns true if this database is strict about what can be put into an IP field.
387 * Specifically, it uses a NULL value instead of an empty string.
391 public function strictIPs() {
396 * Returns true if this database uses timestamps rather than integers
400 public function realTimestamps() {
405 * Returns true if this database does an implicit sort when doing GROUP BY
409 public function implicitGroupby() {
414 * Returns true if this database does an implicit order by when the column has an index
415 * For example: SELECT page_title FROM page LIMIT 1
419 public function implicitOrderby() {
424 * Returns true if this database can do a native search on IP columns
425 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
429 public function searchableIPs() {
434 * Returns true if this database can use functional indexes
438 public function functionalIndexes() {
443 * Return the last query that went through DatabaseBase::query()
446 public function lastQuery() {
447 return $this->mLastQuery
;
451 * Returns true if the connection may have been used for write queries.
452 * Should return true if unsure.
456 public function doneWrites() {
457 return (bool)$this->mDoneWrites
;
461 * Returns the last time the connection may have been used for write queries.
462 * Should return a timestamp if unsure.
464 * @return int|float UNIX timestamp or false
467 public function lastDoneWrites() {
468 return $this->mDoneWrites ?
: false;
472 * Returns true if there is a transaction open with possible write
473 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
477 public function writesOrCallbacksPending() {
478 return $this->mTrxLevel
&& (
479 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
484 * Get the time spend running write queries for this
486 * High times could be due to scanning, updates, locking, and such
488 * @return float|bool Returns false if not transaction is active
491 public function pendingWriteQueryDuration() {
492 return $this->mTrxLevel ?
$this->mTrxWriteDuration
: false;
496 * Is a connection to the database open?
499 public function isOpen() {
500 return $this->mOpened
;
504 * Set a flag for this connection
506 * @param int $flag DBO_* constants from Defines.php:
507 * - DBO_DEBUG: output some debug info (same as debug())
508 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
509 * - DBO_TRX: automatically start transactions
510 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
511 * and removes it in command line mode
512 * - DBO_PERSISTENT: use persistant database connection
514 public function setFlag( $flag ) {
515 global $wgDebugDBTransactions;
516 $this->mFlags |
= $flag;
517 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
518 wfDebug( "Implicit transactions are now enabled.\n" );
523 * Clear a flag for this connection
525 * @param int $flag DBO_* constants from Defines.php:
526 * - DBO_DEBUG: output some debug info (same as debug())
527 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
528 * - DBO_TRX: automatically start transactions
529 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
530 * and removes it in command line mode
531 * - DBO_PERSISTENT: use persistant database connection
533 public function clearFlag( $flag ) {
534 global $wgDebugDBTransactions;
535 $this->mFlags
&= ~
$flag;
536 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
537 wfDebug( "Implicit transactions are now disabled.\n" );
542 * Returns a boolean whether the flag $flag is set for this connection
544 * @param int $flag DBO_* constants from Defines.php:
545 * - DBO_DEBUG: output some debug info (same as debug())
546 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
547 * - DBO_TRX: automatically start transactions
548 * - DBO_PERSISTENT: use persistant database connection
551 public function getFlag( $flag ) {
552 return !!( $this->mFlags
& $flag );
556 * General read-only accessor
558 * @param string $name
561 public function getProperty( $name ) {
568 public function getWikiID() {
569 if ( $this->mTablePrefix
) {
570 return "{$this->mDBname}-{$this->mTablePrefix}";
572 return $this->mDBname
;
577 * Return a path to the DBMS-specific SQL file if it exists,
578 * otherwise default SQL file
580 * @param string $filename
583 private function getSqlFilePath( $filename ) {
585 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
586 if ( file_exists( $dbmsSpecificFilePath ) ) {
587 return $dbmsSpecificFilePath;
589 return "$IP/maintenance/$filename";
594 * Return a path to the DBMS-specific schema file,
595 * otherwise default to tables.sql
599 public function getSchemaPath() {
600 return $this->getSqlFilePath( 'tables.sql' );
604 * Return a path to the DBMS-specific update key file,
605 * otherwise default to update-keys.sql
609 public function getUpdateKeysPath() {
610 return $this->getSqlFilePath( 'update-keys.sql' );
614 * Get the type of the DBMS, as it appears in $wgDBtype.
618 abstract function getType();
621 * Open a connection to the database. Usually aborts on failure
623 * @param string $server Database server host
624 * @param string $user Database user name
625 * @param string $password Database user password
626 * @param string $dbName Database name
628 * @throws DBConnectionError
630 abstract function open( $server, $user, $password, $dbName );
633 * Fetch the next row from the given result object, in object form.
634 * Fields can be retrieved with $row->fieldname, with fields acting like
636 * If no more rows are available, false is returned.
638 * @param ResultWrapper|stdClass $res Object as returned from DatabaseBase::query(), etc.
639 * @return stdClass|bool
640 * @throws DBUnexpectedError Thrown if the database returns an error
642 abstract function fetchObject( $res );
645 * Fetch the next row from the given result object, in associative array
646 * form. Fields are retrieved with $row['fieldname'].
647 * If no more rows are available, false is returned.
649 * @param ResultWrapper $res Result object as returned from DatabaseBase::query(), etc.
651 * @throws DBUnexpectedError Thrown if the database returns an error
653 abstract function fetchRow( $res );
656 * Get the number of rows in a result object
658 * @param mixed $res A SQL result
661 abstract function numRows( $res );
664 * Get the number of fields in a result object
665 * @see http://www.php.net/mysql_num_fields
667 * @param mixed $res A SQL result
670 abstract function numFields( $res );
673 * Get a field name in a result object
674 * @see http://www.php.net/mysql_field_name
676 * @param mixed $res A SQL result
680 abstract function fieldName( $res, $n );
683 * Get the inserted value of an auto-increment row
685 * The value inserted should be fetched from nextSequenceValue()
688 * $id = $dbw->nextSequenceValue( 'page_page_id_seq' );
689 * $dbw->insert( 'page', array( 'page_id' => $id ) );
690 * $id = $dbw->insertId();
694 abstract function insertId();
697 * Change the position of the cursor in a result object
698 * @see http://www.php.net/mysql_data_seek
700 * @param mixed $res A SQL result
703 abstract function dataSeek( $res, $row );
706 * Get the last error number
707 * @see http://www.php.net/mysql_errno
711 abstract function lastErrno();
714 * Get a description of the last error
715 * @see http://www.php.net/mysql_error
719 abstract function lastError();
722 * mysql_fetch_field() wrapper
723 * Returns false if the field doesn't exist
725 * @param string $table Table name
726 * @param string $field Field name
730 abstract function fieldInfo( $table, $field );
733 * Get information about an index into an object
734 * @param string $table Table name
735 * @param string $index Index name
736 * @param string $fname Calling function name
737 * @return mixed Database-specific index description class or false if the index does not exist
739 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
742 * Get the number of rows affected by the last write query
743 * @see http://www.php.net/mysql_affected_rows
747 abstract function affectedRows();
750 * Wrapper for addslashes()
752 * @param string $s String to be slashed.
753 * @return string Slashed string.
755 abstract function strencode( $s );
758 * Returns a wikitext link to the DB's website, e.g.,
759 * return "[http://www.mysql.com/ MySQL]";
760 * Should at least contain plain text, if for some reason
761 * your database has no website.
763 * @return string Wikitext of a link to the server software's web site
765 abstract function getSoftwareLink();
768 * A string describing the current software version, like from
769 * mysql_get_server_info().
771 * @return string Version information from the database server.
773 abstract function getServerVersion();
778 * FIXME: It is possible to construct a Database object with no associated
779 * connection object, by specifying no parameters to __construct(). This
780 * feature is deprecated and should be removed.
782 * DatabaseBase subclasses should not be constructed directly in external
783 * code. DatabaseBase::factory() should be used instead.
785 * @param array $params Parameters passed from DatabaseBase::factory()
787 function __construct( array $params ) {
788 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode, $wgDebugDBTransactions;
790 $this->mTrxAtomicLevels
= new SplStack
;
792 $server = $params['host'];
793 $user = $params['user'];
794 $password = $params['password'];
795 $dbName = $params['dbname'];
796 $flags = $params['flags'];
797 $tablePrefix = $params['tablePrefix'];
798 $schema = $params['schema'];
799 $foreign = $params['foreign'];
801 $this->mFlags
= $flags;
802 if ( $this->mFlags
& DBO_DEFAULT
) {
803 if ( $wgCommandLineMode ) {
804 $this->mFlags
&= ~DBO_TRX
;
805 if ( $wgDebugDBTransactions ) {
806 wfDebug( "Implicit transaction open disabled.\n" );
809 $this->mFlags |
= DBO_TRX
;
810 if ( $wgDebugDBTransactions ) {
811 wfDebug( "Implicit transaction open enabled.\n" );
816 /** Get the default table prefix*/
817 if ( $tablePrefix == 'get from global' ) {
818 $this->mTablePrefix
= $wgDBprefix;
820 $this->mTablePrefix
= $tablePrefix;
823 /** Get the database schema*/
824 if ( $schema == 'get from global' ) {
825 $this->mSchema
= $wgDBmwschema;
827 $this->mSchema
= $schema;
830 $this->mForeign
= $foreign;
832 if ( isset( $params['trxProfiler'] ) ) {
833 $this->trxProfiler
= $params['trxProfiler']; // override
837 $this->open( $server, $user, $password, $dbName );
842 * Called by serialize. Throw an exception when DB connection is serialized.
843 * This causes problems on some database engines because the connection is
844 * not restored on unserialize.
846 public function __sleep() {
847 throw new MWException( 'Database serialization may cause problems, since ' .
848 'the connection is not restored on wakeup.' );
852 * Given a DB type, construct the name of the appropriate child class of
853 * DatabaseBase. This is designed to replace all of the manual stuff like:
854 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
855 * as well as validate against the canonical list of DB types we have
857 * This factory function is mostly useful for when you need to connect to a
858 * database other than the MediaWiki default (such as for external auth,
859 * an extension, et cetera). Do not use this to connect to the MediaWiki
860 * database. Example uses in core:
861 * @see LoadBalancer::reallyOpenConnection()
862 * @see ForeignDBRepo::getMasterDB()
863 * @see WebInstallerDBConnect::execute()
867 * @param string $dbType A possible DB type
868 * @param array $p An array of options to pass to the constructor.
869 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
870 * @throws MWException If the database driver or extension cannot be found
871 * @return DatabaseBase|null DatabaseBase subclass or null
873 final public static function factory( $dbType, $p = array() ) {
874 $canonicalDBTypes = array(
875 'mysql' => array( 'mysqli', 'mysql' ),
876 'postgres' => array(),
883 $dbType = strtolower( $dbType );
884 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
885 $possibleDrivers = $canonicalDBTypes[$dbType];
886 if ( !empty( $p['driver'] ) ) {
887 if ( in_array( $p['driver'], $possibleDrivers ) ) {
888 $driver = $p['driver'];
890 throw new MWException( __METHOD__
.
891 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
894 foreach ( $possibleDrivers as $posDriver ) {
895 if ( extension_loaded( $posDriver ) ) {
896 $driver = $posDriver;
904 if ( $driver === false ) {
905 throw new MWException( __METHOD__
.
906 " no viable database extension found for type '$dbType'" );
909 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
910 // and everything else doesn't use a schema (e.g. null)
911 // Although postgres and oracle support schemas, we don't use them (yet)
912 // to maintain backwards compatibility
913 $defaultSchemas = array(
918 'mssql' => 'get from global',
921 $class = 'Database' . ucfirst( $driver );
922 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
923 // Resolve some defaults for b/c
924 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
925 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
926 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
927 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
928 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
929 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global';
930 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : $defaultSchemas[$dbType];
931 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
933 return new $class( $p );
939 protected function installErrorHandler() {
940 $this->mPHPError
= false;
941 $this->htmlErrors
= ini_set( 'html_errors', '0' );
942 set_error_handler( array( $this, 'connectionErrorHandler' ) );
946 * @return bool|string
948 protected function restoreErrorHandler() {
949 restore_error_handler();
950 if ( $this->htmlErrors
!== false ) {
951 ini_set( 'html_errors', $this->htmlErrors
);
953 if ( $this->mPHPError
) {
954 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
955 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
965 * @param string $errstr
967 public function connectionErrorHandler( $errno, $errstr ) {
968 $this->mPHPError
= $errstr;
972 * Create a log context to pass to wfLogDBError or other logging functions.
974 * @param array $extras Additional data to add to context
977 protected function getLogContext( array $extras = array() ) {
980 'db_server' => $this->mServer
,
981 'db_name' => $this->mDBname
,
982 'db_user' => $this->mUser
,
989 * Closes a database connection.
990 * if it is open : commits any open transactions
992 * @throws MWException
993 * @return bool Operation success. true if already closed.
995 public function close() {
996 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
997 throw new MWException( "Transaction idle callbacks still pending." );
999 if ( $this->mConn
) {
1000 if ( $this->trxLevel() ) {
1001 if ( !$this->mTrxAutomatic
) {
1002 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
1003 " performing implicit commit before closing connection!" );
1006 $this->commit( __METHOD__
, 'flush' );
1009 $closed = $this->closeConnection();
1010 $this->mConn
= false;
1014 $this->mOpened
= false;
1020 * Closes underlying database connection
1022 * @return bool Whether connection was closed successfully
1024 abstract protected function closeConnection();
1027 * @param string $error Fallback error message, used if none is given by DB
1028 * @throws DBConnectionError
1030 function reportConnectionError( $error = 'Unknown error' ) {
1031 $myError = $this->lastError();
1037 throw new DBConnectionError( $this, $error );
1041 * The DBMS-dependent part of query()
1043 * @param string $sql SQL query.
1044 * @return ResultWrapper|bool Result object to feed to fetchObject,
1045 * fetchRow, ...; or false on failure
1047 abstract protected function doQuery( $sql );
1050 * Determine whether a query writes to the DB.
1051 * Should return true if unsure.
1053 * @param string $sql
1056 public function isWriteQuery( $sql ) {
1057 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
1061 * Determine whether a SQL statement is sensitive to isolation level.
1062 * A SQL statement is considered transactable if its result could vary
1063 * depending on the transaction isolation level. Operational commands
1064 * such as 'SET' and 'SHOW' are not considered to be transactable.
1066 * @param string $sql
1069 public function isTransactableQuery( $sql ) {
1070 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
1071 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
1075 * Run an SQL query and return the result. Normally throws a DBQueryError
1076 * on failure. If errors are ignored, returns false instead.
1078 * In new code, the query wrappers select(), insert(), update(), delete(),
1079 * etc. should be used where possible, since they give much better DBMS
1080 * independence and automatically quote or validate user input in a variety
1081 * of contexts. This function is generally only useful for queries which are
1082 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
1085 * However, the query wrappers themselves should call this function.
1087 * @param string $sql SQL query
1088 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
1089 * comment (you can use __METHOD__ or add some extra info)
1090 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
1091 * maybe best to catch the exception instead?
1092 * @throws MWException
1093 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
1094 * for a successful read query, or false on failure if $tempIgnore set
1096 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
1097 global $wgUser, $wgDebugDBTransactions, $wgDebugDumpSqlLength;
1099 $this->mLastQuery
= $sql;
1101 $isWriteQuery = $this->isWriteQuery( $sql );
1102 if ( $isWriteQuery ) {
1103 if ( !$this->mDoneWrites
) {
1104 wfDebug( __METHOD__
. ': Writes done: ' .
1105 DatabaseBase
::generalizeSQL( $sql ) . "\n" );
1107 # Set a flag indicating that writes have been done
1108 $this->mDoneWrites
= microtime( true );
1111 # Add a comment for easy SHOW PROCESSLIST interpretation
1112 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
1113 $userName = $wgUser->getName();
1114 if ( mb_strlen( $userName ) > 15 ) {
1115 $userName = mb_substr( $userName, 0, 15 ) . '...';
1117 $userName = str_replace( '/', '', $userName );
1122 // Add trace comment to the begin of the sql string, right after the operator.
1123 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
1124 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
1126 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
) && $this->isTransactableQuery( $sql ) ) {
1127 if ( $wgDebugDBTransactions ) {
1128 wfDebug( "Implicit transaction start.\n" );
1130 $this->begin( __METHOD__
. " ($fname)" );
1131 $this->mTrxAutomatic
= true;
1134 # Keep track of whether the transaction has write queries pending
1135 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWriteQuery ) {
1136 $this->mTrxDoneWrites
= true;
1137 $this->getTransactionProfiler()->transactionWritingIn(
1138 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
1141 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1142 # generalizeSQL will probably cut down the query to reasonable
1143 # logging size most of the time. The substr is really just a sanity check.
1145 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1146 $totalProf = 'DatabaseBase::query-master';
1148 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1149 $totalProf = 'DatabaseBase::query';
1151 # Include query transaction state
1152 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
1154 $profiler = Profiler
::instance();
1155 if ( !$profiler instanceof ProfilerStub
) {
1156 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
1157 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
1160 if ( $this->debug() ) {
1164 $sqlx = $wgDebugDumpSqlLength ?
substr( $commentedSql, 0, $wgDebugDumpSqlLength )
1166 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1168 $master = $isMaster ?
'master' : 'slave';
1169 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1172 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
1174 # Avoid fatals if close() was called
1175 if ( !$this->isOpen() ) {
1176 throw new DBUnexpectedError( $this, "DB connection was already closed." );
1179 # Do the query and handle errors
1180 $startTime = microtime( true );
1181 $ret = $this->doQuery( $commentedSql );
1182 $queryRuntime = microtime( true ) - $startTime;
1183 # Log the query time and feed it into the DB trx profiler
1184 $this->getTransactionProfiler()->recordQueryCompletion(
1185 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1187 MWDebug
::queryTime( $queryId );
1189 # Try reconnecting if the connection was lost
1190 if ( false === $ret && $this->wasErrorReissuable() ) {
1191 # Transaction is gone, like it or not
1192 $hadTrx = $this->mTrxLevel
; // possible lost transaction
1193 $this->mTrxLevel
= 0;
1194 $this->mTrxIdleCallbacks
= array(); // bug 65263
1195 $this->mTrxPreCommitCallbacks
= array(); // bug 65263
1196 wfDebug( "Connection lost, reconnecting...\n" );
1197 # Stash the last error values since ping() might clear them
1198 $lastError = $this->lastError();
1199 $lastErrno = $this->lastErrno();
1200 if ( $this->ping() ) {
1201 wfDebug( "Reconnected\n" );
1202 $server = $this->getServer();
1203 $msg = __METHOD__
. ": lost connection to $server; reconnected";
1204 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1207 # Leave $ret as false and let an error be reported.
1208 # Callers may catch the exception and continue to use the DB.
1209 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1211 # Should be safe to silently retry (no trx and thus no callbacks)
1212 $startTime = microtime( true );
1213 $ret = $this->doQuery( $commentedSql );
1214 $queryRuntime = microtime( true ) - $startTime;
1215 # Log the query time and feed it into the DB trx profiler
1216 $this->getTransactionProfiler()->recordQueryCompletion(
1217 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1220 wfDebug( "Failed\n" );
1224 if ( false === $ret ) {
1225 $this->reportQueryError(
1226 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1229 $res = $this->resultObject( $ret );
1231 // Destroy profile sections in the opposite order to their creation
1232 $queryProfSection = false;
1233 $totalProfSection = false;
1235 if ( $isWriteQuery && $this->mTrxLevel
) {
1236 $this->mTrxWriteDuration +
= $queryRuntime;
1243 * Report a query error. Log the error, and if neither the object ignore
1244 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1246 * @param string $error
1248 * @param string $sql
1249 * @param string $fname
1250 * @param bool $tempIgnore
1251 * @throws DBQueryError
1253 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1254 ++
$this->mErrorCount
;
1256 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1257 wfDebug( "SQL ERROR (ignored): $error\n" );
1259 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1261 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1262 $this->getLogContext( array(
1263 'method' => __METHOD__
,
1266 'sql1line' => $sql1line,
1270 wfDebug( "SQL ERROR: " . $error . "\n" );
1271 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1276 * Intended to be compatible with the PEAR::DB wrapper functions.
1277 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1279 * ? = scalar value, quoted as necessary
1280 * ! = raw SQL bit (a function for instance)
1281 * & = filename; reads the file and inserts as a blob
1282 * (we don't use this though...)
1284 * @param string $sql
1285 * @param string $func
1289 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1290 /* MySQL doesn't support prepared statements (yet), so just
1291 * pack up the query for reference. We'll manually replace
1294 return array( 'query' => $sql, 'func' => $func );
1298 * Free a prepared query, generated by prepare().
1299 * @param string $prepared
1301 protected function freePrepared( $prepared ) {
1302 /* No-op by default */
1306 * Execute a prepared query with the various arguments
1307 * @param string $prepared The prepared sql
1308 * @param mixed $args Either an array here, or put scalars as varargs
1310 * @return ResultWrapper
1312 public function execute( $prepared, $args = null ) {
1313 if ( !is_array( $args ) ) {
1315 $args = func_get_args();
1316 array_shift( $args );
1319 $sql = $this->fillPrepared( $prepared['query'], $args );
1321 return $this->query( $sql, $prepared['func'] );
1325 * For faking prepared SQL statements on DBs that don't support it directly.
1327 * @param string $preparedQuery A 'preparable' SQL statement
1328 * @param array $args Array of Arguments to fill it with
1329 * @return string Executable SQL
1331 public function fillPrepared( $preparedQuery, $args ) {
1333 $this->preparedArgs
=& $args;
1335 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1336 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1340 * preg_callback func for fillPrepared()
1341 * The arguments should be in $this->preparedArgs and must not be touched
1342 * while we're doing this.
1344 * @param array $matches
1345 * @throws DBUnexpectedError
1348 protected function fillPreparedArg( $matches ) {
1349 switch ( $matches[1] ) {
1358 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1360 switch ( $matches[1] ) {
1362 return $this->addQuotes( $arg );
1366 # return $this->addQuotes( file_get_contents( $arg ) );
1367 throw new DBUnexpectedError(
1369 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1372 throw new DBUnexpectedError(
1374 'Received invalid match. This should never happen!'
1380 * Free a result object returned by query() or select(). It's usually not
1381 * necessary to call this, just use unset() or let the variable holding
1382 * the result object go out of scope.
1384 * @param mixed $res A SQL result
1386 public function freeResult( $res ) {
1390 * A SELECT wrapper which returns a single field from a single result row.
1392 * Usually throws a DBQueryError on failure. If errors are explicitly
1393 * ignored, returns false on failure.
1395 * If no result rows are returned from the query, false is returned.
1397 * @param string|array $table Table name. See DatabaseBase::select() for details.
1398 * @param string $var The field name to select. This must be a valid SQL
1399 * fragment: do not use unvalidated user input.
1400 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1401 * @param string $fname The function name of the caller.
1402 * @param string|array $options The query options. See DatabaseBase::select() for details.
1404 * @return bool|mixed The value from the field, or false on failure.
1406 public function selectField(
1407 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1409 if ( $var === '*' ) { // sanity
1410 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1413 if ( !is_array( $options ) ) {
1414 $options = array( $options );
1417 $options['LIMIT'] = 1;
1419 $res = $this->select( $table, $var, $cond, $fname, $options );
1420 if ( $res === false ||
!$this->numRows( $res ) ) {
1424 $row = $this->fetchRow( $res );
1426 if ( $row !== false ) {
1427 return reset( $row );
1434 * A SELECT wrapper which returns a list of single field values from result rows.
1436 * Usually throws a DBQueryError on failure. If errors are explicitly
1437 * ignored, returns false on failure.
1439 * If no result rows are returned from the query, false is returned.
1441 * @param string|array $table Table name. See DatabaseBase::select() for details.
1442 * @param string $var The field name to select. This must be a valid SQL
1443 * fragment: do not use unvalidated user input.
1444 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1445 * @param string $fname The function name of the caller.
1446 * @param string|array $options The query options. See DatabaseBase::select() for details.
1448 * @return bool|array The values from the field, or false on failure
1451 public function selectFieldValues(
1452 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1454 if ( $var === '*' ) { // sanity
1455 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1458 if ( !is_array( $options ) ) {
1459 $options = array( $options );
1462 $res = $this->select( $table, $var, $cond, $fname, $options );
1463 if ( $res === false ) {
1468 foreach ( $res as $row ) {
1469 $values[] = $row->$var;
1476 * Returns an optional USE INDEX clause to go after the table, and a
1477 * string to go at the end of the query.
1479 * @param array $options Associative array of options to be turned into
1480 * an SQL query, valid keys are listed in the function.
1482 * @see DatabaseBase::select()
1484 public function makeSelectOptions( $options ) {
1485 $preLimitTail = $postLimitTail = '';
1488 $noKeyOptions = array();
1490 foreach ( $options as $key => $option ) {
1491 if ( is_numeric( $key ) ) {
1492 $noKeyOptions[$option] = true;
1496 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1498 $preLimitTail .= $this->makeOrderBy( $options );
1500 // if (isset($options['LIMIT'])) {
1501 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1502 // isset($options['OFFSET']) ? $options['OFFSET']
1506 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1507 $postLimitTail .= ' FOR UPDATE';
1510 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1511 $postLimitTail .= ' LOCK IN SHARE MODE';
1514 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1515 $startOpts .= 'DISTINCT';
1518 # Various MySQL extensions
1519 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1520 $startOpts .= ' /*! STRAIGHT_JOIN */';
1523 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1524 $startOpts .= ' HIGH_PRIORITY';
1527 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1528 $startOpts .= ' SQL_BIG_RESULT';
1531 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1532 $startOpts .= ' SQL_BUFFER_RESULT';
1535 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1536 $startOpts .= ' SQL_SMALL_RESULT';
1539 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1540 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1543 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1544 $startOpts .= ' SQL_CACHE';
1547 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1548 $startOpts .= ' SQL_NO_CACHE';
1551 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1552 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1557 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1561 * Returns an optional GROUP BY with an optional HAVING
1563 * @param array $options Associative array of options
1565 * @see DatabaseBase::select()
1568 public function makeGroupByWithHaving( $options ) {
1570 if ( isset( $options['GROUP BY'] ) ) {
1571 $gb = is_array( $options['GROUP BY'] )
1572 ?
implode( ',', $options['GROUP BY'] )
1573 : $options['GROUP BY'];
1574 $sql .= ' GROUP BY ' . $gb;
1576 if ( isset( $options['HAVING'] ) ) {
1577 $having = is_array( $options['HAVING'] )
1578 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1579 : $options['HAVING'];
1580 $sql .= ' HAVING ' . $having;
1587 * Returns an optional ORDER BY
1589 * @param array $options Associative array of options
1591 * @see DatabaseBase::select()
1594 public function makeOrderBy( $options ) {
1595 if ( isset( $options['ORDER BY'] ) ) {
1596 $ob = is_array( $options['ORDER BY'] )
1597 ?
implode( ',', $options['ORDER BY'] )
1598 : $options['ORDER BY'];
1600 return ' ORDER BY ' . $ob;
1607 * Execute a SELECT query constructed using the various parameters provided.
1608 * See below for full details of the parameters.
1610 * @param string|array $table Table name
1611 * @param string|array $vars Field names
1612 * @param string|array $conds Conditions
1613 * @param string $fname Caller function name
1614 * @param array $options Query options
1615 * @param array $join_conds Join conditions
1618 * @param string|array $table
1620 * May be either an array of table names, or a single string holding a table
1621 * name. If an array is given, table aliases can be specified, for example:
1623 * array( 'a' => 'user' )
1625 * This includes the user table in the query, with the alias "a" available
1626 * for use in field names (e.g. a.user_name).
1628 * All of the table names given here are automatically run through
1629 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1630 * added, and various other table name mappings to be performed.
1633 * @param string|array $vars
1635 * May be either a field name or an array of field names. The field names
1636 * can be complete fragments of SQL, for direct inclusion into the SELECT
1637 * query. If an array is given, field aliases can be specified, for example:
1639 * array( 'maxrev' => 'MAX(rev_id)' )
1641 * This includes an expression with the alias "maxrev" in the query.
1643 * If an expression is given, care must be taken to ensure that it is
1647 * @param string|array $conds
1649 * May be either a string containing a single condition, or an array of
1650 * conditions. If an array is given, the conditions constructed from each
1651 * element are combined with AND.
1653 * Array elements may take one of two forms:
1655 * - Elements with a numeric key are interpreted as raw SQL fragments.
1656 * - Elements with a string key are interpreted as equality conditions,
1657 * where the key is the field name.
1658 * - If the value of such an array element is a scalar (such as a
1659 * string), it will be treated as data and thus quoted appropriately.
1660 * If it is null, an IS NULL clause will be added.
1661 * - If the value is an array, an IN (...) clause will be constructed
1662 * from its non-null elements, and an IS NULL clause will be added
1663 * if null is present, such that the field may match any of the
1664 * elements in the array. The non-null elements will be quoted.
1666 * Note that expressions are often DBMS-dependent in their syntax.
1667 * DBMS-independent wrappers are provided for constructing several types of
1668 * expression commonly used in condition queries. See:
1669 * - DatabaseBase::buildLike()
1670 * - DatabaseBase::conditional()
1673 * @param string|array $options
1675 * Optional: Array of query options. Boolean options are specified by
1676 * including them in the array as a string value with a numeric key, for
1679 * array( 'FOR UPDATE' )
1681 * The supported options are:
1683 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1684 * with LIMIT can theoretically be used for paging through a result set,
1685 * but this is discouraged in MediaWiki for performance reasons.
1687 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1688 * and then the first rows are taken until the limit is reached. LIMIT
1689 * is applied to a result set after OFFSET.
1691 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1692 * changed until the next COMMIT.
1694 * - DISTINCT: Boolean: return only unique result rows.
1696 * - GROUP BY: May be either an SQL fragment string naming a field or
1697 * expression to group by, or an array of such SQL fragments.
1699 * - HAVING: May be either an string containing a HAVING clause or an array of
1700 * conditions building the HAVING clause. If an array is given, the conditions
1701 * constructed from each element are combined with AND.
1703 * - ORDER BY: May be either an SQL fragment giving a field name or
1704 * expression to order by, or an array of such SQL fragments.
1706 * - USE INDEX: This may be either a string giving the index name to use
1707 * for the query, or an array. If it is an associative array, each key
1708 * gives the table name (or alias), each value gives the index name to
1709 * use for that table. All strings are SQL fragments and so should be
1710 * validated by the caller.
1712 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1713 * instead of SELECT.
1715 * And also the following boolean MySQL extensions, see the MySQL manual
1716 * for documentation:
1718 * - LOCK IN SHARE MODE
1722 * - SQL_BUFFER_RESULT
1723 * - SQL_SMALL_RESULT
1724 * - SQL_CALC_FOUND_ROWS
1729 * @param string|array $join_conds
1731 * Optional associative array of table-specific join conditions. In the
1732 * most common case, this is unnecessary, since the join condition can be
1733 * in $conds. However, it is useful for doing a LEFT JOIN.
1735 * The key of the array contains the table name or alias. The value is an
1736 * array with two elements, numbered 0 and 1. The first gives the type of
1737 * join, the second is an SQL fragment giving the join condition for that
1738 * table. For example:
1740 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1742 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1743 * with no rows in it will be returned. If there was a query error, a
1744 * DBQueryError exception will be thrown, except if the "ignore errors"
1745 * option was set, in which case false will be returned.
1747 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1748 $options = array(), $join_conds = array() ) {
1749 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1751 return $this->query( $sql, $fname );
1755 * The equivalent of DatabaseBase::select() except that the constructed SQL
1756 * is returned, instead of being immediately executed. This can be useful for
1757 * doing UNION queries, where the SQL text of each query is needed. In general,
1758 * however, callers outside of Database classes should just use select().
1760 * @param string|array $table Table name
1761 * @param string|array $vars Field names
1762 * @param string|array $conds Conditions
1763 * @param string $fname Caller function name
1764 * @param string|array $options Query options
1765 * @param string|array $join_conds Join conditions
1767 * @return string SQL query string.
1768 * @see DatabaseBase::select()
1770 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1771 $options = array(), $join_conds = array()
1773 if ( is_array( $vars ) ) {
1774 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1777 $options = (array)$options;
1778 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1779 ?
$options['USE INDEX']
1782 if ( is_array( $table ) ) {
1784 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1785 } elseif ( $table != '' ) {
1786 if ( $table[0] == ' ' ) {
1787 $from = ' FROM ' . $table;
1790 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1796 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1797 $this->makeSelectOptions( $options );
1799 if ( !empty( $conds ) ) {
1800 if ( is_array( $conds ) ) {
1801 $conds = $this->makeList( $conds, LIST_AND
);
1803 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1805 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1808 if ( isset( $options['LIMIT'] ) ) {
1809 $sql = $this->limitResult( $sql, $options['LIMIT'],
1810 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1812 $sql = "$sql $postLimitTail";
1814 if ( isset( $options['EXPLAIN'] ) ) {
1815 $sql = 'EXPLAIN ' . $sql;
1822 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1823 * that a single row object is returned. If the query returns no rows,
1824 * false is returned.
1826 * @param string|array $table Table name
1827 * @param string|array $vars Field names
1828 * @param array $conds Conditions
1829 * @param string $fname Caller function name
1830 * @param string|array $options Query options
1831 * @param array|string $join_conds Join conditions
1833 * @return stdClass|bool
1835 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1836 $options = array(), $join_conds = array()
1838 $options = (array)$options;
1839 $options['LIMIT'] = 1;
1840 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1842 if ( $res === false ) {
1846 if ( !$this->numRows( $res ) ) {
1850 $obj = $this->fetchObject( $res );
1856 * Estimate the number of rows in dataset
1858 * MySQL allows you to estimate the number of rows that would be returned
1859 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1860 * index cardinality statistics, and is notoriously inaccurate, especially
1861 * when large numbers of rows have recently been added or deleted.
1863 * For DBMSs that don't support fast result size estimation, this function
1864 * will actually perform the SELECT COUNT(*).
1866 * Takes the same arguments as DatabaseBase::select().
1868 * @param string $table Table name
1869 * @param string $vars Unused
1870 * @param array|string $conds Filters on the table
1871 * @param string $fname Function name for profiling
1872 * @param array $options Options for select
1873 * @return int Row count
1875 public function estimateRowCount(
1876 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1879 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1882 $row = $this->fetchRow( $res );
1883 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1890 * Get the number of rows in dataset
1892 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
1894 * Takes the same arguments as DatabaseBase::select().
1896 * @param string $table Table name
1897 * @param string $vars Unused
1898 * @param array|string $conds Filters on the table
1899 * @param string $fname Function name for profiling
1900 * @param array $options Options for select
1901 * @return int Row count
1904 public function selectRowCount(
1905 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1908 $sql = $this->selectSQLText( $table, '1', $conds, $fname, $options );
1909 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count" );
1912 $row = $this->fetchRow( $res );
1913 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1920 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1921 * It's only slightly flawed. Don't use for anything important.
1923 * @param string $sql A SQL Query
1927 static function generalizeSQL( $sql ) {
1928 # This does the same as the regexp below would do, but in such a way
1929 # as to avoid crashing php on some large strings.
1930 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1932 $sql = str_replace( "\\\\", '', $sql );
1933 $sql = str_replace( "\\'", '', $sql );
1934 $sql = str_replace( "\\\"", '', $sql );
1935 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1936 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1938 # All newlines, tabs, etc replaced by single space
1939 $sql = preg_replace( '/\s+/', ' ', $sql );
1942 # except the ones surrounded by characters, e.g. l10n
1943 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1944 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1950 * Determines whether a field exists in a table
1952 * @param string $table Table name
1953 * @param string $field Filed to check on that table
1954 * @param string $fname Calling function name (optional)
1955 * @return bool Whether $table has filed $field
1957 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1958 $info = $this->fieldInfo( $table, $field );
1964 * Determines whether an index exists
1965 * Usually throws a DBQueryError on failure
1966 * If errors are explicitly ignored, returns NULL on failure
1968 * @param string $table
1969 * @param string $index
1970 * @param string $fname
1973 public function indexExists( $table, $index, $fname = __METHOD__
) {
1974 if ( !$this->tableExists( $table ) ) {
1978 $info = $this->indexInfo( $table, $index, $fname );
1979 if ( is_null( $info ) ) {
1982 return $info !== false;
1987 * Query whether a given table exists
1989 * @param string $table
1990 * @param string $fname
1993 public function tableExists( $table, $fname = __METHOD__
) {
1994 $table = $this->tableName( $table );
1995 $old = $this->ignoreErrors( true );
1996 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1997 $this->ignoreErrors( $old );
2003 * Determines if a given index is unique
2005 * @param string $table
2006 * @param string $index
2010 public function indexUnique( $table, $index ) {
2011 $indexInfo = $this->indexInfo( $table, $index );
2013 if ( !$indexInfo ) {
2017 return !$indexInfo[0]->Non_unique
;
2021 * Helper for DatabaseBase::insert().
2023 * @param array $options
2026 protected function makeInsertOptions( $options ) {
2027 return implode( ' ', $options );
2031 * INSERT wrapper, inserts an array into a table.
2035 * - A single associative array. The array keys are the field names, and
2036 * the values are the values to insert. The values are treated as data
2037 * and will be quoted appropriately. If NULL is inserted, this will be
2038 * converted to a database NULL.
2039 * - An array with numeric keys, holding a list of associative arrays.
2040 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2041 * each subarray must be identical to each other, and in the same order.
2043 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2046 * $options is an array of options, with boolean options encoded as values
2047 * with numeric keys, in the same style as $options in
2048 * DatabaseBase::select(). Supported options are:
2050 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
2051 * any rows which cause duplicate key errors are not inserted. It's
2052 * possible to determine how many rows were successfully inserted using
2053 * DatabaseBase::affectedRows().
2055 * @param string $table Table name. This will be passed through
2056 * DatabaseBase::tableName().
2057 * @param array $a Array of rows to insert
2058 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2059 * @param array $options Array of options
2063 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
2064 # No rows to insert, easy just return now
2065 if ( !count( $a ) ) {
2069 $table = $this->tableName( $table );
2071 if ( !is_array( $options ) ) {
2072 $options = array( $options );
2076 if ( isset( $options['fileHandle'] ) ) {
2077 $fh = $options['fileHandle'];
2079 $options = $this->makeInsertOptions( $options );
2081 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
2083 $keys = array_keys( $a[0] );
2086 $keys = array_keys( $a );
2089 $sql = 'INSERT ' . $options .
2090 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
2094 foreach ( $a as $row ) {
2100 $sql .= '(' . $this->makeList( $row ) . ')';
2103 $sql .= '(' . $this->makeList( $a ) . ')';
2106 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
2108 } elseif ( $fh !== null ) {
2112 return (bool)$this->query( $sql, $fname );
2116 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
2118 * @param array $options
2121 protected function makeUpdateOptionsArray( $options ) {
2122 if ( !is_array( $options ) ) {
2123 $options = array( $options );
2128 if ( in_array( 'LOW_PRIORITY', $options ) ) {
2129 $opts[] = $this->lowPriorityOption();
2132 if ( in_array( 'IGNORE', $options ) ) {
2140 * Make UPDATE options for the DatabaseBase::update function
2142 * @param array $options The options passed to DatabaseBase::update
2145 protected function makeUpdateOptions( $options ) {
2146 $opts = $this->makeUpdateOptionsArray( $options );
2148 return implode( ' ', $opts );
2152 * UPDATE wrapper. Takes a condition array and a SET array.
2154 * @param string $table Name of the table to UPDATE. This will be passed through
2155 * DatabaseBase::tableName().
2156 * @param array $values An array of values to SET. For each array element,
2157 * the key gives the field name, and the value gives the data to set
2158 * that field to. The data will be quoted by DatabaseBase::addQuotes().
2159 * @param array $conds An array of conditions (WHERE). See
2160 * DatabaseBase::select() for the details of the format of condition
2161 * arrays. Use '*' to update all rows.
2162 * @param string $fname The function name of the caller (from __METHOD__),
2163 * for logging and profiling.
2164 * @param array $options An array of UPDATE options, can be:
2165 * - IGNORE: Ignore unique key conflicts
2166 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
2169 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
2170 $table = $this->tableName( $table );
2171 $opts = $this->makeUpdateOptions( $options );
2172 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
2174 if ( $conds !== array() && $conds !== '*' ) {
2175 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
2178 return $this->query( $sql, $fname );
2182 * Makes an encoded list of strings from an array
2184 * @param array $a Containing the data
2185 * @param int $mode Constant
2186 * - LIST_COMMA: Comma separated, no field names
2187 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2188 * documentation for $conds in DatabaseBase::select().
2189 * - LIST_OR: ORed WHERE clause (without the WHERE)
2190 * - LIST_SET: Comma separated with field names, like a SET clause
2191 * - LIST_NAMES: Comma separated field names
2192 * @throws MWException|DBUnexpectedError
2195 public function makeList( $a, $mode = LIST_COMMA
) {
2196 if ( !is_array( $a ) ) {
2197 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2203 foreach ( $a as $field => $value ) {
2205 if ( $mode == LIST_AND
) {
2207 } elseif ( $mode == LIST_OR
) {
2216 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
2217 $list .= "($value)";
2218 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
2220 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
2221 // Remove null from array to be handled separately if found
2222 $includeNull = false;
2223 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2224 $includeNull = true;
2225 unset( $value[$nullKey] );
2227 if ( count( $value ) == 0 && !$includeNull ) {
2228 throw new MWException( __METHOD__
. ": empty input for field $field" );
2229 } elseif ( count( $value ) == 0 ) {
2230 // only check if $field is null
2231 $list .= "$field IS NULL";
2233 // IN clause contains at least one valid element
2234 if ( $includeNull ) {
2235 // Group subconditions to ensure correct precedence
2238 if ( count( $value ) == 1 ) {
2239 // Special-case single values, as IN isn't terribly efficient
2240 // Don't necessarily assume the single key is 0; we don't
2241 // enforce linear numeric ordering on other arrays here.
2242 $value = array_values( $value );
2243 $list .= $field . " = " . $this->addQuotes( $value[0] );
2245 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2247 // if null present in array, append IS NULL
2248 if ( $includeNull ) {
2249 $list .= " OR $field IS NULL)";
2252 } elseif ( $value === null ) {
2253 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
2254 $list .= "$field IS ";
2255 } elseif ( $mode == LIST_SET
) {
2256 $list .= "$field = ";
2260 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
2261 $list .= "$field = ";
2263 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
2271 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2272 * The keys on each level may be either integers or strings.
2274 * @param array $data Organized as 2-d
2275 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2276 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2277 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2278 * @return string|bool SQL fragment, or false if no items in array
2280 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2283 foreach ( $data as $base => $sub ) {
2284 if ( count( $sub ) ) {
2285 $conds[] = $this->makeList(
2286 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2292 return $this->makeList( $conds, LIST_OR
);
2294 // Nothing to search for...
2300 * Return aggregated value alias
2302 * @param array $valuedata
2303 * @param string $valuename
2307 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2312 * @param string $field
2315 public function bitNot( $field ) {
2320 * @param string $fieldLeft
2321 * @param string $fieldRight
2324 public function bitAnd( $fieldLeft, $fieldRight ) {
2325 return "($fieldLeft & $fieldRight)";
2329 * @param string $fieldLeft
2330 * @param string $fieldRight
2333 public function bitOr( $fieldLeft, $fieldRight ) {
2334 return "($fieldLeft | $fieldRight)";
2338 * Build a concatenation list to feed into a SQL query
2339 * @param array $stringList List of raw SQL expressions; caller is
2340 * responsible for any quoting
2343 public function buildConcat( $stringList ) {
2344 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2348 * Build a GROUP_CONCAT or equivalent statement for a query.
2350 * This is useful for combining a field for several rows into a single string.
2351 * NULL values will not appear in the output, duplicated values will appear,
2352 * and the resulting delimiter-separated values have no defined sort order.
2353 * Code using the results may need to use the PHP unique() or sort() methods.
2355 * @param string $delim Glue to bind the results together
2356 * @param string|array $table Table name
2357 * @param string $field Field name
2358 * @param string|array $conds Conditions
2359 * @param string|array $join_conds Join conditions
2360 * @return string SQL text
2363 public function buildGroupConcatField(
2364 $delim, $table, $field, $conds = '', $join_conds = array()
2366 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2368 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2372 * Change the current database
2374 * @todo Explain what exactly will fail if this is not overridden.
2378 * @return bool Success or failure
2380 public function selectDB( $db ) {
2381 # Stub. Shouldn't cause serious problems if it's not overridden, but
2382 # if your database engine supports a concept similar to MySQL's
2383 # databases you may as well.
2384 $this->mDBname
= $db;
2390 * Get the current DB name
2393 public function getDBname() {
2394 return $this->mDBname
;
2398 * Get the server hostname or IP address
2401 public function getServer() {
2402 return $this->mServer
;
2406 * Format a table name ready for use in constructing an SQL query
2408 * This does two important things: it quotes the table names to clean them up,
2409 * and it adds a table prefix if only given a table name with no quotes.
2411 * All functions of this object which require a table name call this function
2412 * themselves. Pass the canonical name to such functions. This is only needed
2413 * when calling query() directly.
2415 * @param string $name Database table name
2416 * @param string $format One of:
2417 * quoted - Automatically pass the table name through addIdentifierQuotes()
2418 * so that it can be used in a query.
2419 * raw - Do not add identifier quotes to the table name
2420 * @return string Full database name
2422 public function tableName( $name, $format = 'quoted' ) {
2423 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2424 # Skip the entire process when we have a string quoted on both ends.
2425 # Note that we check the end so that we will still quote any use of
2426 # use of `database`.table. But won't break things if someone wants
2427 # to query a database table with a dot in the name.
2428 if ( $this->isQuotedIdentifier( $name ) ) {
2432 # Lets test for any bits of text that should never show up in a table
2433 # name. Basically anything like JOIN or ON which are actually part of
2434 # SQL queries, but may end up inside of the table value to combine
2435 # sql. Such as how the API is doing.
2436 # Note that we use a whitespace test rather than a \b test to avoid
2437 # any remote case where a word like on may be inside of a table name
2438 # surrounded by symbols which may be considered word breaks.
2439 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2443 # Split database and table into proper variables.
2444 # We reverse the explode so that database.table and table both output
2445 # the correct table.
2446 $dbDetails = explode( '.', $name, 3 );
2447 if ( count( $dbDetails ) == 3 ) {
2448 list( $database, $schema, $table ) = $dbDetails;
2449 # We don't want any prefix added in this case
2451 } elseif ( count( $dbDetails ) == 2 ) {
2452 list( $database, $table ) = $dbDetails;
2453 # We don't want any prefix added in this case
2454 # In dbs that support it, $database may actually be the schema
2455 # but that doesn't affect any of the functionality here
2459 list( $table ) = $dbDetails;
2460 if ( $wgSharedDB !== null # We have a shared database
2461 && $this->mForeign
== false # We're not working on a foreign database
2462 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2463 && in_array( $table, $wgSharedTables ) # A shared table is selected
2465 $database = $wgSharedDB;
2466 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
2467 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
2470 $schema = $this->mSchema
; # Default schema
2471 $prefix = $this->mTablePrefix
; # Default prefix
2475 # Quote $table and apply the prefix if not quoted.
2476 # $tableName might be empty if this is called from Database::replaceVars()
2477 $tableName = "{$prefix}{$table}";
2478 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2479 $tableName = $this->addIdentifierQuotes( $tableName );
2482 # Quote $schema and merge it with the table name if needed
2483 if ( $schema !== null ) {
2484 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2485 $schema = $this->addIdentifierQuotes( $schema );
2487 $tableName = $schema . '.' . $tableName;
2490 # Quote $database and merge it with the table name if needed
2491 if ( $database !== null ) {
2492 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2493 $database = $this->addIdentifierQuotes( $database );
2495 $tableName = $database . '.' . $tableName;
2502 * Fetch a number of table names into an array
2503 * This is handy when you need to construct SQL for joins
2506 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2507 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2508 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2512 public function tableNames() {
2513 $inArray = func_get_args();
2516 foreach ( $inArray as $name ) {
2517 $retVal[$name] = $this->tableName( $name );
2524 * Fetch a number of table names into an zero-indexed numerical array
2525 * This is handy when you need to construct SQL for joins
2528 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2529 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2530 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2534 public function tableNamesN() {
2535 $inArray = func_get_args();
2538 foreach ( $inArray as $name ) {
2539 $retVal[] = $this->tableName( $name );
2546 * Get an aliased table name
2547 * e.g. tableName AS newTableName
2549 * @param string $name Table name, see tableName()
2550 * @param string|bool $alias Alias (optional)
2551 * @return string SQL name for aliased table. Will not alias a table to its own name
2553 public function tableNameWithAlias( $name, $alias = false ) {
2554 if ( !$alias ||
$alias == $name ) {
2555 return $this->tableName( $name );
2557 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2562 * Gets an array of aliased table names
2564 * @param array $tables Array( [alias] => table )
2565 * @return string[] See tableNameWithAlias()
2567 public function tableNamesWithAlias( $tables ) {
2569 foreach ( $tables as $alias => $table ) {
2570 if ( is_numeric( $alias ) ) {
2573 $retval[] = $this->tableNameWithAlias( $table, $alias );
2580 * Get an aliased field name
2581 * e.g. fieldName AS newFieldName
2583 * @param string $name Field name
2584 * @param string|bool $alias Alias (optional)
2585 * @return string SQL name for aliased field. Will not alias a field to its own name
2587 public function fieldNameWithAlias( $name, $alias = false ) {
2588 if ( !$alias ||
(string)$alias === (string)$name ) {
2591 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2596 * Gets an array of aliased field names
2598 * @param array $fields Array( [alias] => field )
2599 * @return string[] See fieldNameWithAlias()
2601 public function fieldNamesWithAlias( $fields ) {
2603 foreach ( $fields as $alias => $field ) {
2604 if ( is_numeric( $alias ) ) {
2607 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2614 * Get the aliased table name clause for a FROM clause
2615 * which might have a JOIN and/or USE INDEX clause
2617 * @param array $tables ( [alias] => table )
2618 * @param array $use_index Same as for select()
2619 * @param array $join_conds Same as for select()
2622 protected function tableNamesWithUseIndexOrJOIN(
2623 $tables, $use_index = array(), $join_conds = array()
2627 $use_index = (array)$use_index;
2628 $join_conds = (array)$join_conds;
2630 foreach ( $tables as $alias => $table ) {
2631 if ( !is_string( $alias ) ) {
2632 // No alias? Set it equal to the table name
2635 // Is there a JOIN clause for this table?
2636 if ( isset( $join_conds[$alias] ) ) {
2637 list( $joinType, $conds ) = $join_conds[$alias];
2638 $tableClause = $joinType;
2639 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2640 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2641 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2643 $tableClause .= ' ' . $use;
2646 $on = $this->makeList( (array)$conds, LIST_AND
);
2648 $tableClause .= ' ON (' . $on . ')';
2651 $retJOIN[] = $tableClause;
2652 } elseif ( isset( $use_index[$alias] ) ) {
2653 // Is there an INDEX clause for this table?
2654 $tableClause = $this->tableNameWithAlias( $table, $alias );
2655 $tableClause .= ' ' . $this->useIndexClause(
2656 implode( ',', (array)$use_index[$alias] )
2659 $ret[] = $tableClause;
2661 $tableClause = $this->tableNameWithAlias( $table, $alias );
2663 $ret[] = $tableClause;
2667 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2668 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2669 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2671 // Compile our final table clause
2672 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2676 * Get the name of an index in a given table.
2678 * @protected Don't use outside of DatabaseBase and childs
2679 * @param string $index
2682 public function indexName( $index ) {
2683 // @FIXME: Make this protected once we move away from PHP 5.3
2684 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
2686 // Backwards-compatibility hack
2688 'ar_usertext_timestamp' => 'usertext_timestamp',
2689 'un_user_id' => 'user_id',
2690 'un_user_ip' => 'user_ip',
2693 if ( isset( $renamed[$index] ) ) {
2694 return $renamed[$index];
2701 * Adds quotes and backslashes.
2703 * @param string|Blob $s
2706 public function addQuotes( $s ) {
2707 if ( $s instanceof Blob
) {
2710 if ( $s === null ) {
2713 # This will also quote numeric values. This should be harmless,
2714 # and protects against weird problems that occur when they really
2715 # _are_ strings such as article titles and string->number->string
2716 # conversion is not 1:1.
2717 return "'" . $this->strencode( $s ) . "'";
2722 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2723 * MySQL uses `backticks` while basically everything else uses double quotes.
2724 * Since MySQL is the odd one out here the double quotes are our generic
2725 * and we implement backticks in DatabaseMysql.
2730 public function addIdentifierQuotes( $s ) {
2731 return '"' . str_replace( '"', '""', $s ) . '"';
2735 * Returns if the given identifier looks quoted or not according to
2736 * the database convention for quoting identifiers .
2738 * @param string $name
2741 public function isQuotedIdentifier( $name ) {
2742 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2749 protected function escapeLikeInternal( $s ) {
2750 return addcslashes( $s, '\%_' );
2754 * LIKE statement wrapper, receives a variable-length argument list with
2755 * parts of pattern to match containing either string literals that will be
2756 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2757 * the function could be provided with an array of aforementioned
2760 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2761 * a LIKE clause that searches for subpages of 'My page title'.
2763 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2764 * $query .= $dbr->buildLike( $pattern );
2767 * @return string Fully built LIKE statement
2769 public function buildLike() {
2770 $params = func_get_args();
2772 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2773 $params = $params[0];
2778 foreach ( $params as $value ) {
2779 if ( $value instanceof LikeMatch
) {
2780 $s .= $value->toString();
2782 $s .= $this->escapeLikeInternal( $value );
2786 return " LIKE {$this->addQuotes( $s )} ";
2790 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2794 public function anyChar() {
2795 return new LikeMatch( '_' );
2799 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2803 public function anyString() {
2804 return new LikeMatch( '%' );
2808 * Returns an appropriately quoted sequence value for inserting a new row.
2809 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2810 * subclass will return an integer, and save the value for insertId()
2812 * Any implementation of this function should *not* involve reusing
2813 * sequence numbers created for rolled-back transactions.
2814 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2815 * @param string $seqName
2818 public function nextSequenceValue( $seqName ) {
2823 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2824 * is only needed because a) MySQL must be as efficient as possible due to
2825 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2826 * which index to pick. Anyway, other databases might have different
2827 * indexes on a given table. So don't bother overriding this unless you're
2829 * @param string $index
2832 public function useIndexClause( $index ) {
2837 * REPLACE query wrapper.
2839 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2840 * except that when there is a duplicate key error, the old row is deleted
2841 * and the new row is inserted in its place.
2843 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2844 * perform the delete, we need to know what the unique indexes are so that
2845 * we know how to find the conflicting rows.
2847 * It may be more efficient to leave off unique indexes which are unlikely
2848 * to collide. However if you do this, you run the risk of encountering
2849 * errors which wouldn't have occurred in MySQL.
2851 * @param string $table The table to replace the row(s) in.
2852 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2853 * a field name or an array of field names
2854 * @param array $rows Can be either a single row to insert, or multiple rows,
2855 * in the same format as for DatabaseBase::insert()
2856 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2858 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2859 $quotedTable = $this->tableName( $table );
2861 if ( count( $rows ) == 0 ) {
2866 if ( !is_array( reset( $rows ) ) ) {
2867 $rows = array( $rows );
2870 foreach ( $rows as $row ) {
2871 # Delete rows which collide
2872 if ( $uniqueIndexes ) {
2873 $sql = "DELETE FROM $quotedTable WHERE ";
2875 foreach ( $uniqueIndexes as $index ) {
2882 if ( is_array( $index ) ) {
2884 foreach ( $index as $col ) {
2890 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2893 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2897 $this->query( $sql, $fname );
2900 # Now insert the row
2901 $this->insert( $table, $row, $fname );
2906 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2909 * @param string $table Table name
2910 * @param array|string $rows Row(s) to insert
2911 * @param string $fname Caller function name
2913 * @return ResultWrapper
2915 protected function nativeReplace( $table, $rows, $fname ) {
2916 $table = $this->tableName( $table );
2919 if ( !is_array( reset( $rows ) ) ) {
2920 $rows = array( $rows );
2923 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2926 foreach ( $rows as $row ) {
2933 $sql .= '(' . $this->makeList( $row ) . ')';
2936 return $this->query( $sql, $fname );
2940 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2942 * This updates any conflicting rows (according to the unique indexes) using
2943 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2945 * $rows may be either:
2946 * - A single associative array. The array keys are the field names, and
2947 * the values are the values to insert. The values are treated as data
2948 * and will be quoted appropriately. If NULL is inserted, this will be
2949 * converted to a database NULL.
2950 * - An array with numeric keys, holding a list of associative arrays.
2951 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2952 * each subarray must be identical to each other, and in the same order.
2954 * It may be more efficient to leave off unique indexes which are unlikely
2955 * to collide. However if you do this, you run the risk of encountering
2956 * errors which wouldn't have occurred in MySQL.
2958 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2963 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2964 * @param array $rows A single row or list of rows to insert
2965 * @param array $uniqueIndexes List of single field names or field name tuples
2966 * @param array $set An array of values to SET. For each array element, the
2967 * key gives the field name, and the value gives the data to set that
2968 * field to. The data will be quoted by DatabaseBase::addQuotes().
2969 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2973 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2976 if ( !count( $rows ) ) {
2977 return true; // nothing to do
2980 if ( !is_array( reset( $rows ) ) ) {
2981 $rows = array( $rows );
2984 if ( count( $uniqueIndexes ) ) {
2985 $clauses = array(); // list WHERE clauses that each identify a single row
2986 foreach ( $rows as $row ) {
2987 foreach ( $uniqueIndexes as $index ) {
2988 $index = is_array( $index ) ?
$index : array( $index ); // columns
2989 $rowKey = array(); // unique key to this row
2990 foreach ( $index as $column ) {
2991 $rowKey[$column] = $row[$column];
2993 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2996 $where = array( $this->makeList( $clauses, LIST_OR
) );
3001 $useTrx = !$this->mTrxLevel
;
3003 $this->begin( $fname );
3006 # Update any existing conflicting row(s)
3007 if ( $where !== false ) {
3008 $ok = $this->update( $table, $set, $where, $fname );
3012 # Now insert any non-conflicting row(s)
3013 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
3014 } catch ( Exception
$e ) {
3016 $this->rollback( $fname );
3021 $this->commit( $fname );
3028 * DELETE where the condition is a join.
3030 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
3031 * we use sub-selects
3033 * For safety, an empty $conds will not delete everything. If you want to
3034 * delete all rows where the join condition matches, set $conds='*'.
3036 * DO NOT put the join condition in $conds.
3038 * @param string $delTable The table to delete from.
3039 * @param string $joinTable The other table.
3040 * @param string $delVar The variable to join on, in the first table.
3041 * @param string $joinVar The variable to join on, in the second table.
3042 * @param array $conds Condition array of field names mapped to variables,
3043 * ANDed together in the WHERE clause
3044 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
3045 * @throws DBUnexpectedError
3047 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
3051 throw new DBUnexpectedError( $this,
3052 'DatabaseBase::deleteJoin() called with empty $conds' );
3055 $delTable = $this->tableName( $delTable );
3056 $joinTable = $this->tableName( $joinTable );
3057 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
3058 if ( $conds != '*' ) {
3059 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
3063 $this->query( $sql, $fname );
3067 * Returns the size of a text field, or -1 for "unlimited"
3069 * @param string $table
3070 * @param string $field
3073 public function textFieldSize( $table, $field ) {
3074 $table = $this->tableName( $table );
3075 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
3076 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
3077 $row = $this->fetchObject( $res );
3081 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
3091 * A string to insert into queries to show that they're low-priority, like
3092 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
3093 * string and nothing bad should happen.
3095 * @return string Returns the text of the low priority option if it is
3096 * supported, or a blank string otherwise
3098 public function lowPriorityOption() {
3103 * DELETE query wrapper.
3105 * @param array $table Table name
3106 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
3107 * for the format. Use $conds == "*" to delete all rows
3108 * @param string $fname Name of the calling function
3109 * @throws DBUnexpectedError
3110 * @return bool|ResultWrapper
3112 public function delete( $table, $conds, $fname = __METHOD__
) {
3114 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
3117 $table = $this->tableName( $table );
3118 $sql = "DELETE FROM $table";
3120 if ( $conds != '*' ) {
3121 if ( is_array( $conds ) ) {
3122 $conds = $this->makeList( $conds, LIST_AND
);
3124 $sql .= ' WHERE ' . $conds;
3127 return $this->query( $sql, $fname );
3131 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
3132 * into another table.
3134 * @param string $destTable The table name to insert into
3135 * @param string|array $srcTable May be either a table name, or an array of table names
3136 * to include in a join.
3138 * @param array $varMap Must be an associative array of the form
3139 * array( 'dest1' => 'source1', ...). Source items may be literals
3140 * rather than field names, but strings should be quoted with
3141 * DatabaseBase::addQuotes()
3143 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
3144 * the details of the format of condition arrays. May be "*" to copy the
3147 * @param string $fname The function name of the caller, from __METHOD__
3149 * @param array $insertOptions Options for the INSERT part of the query, see
3150 * DatabaseBase::insert() for details.
3151 * @param array $selectOptions Options for the SELECT part of the query, see
3152 * DatabaseBase::select() for details.
3154 * @return ResultWrapper
3156 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
3157 $fname = __METHOD__
,
3158 $insertOptions = array(), $selectOptions = array()
3160 $destTable = $this->tableName( $destTable );
3162 if ( !is_array( $insertOptions ) ) {
3163 $insertOptions = array( $insertOptions );
3166 $insertOptions = $this->makeInsertOptions( $insertOptions );
3168 if ( !is_array( $selectOptions ) ) {
3169 $selectOptions = array( $selectOptions );
3172 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
3174 if ( is_array( $srcTable ) ) {
3175 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
3177 $srcTable = $this->tableName( $srcTable );
3180 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
3181 " SELECT $startOpts " . implode( ',', $varMap ) .
3182 " FROM $srcTable $useIndex ";
3184 if ( $conds != '*' ) {
3185 if ( is_array( $conds ) ) {
3186 $conds = $this->makeList( $conds, LIST_AND
);
3188 $sql .= " WHERE $conds";
3191 $sql .= " $tailOpts";
3193 return $this->query( $sql, $fname );
3197 * Construct a LIMIT query with optional offset. This is used for query
3198 * pages. The SQL should be adjusted so that only the first $limit rows
3199 * are returned. If $offset is provided as well, then the first $offset
3200 * rows should be discarded, and the next $limit rows should be returned.
3201 * If the result of the query is not ordered, then the rows to be returned
3202 * are theoretically arbitrary.
3204 * $sql is expected to be a SELECT, if that makes a difference.
3206 * The version provided by default works in MySQL and SQLite. It will very
3207 * likely need to be overridden for most other DBMSes.
3209 * @param string $sql SQL query we will append the limit too
3210 * @param int $limit The SQL limit
3211 * @param int|bool $offset The SQL offset (default false)
3212 * @throws DBUnexpectedError
3215 public function limitResult( $sql, $limit, $offset = false ) {
3216 if ( !is_numeric( $limit ) ) {
3217 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3220 return "$sql LIMIT "
3221 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3226 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3227 * within the UNION construct.
3230 public function unionSupportsOrderAndLimit() {
3231 return true; // True for almost every DB supported
3235 * Construct a UNION query
3236 * This is used for providing overload point for other DB abstractions
3237 * not compatible with the MySQL syntax.
3238 * @param array $sqls SQL statements to combine
3239 * @param bool $all Use UNION ALL
3240 * @return string SQL fragment
3242 public function unionQueries( $sqls, $all ) {
3243 $glue = $all ?
') UNION ALL (' : ') UNION (';
3245 return '(' . implode( $glue, $sqls ) . ')';
3249 * Returns an SQL expression for a simple conditional. This doesn't need
3250 * to be overridden unless CASE isn't supported in your DBMS.
3252 * @param string|array $cond SQL expression which will result in a boolean value
3253 * @param string $trueVal SQL expression to return if true
3254 * @param string $falseVal SQL expression to return if false
3255 * @return string SQL fragment
3257 public function conditional( $cond, $trueVal, $falseVal ) {
3258 if ( is_array( $cond ) ) {
3259 $cond = $this->makeList( $cond, LIST_AND
);
3262 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3266 * Returns a comand for str_replace function in SQL query.
3267 * Uses REPLACE() in MySQL
3269 * @param string $orig Column to modify
3270 * @param string $old Column to seek
3271 * @param string $new Column to replace with
3275 public function strreplace( $orig, $old, $new ) {
3276 return "REPLACE({$orig}, {$old}, {$new})";
3280 * Determines how long the server has been up
3285 public function getServerUptime() {
3290 * Determines if the last failure was due to a deadlock
3295 public function wasDeadlock() {
3300 * Determines if the last failure was due to a lock timeout
3305 public function wasLockTimeout() {
3310 * Determines if the last query error was something that should be dealt
3311 * with by pinging the connection and reissuing the query.
3316 public function wasErrorReissuable() {
3321 * Determines if the last failure was due to the database being read-only.
3326 public function wasReadOnlyError() {
3331 * Perform a deadlock-prone transaction.
3333 * This function invokes a callback function to perform a set of write
3334 * queries. If a deadlock occurs during the processing, the transaction
3335 * will be rolled back and the callback function will be called again.
3338 * $dbw->deadlockLoop( callback, ... );
3340 * Extra arguments are passed through to the specified callback function.
3342 * Returns whatever the callback function returned on its successful,
3343 * iteration, or false on error, for example if the retry limit was
3348 public function deadlockLoop() {
3349 $args = func_get_args();
3350 $function = array_shift( $args );
3351 $tries = self
::DEADLOCK_TRIES
;
3352 if ( is_array( $function ) ) {
3353 $fname = $function[0];
3358 $this->begin( __METHOD__
);
3363 $retVal = call_user_func_array( $function, $args );
3365 } catch ( DBQueryError
$e ) {
3366 $error = $this->lastError();
3367 $errno = $this->lastErrno();
3368 $sql = $this->lastQuery();
3369 if ( $this->wasDeadlock() ) {
3370 // Retry after a randomized delay
3371 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3373 // Throw the error back up
3377 } while ( --$tries > 0 );
3379 if ( $tries <= 0 ) {
3380 // Too many deadlocks; give up
3381 $this->rollback( __METHOD__
);
3384 $this->commit( __METHOD__
);
3391 * Wait for the slave to catch up to a given master position.
3393 * @param DBMasterPos $pos
3394 * @param int $timeout The maximum number of seconds to wait for
3396 * @return int Zero if the slave was past that position already,
3397 * greater than zero if we waited for some period of time, less than
3398 * zero if we timed out.
3400 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3401 # Real waits are implemented in the subclass.
3406 * Get the replication position of this slave
3408 * @return DBMasterPos|bool False if this is not a slave.
3410 public function getSlavePos() {
3416 * Get the position of this master
3418 * @return DBMasterPos|bool False if this is not a master
3420 public function getMasterPos() {
3426 * Run an anonymous function as soon as there is no transaction pending.
3427 * If there is a transaction and it is rolled back, then the callback is cancelled.
3428 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3429 * Callbacks must commit any transactions that they begin.
3431 * This is useful for updates to different systems or when separate transactions are needed.
3432 * For example, one might want to enqueue jobs into a system outside the database, but only
3433 * after the database is updated so that the jobs will see the data when they actually run.
3434 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3436 * @param callable $callback
3439 final public function onTransactionIdle( $callback ) {
3440 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
3441 if ( !$this->mTrxLevel
) {
3442 $this->runOnTransactionIdleCallbacks();
3447 * Run an anonymous function before the current transaction commits or now if there is none.
3448 * If there is a transaction and it is rolled back, then the callback is cancelled.
3449 * Callbacks must not start nor commit any transactions.
3451 * This is useful for updates that easily cause deadlocks if locks are held too long
3452 * but where atomicity is strongly desired for these updates and some related updates.
3454 * @param callable $callback
3457 final public function onTransactionPreCommitOrIdle( $callback ) {
3458 if ( $this->mTrxLevel
) {
3459 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
3461 $this->onTransactionIdle( $callback ); // this will trigger immediately
3466 * Actually any "on transaction idle" callbacks.
3470 protected function runOnTransactionIdleCallbacks() {
3471 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
3473 $e = $ePrior = null; // last exception
3474 do { // callbacks may add callbacks :)
3475 $callbacks = $this->mTrxIdleCallbacks
;
3476 $this->mTrxIdleCallbacks
= array(); // recursion guard
3477 foreach ( $callbacks as $callback ) {
3479 list( $phpCallback ) = $callback;
3480 $this->clearFlag( DBO_TRX
); // make each query its own transaction
3481 call_user_func( $phpCallback );
3482 $this->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
3483 } catch ( Exception
$e ) {
3485 MWExceptionHandler
::logException( $ePrior );
3490 } while ( count( $this->mTrxIdleCallbacks
) );
3492 if ( $e instanceof Exception
) {
3493 throw $e; // re-throw any last exception
3498 * Actually any "on transaction pre-commit" callbacks.
3502 protected function runOnTransactionPreCommitCallbacks() {
3503 $e = $ePrior = null; // last exception
3504 do { // callbacks may add callbacks :)
3505 $callbacks = $this->mTrxPreCommitCallbacks
;
3506 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
3507 foreach ( $callbacks as $callback ) {
3509 list( $phpCallback ) = $callback;
3510 call_user_func( $phpCallback );
3511 } catch ( Exception
$e ) {
3513 MWExceptionHandler
::logException( $ePrior );
3518 } while ( count( $this->mTrxPreCommitCallbacks
) );
3520 if ( $e instanceof Exception
) {
3521 throw $e; // re-throw any last exception
3526 * Begin an atomic section of statements
3528 * If a transaction has been started already, just keep track of the given
3529 * section name to make sure the transaction is not committed pre-maturely.
3530 * This function can be used in layers (with sub-sections), so use a stack
3531 * to keep track of the different atomic sections. If there is no transaction,
3532 * start one implicitly.
3534 * The goal of this function is to create an atomic section of SQL queries
3535 * without having to start a new transaction if it already exists.
3537 * Atomic sections are more strict than transactions. With transactions,
3538 * attempting to begin a new transaction when one is already running results
3539 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3540 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3541 * and any database transactions cannot be began or committed until all atomic
3542 * levels are closed. There is no such thing as implicitly opening or closing
3543 * an atomic section.
3546 * @param string $fname
3549 final public function startAtomic( $fname = __METHOD__
) {
3550 if ( !$this->mTrxLevel
) {
3551 $this->begin( $fname );
3552 $this->mTrxAutomatic
= true;
3553 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3554 // in all changes being in one transaction to keep requests transactional.
3555 if ( !$this->getFlag( DBO_TRX
) ) {
3556 $this->mTrxAutomaticAtomic
= true;
3560 $this->mTrxAtomicLevels
->push( $fname );
3564 * Ends an atomic section of SQL statements
3566 * Ends the next section of atomic SQL statements and commits the transaction
3570 * @see DatabaseBase::startAtomic
3571 * @param string $fname
3574 final public function endAtomic( $fname = __METHOD__
) {
3575 if ( !$this->mTrxLevel
) {
3576 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3578 if ( $this->mTrxAtomicLevels
->isEmpty() ||
3579 $this->mTrxAtomicLevels
->pop() !== $fname
3581 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3584 if ( $this->mTrxAtomicLevels
->isEmpty() && $this->mTrxAutomaticAtomic
) {
3585 $this->commit( $fname, 'flush' );
3590 * Begin a transaction. If a transaction is already in progress,
3591 * that transaction will be committed before the new transaction is started.
3593 * Note that when the DBO_TRX flag is set (which is usually the case for web
3594 * requests, but not for maintenance scripts), any previous database query
3595 * will have started a transaction automatically.
3597 * Nesting of transactions is not supported. Attempts to nest transactions
3598 * will cause a warning, unless the current transaction was started
3599 * automatically because of the DBO_TRX flag.
3601 * @param string $fname
3604 final public function begin( $fname = __METHOD__
) {
3605 global $wgDebugDBTransactions;
3607 if ( $this->mTrxLevel
) { // implicit commit
3608 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3609 // If the current transaction was an automatic atomic one, then we definitely have
3610 // a problem. Same if there is any unclosed atomic level.
3611 throw new DBUnexpectedError( $this,
3612 "Attempted to start explicit transaction when atomic levels are still open."
3614 } elseif ( !$this->mTrxAutomatic
) {
3615 // We want to warn about inadvertently nested begin/commit pairs, but not about
3616 // auto-committing implicit transactions that were started by query() via DBO_TRX
3617 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3618 " performing implicit commit!";
3621 $this->getLogContext( array(
3622 'method' => __METHOD__
,
3627 // if the transaction was automatic and has done write operations,
3628 // log it if $wgDebugDBTransactions is enabled.
3629 if ( $this->mTrxDoneWrites
&& $wgDebugDBTransactions ) {
3630 wfDebug( "$fname: Automatic transaction with writes in progress" .
3631 " (from {$this->mTrxFname}), performing implicit commit!\n"
3636 $this->runOnTransactionPreCommitCallbacks();
3637 $this->doCommit( $fname );
3638 if ( $this->mTrxDoneWrites
) {
3639 $this->mDoneWrites
= microtime( true );
3640 $this->getTransactionProfiler()->transactionWritingOut(
3641 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3643 $this->runOnTransactionIdleCallbacks();
3646 # Avoid fatals if close() was called
3647 if ( !$this->isOpen() ) {
3648 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3651 $this->doBegin( $fname );
3652 $this->mTrxTimestamp
= microtime( true );
3653 $this->mTrxFname
= $fname;
3654 $this->mTrxDoneWrites
= false;
3655 $this->mTrxAutomatic
= false;
3656 $this->mTrxAutomaticAtomic
= false;
3657 $this->mTrxAtomicLevels
= new SplStack
;
3658 $this->mTrxIdleCallbacks
= array();
3659 $this->mTrxPreCommitCallbacks
= array();
3660 $this->mTrxShortId
= wfRandomString( 12 );
3661 $this->mTrxWriteDuration
= 0.0;
3665 * Issues the BEGIN command to the database server.
3667 * @see DatabaseBase::begin()
3668 * @param string $fname
3670 protected function doBegin( $fname ) {
3671 $this->query( 'BEGIN', $fname );
3672 $this->mTrxLevel
= 1;
3676 * Commits a transaction previously started using begin().
3677 * If no transaction is in progress, a warning is issued.
3679 * Nesting of transactions is not supported.
3681 * @param string $fname
3682 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3683 * explicitly committing implicit transactions, or calling commit when no
3684 * transaction is in progress. This will silently break any ongoing
3685 * explicit transaction. Only set the flush flag if you are sure that it
3686 * is safe to ignore these warnings in your context.
3687 * @throws DBUnexpectedError
3689 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3690 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3691 // There are still atomic sections open. This cannot be ignored
3692 throw new DBUnexpectedError(
3694 "Attempted to commit transaction while atomic sections are still open"
3698 if ( $flush === 'flush' ) {
3699 if ( !$this->mTrxLevel
) {
3700 return; // nothing to do
3701 } elseif ( !$this->mTrxAutomatic
) {
3702 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3705 if ( !$this->mTrxLevel
) {
3706 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3707 return; // nothing to do
3708 } elseif ( $this->mTrxAutomatic
) {
3709 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3713 # Avoid fatals if close() was called
3714 if ( !$this->isOpen() ) {
3715 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3718 $this->runOnTransactionPreCommitCallbacks();
3719 $this->doCommit( $fname );
3720 if ( $this->mTrxDoneWrites
) {
3721 $this->mDoneWrites
= microtime( true );
3722 $this->getTransactionProfiler()->transactionWritingOut(
3723 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3725 $this->runOnTransactionIdleCallbacks();
3729 * Issues the COMMIT command to the database server.
3731 * @see DatabaseBase::commit()
3732 * @param string $fname
3734 protected function doCommit( $fname ) {
3735 if ( $this->mTrxLevel
) {
3736 $this->query( 'COMMIT', $fname );
3737 $this->mTrxLevel
= 0;
3742 * Rollback a transaction previously started using begin().
3743 * If no transaction is in progress, a warning is issued.
3745 * No-op on non-transactional databases.
3747 * @param string $fname
3748 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3749 * calling rollback when no transaction is in progress. This will silently
3750 * break any ongoing explicit transaction. Only set the flush flag if you
3751 * are sure that it is safe to ignore these warnings in your context.
3752 * @throws DBUnexpectedError
3753 * @since 1.23 Added $flush parameter
3755 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3756 if ( $flush !== 'flush' ) {
3757 if ( !$this->mTrxLevel
) {
3758 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3759 return; // nothing to do
3760 } elseif ( $this->mTrxAutomatic
) {
3761 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3764 if ( !$this->mTrxLevel
) {
3765 return; // nothing to do
3766 } elseif ( !$this->mTrxAutomatic
) {
3767 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3771 # Avoid fatals if close() was called
3772 if ( !$this->isOpen() ) {
3773 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3776 $this->doRollback( $fname );
3777 $this->mTrxIdleCallbacks
= array(); // cancel
3778 $this->mTrxPreCommitCallbacks
= array(); // cancel
3779 $this->mTrxAtomicLevels
= new SplStack
;
3780 if ( $this->mTrxDoneWrites
) {
3781 $this->getTransactionProfiler()->transactionWritingOut(
3782 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3787 * Issues the ROLLBACK command to the database server.
3789 * @see DatabaseBase::rollback()
3790 * @param string $fname
3792 protected function doRollback( $fname ) {
3793 if ( $this->mTrxLevel
) {
3794 $this->query( 'ROLLBACK', $fname, true );
3795 $this->mTrxLevel
= 0;
3800 * Creates a new table with structure copied from existing table
3801 * Note that unlike most database abstraction functions, this function does not
3802 * automatically append database prefix, because it works at a lower
3803 * abstraction level.
3804 * The table names passed to this function shall not be quoted (this
3805 * function calls addIdentifierQuotes when needed).
3807 * @param string $oldName Name of table whose structure should be copied
3808 * @param string $newName Name of table to be created
3809 * @param bool $temporary Whether the new table should be temporary
3810 * @param string $fname Calling function name
3811 * @throws MWException
3812 * @return bool True if operation was successful
3814 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3817 throw new MWException(
3818 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3822 * List all tables on the database
3824 * @param string $prefix Only show tables with this prefix, e.g. mw_
3825 * @param string $fname Calling function name
3826 * @throws MWException
3828 function listTables( $prefix = null, $fname = __METHOD__
) {
3829 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3833 * Reset the views process cache set by listViews()
3836 final public function clearViewsCache() {
3837 $this->allViews
= null;
3841 * Lists all the VIEWs in the database
3843 * For caching purposes the list of all views should be stored in
3844 * $this->allViews. The process cache can be cleared with clearViewsCache()
3846 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3847 * @param string $fname Name of calling function
3848 * @throws MWException
3851 public function listViews( $prefix = null, $fname = __METHOD__
) {
3852 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3856 * Differentiates between a TABLE and a VIEW
3858 * @param string $name Name of the database-structure to test.
3859 * @throws MWException
3862 public function isView( $name ) {
3863 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3867 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3868 * to the format used for inserting into timestamp fields in this DBMS.
3870 * The result is unquoted, and needs to be passed through addQuotes()
3871 * before it can be included in raw SQL.
3873 * @param string|int $ts
3877 public function timestamp( $ts = 0 ) {
3878 return wfTimestamp( TS_MW
, $ts );
3882 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3883 * to the format used for inserting into timestamp fields in this DBMS. If
3884 * NULL is input, it is passed through, allowing NULL values to be inserted
3885 * into timestamp fields.
3887 * The result is unquoted, and needs to be passed through addQuotes()
3888 * before it can be included in raw SQL.
3890 * @param string|int $ts
3894 public function timestampOrNull( $ts = null ) {
3895 if ( is_null( $ts ) ) {
3898 return $this->timestamp( $ts );
3903 * Take the result from a query, and wrap it in a ResultWrapper if
3904 * necessary. Boolean values are passed through as is, to indicate success
3905 * of write queries or failure.
3907 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3908 * resource, and it was necessary to call this function to convert it to
3909 * a wrapper. Nowadays, raw database objects are never exposed to external
3910 * callers, so this is unnecessary in external code. For compatibility with
3911 * old code, ResultWrapper objects are passed through unaltered.
3913 * @param bool|ResultWrapper|resource $result
3914 * @return bool|ResultWrapper
3916 public function resultObject( $result ) {
3917 if ( empty( $result ) ) {
3919 } elseif ( $result instanceof ResultWrapper
) {
3921 } elseif ( $result === true ) {
3922 // Successful write query
3925 return new ResultWrapper( $this, $result );
3930 * Ping the server and try to reconnect if it there is no connection
3932 * @return bool Success or failure
3934 public function ping() {
3935 # Stub. Not essential to override.
3940 * Get slave lag. Currently supported only by MySQL.
3942 * Note that this function will generate a fatal error on many
3943 * installations. Most callers should use LoadBalancer::safeGetLag()
3946 * @return int Database replication lag in seconds
3948 public function getLag() {
3953 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3957 function maxListLen() {
3962 * Some DBMSs have a special format for inserting into blob fields, they
3963 * don't allow simple quoted strings to be inserted. To insert into such
3964 * a field, pass the data through this function before passing it to
3965 * DatabaseBase::insert().
3970 public function encodeBlob( $b ) {
3975 * Some DBMSs return a special placeholder object representing blob fields
3976 * in result objects. Pass the object through this function to return the
3979 * @param string|Blob $b
3982 public function decodeBlob( $b ) {
3983 if ( $b instanceof Blob
) {
3990 * Override database's default behavior. $options include:
3991 * 'connTimeout' : Set the connection timeout value in seconds.
3992 * May be useful for very long batch queries such as
3993 * full-wiki dumps, where a single query reads out over
3996 * @param array $options
3999 public function setSessionOptions( array $options ) {
4003 * Read and execute SQL commands from a file.
4005 * Returns true on success, error string or exception on failure (depending
4006 * on object's error ignore settings).
4008 * @param string $filename File name to open
4009 * @param bool|callable $lineCallback Optional function called before reading each line
4010 * @param bool|callable $resultCallback Optional function called for each MySQL result
4011 * @param bool|string $fname Calling function name or false if name should be
4012 * generated dynamically using $filename
4013 * @param bool|callable $inputCallback Optional function called for each
4014 * complete line sent
4015 * @throws Exception|MWException
4016 * @return bool|string
4018 public function sourceFile(
4019 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
4021 wfSuppressWarnings();
4022 $fp = fopen( $filename, 'r' );
4023 wfRestoreWarnings();
4025 if ( false === $fp ) {
4026 throw new MWException( "Could not open \"{$filename}\".\n" );
4030 $fname = __METHOD__
. "( $filename )";
4034 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
4035 } catch ( Exception
$e ) {
4046 * Get the full path of a patch file. Originally based on archive()
4047 * from updaters.inc. Keep in mind this always returns a patch, as
4048 * it fails back to MySQL if no DB-specific patch can be found
4050 * @param string $patch The name of the patch, like patch-something.sql
4051 * @return string Full path to patch file
4053 public function patchPath( $patch ) {
4056 $dbType = $this->getType();
4057 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
4058 return "$IP/maintenance/$dbType/archives/$patch";
4060 return "$IP/maintenance/archives/$patch";
4065 * Set variables to be used in sourceFile/sourceStream, in preference to the
4066 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
4067 * all. If it's set to false, $GLOBALS will be used.
4069 * @param bool|array $vars Mapping variable name to value.
4071 public function setSchemaVars( $vars ) {
4072 $this->mSchemaVars
= $vars;
4076 * Read and execute commands from an open file handle.
4078 * Returns true on success, error string or exception on failure (depending
4079 * on object's error ignore settings).
4081 * @param resource $fp File handle
4082 * @param bool|callable $lineCallback Optional function called before reading each query
4083 * @param bool|callable $resultCallback Optional function called for each MySQL result
4084 * @param string $fname Calling function name
4085 * @param bool|callable $inputCallback Optional function called for each complete query sent
4086 * @return bool|string
4088 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
4089 $fname = __METHOD__
, $inputCallback = false
4093 while ( !feof( $fp ) ) {
4094 if ( $lineCallback ) {
4095 call_user_func( $lineCallback );
4098 $line = trim( fgets( $fp ) );
4100 if ( $line == '' ) {
4104 if ( '-' == $line[0] && '-' == $line[1] ) {
4112 $done = $this->streamStatementEnd( $cmd, $line );
4116 if ( $done ||
feof( $fp ) ) {
4117 $cmd = $this->replaceVars( $cmd );
4119 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
4120 $res = $this->query( $cmd, $fname );
4122 if ( $resultCallback ) {
4123 call_user_func( $resultCallback, $res, $this );
4126 if ( false === $res ) {
4127 $err = $this->lastError();
4129 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4140 * Called by sourceStream() to check if we've reached a statement end
4142 * @param string $sql SQL assembled so far
4143 * @param string $newLine New line about to be added to $sql
4144 * @return bool Whether $newLine contains end of the statement
4146 public function streamStatementEnd( &$sql, &$newLine ) {
4147 if ( $this->delimiter
) {
4149 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4150 if ( $newLine != $prev ) {
4159 * Database independent variable replacement. Replaces a set of variables
4160 * in an SQL statement with their contents as given by $this->getSchemaVars().
4162 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4164 * - '{$var}' should be used for text and is passed through the database's
4166 * - `{$var}` should be used for identifiers (e.g. table and database names).
4167 * It is passed through the database's addIdentifierQuotes method which
4168 * can be overridden if the database uses something other than backticks.
4169 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4170 * database's tableName method.
4171 * - / *i* / passes the name that follows through the database's indexName method.
4172 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4173 * its use should be avoided. In 1.24 and older, string encoding was applied.
4175 * @param string $ins SQL statement to replace variables in
4176 * @return string The new SQL statement with variables replaced
4178 protected function replaceVars( $ins ) {
4180 $vars = $this->getSchemaVars();
4181 return preg_replace_callback(
4183 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4184 \'\{\$ (\w+) }\' | # 3. addQuotes
4185 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4186 /\*\$ (\w+) \*/ # 5. leave unencoded
4188 function ( $m ) use ( $that, $vars ) {
4189 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4190 // check for both nonexistent keys *and* the empty string.
4191 if ( isset( $m[1] ) && $m[1] !== '' ) {
4192 if ( $m[1] === 'i' ) {
4193 return $that->indexName( $m[2] );
4195 return $that->tableName( $m[2] );
4197 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4198 return $that->addQuotes( $vars[$m[3]] );
4199 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4200 return $that->addIdentifierQuotes( $vars[$m[4]] );
4201 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4202 return $vars[$m[5]];
4212 * Get schema variables. If none have been set via setSchemaVars(), then
4213 * use some defaults from the current object.
4217 protected function getSchemaVars() {
4218 if ( $this->mSchemaVars
) {
4219 return $this->mSchemaVars
;
4221 return $this->getDefaultSchemaVars();
4226 * Get schema variables to use if none have been set via setSchemaVars().
4228 * Override this in derived classes to provide variables for tables.sql
4229 * and SQL patch files.
4233 protected function getDefaultSchemaVars() {
4238 * Check to see if a named lock is available. This is non-blocking.
4240 * @param string $lockName Name of lock to poll
4241 * @param string $method Name of method calling us
4245 public function lockIsFree( $lockName, $method ) {
4250 * Acquire a named lock
4252 * Abstracted from Filestore::lock() so child classes can implement for
4255 * @param string $lockName Name of lock to aquire
4256 * @param string $method Name of method calling us
4257 * @param int $timeout
4260 public function lock( $lockName, $method, $timeout = 5 ) {
4267 * @param string $lockName Name of lock to release
4268 * @param string $method Name of method calling us
4270 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4271 * by this thread (in which case the lock is not released), and NULL if the named
4272 * lock did not exist
4274 public function unlock( $lockName, $method ) {
4279 * Lock specific tables
4281 * @param array $read Array of tables to lock for read access
4282 * @param array $write Array of tables to lock for write access
4283 * @param string $method Name of caller
4284 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4287 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4292 * Unlock specific tables
4294 * @param string $method The caller
4297 public function unlockTables( $method ) {
4303 * @param string $tableName
4304 * @param string $fName
4305 * @return bool|ResultWrapper
4308 public function dropTable( $tableName, $fName = __METHOD__
) {
4309 if ( !$this->tableExists( $tableName, $fName ) ) {
4312 $sql = "DROP TABLE " . $this->tableName( $tableName );
4313 if ( $this->cascadingDeletes() ) {
4317 return $this->query( $sql, $fName );
4321 * Get search engine class. All subclasses of this need to implement this
4322 * if they wish to use searching.
4326 public function getSearchEngine() {
4327 return 'SearchEngineDummy';
4331 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4332 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4333 * because "i" sorts after all numbers.
4337 public function getInfinity() {
4342 * Encode an expiry time into the DBMS dependent format
4344 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4347 public function encodeExpiry( $expiry ) {
4348 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4349 ?
$this->getInfinity()
4350 : $this->timestamp( $expiry );
4354 * Decode an expiry time into a DBMS independent format
4356 * @param string $expiry DB timestamp field value for expiry
4357 * @param int $format TS_* constant, defaults to TS_MW
4360 public function decodeExpiry( $expiry, $format = TS_MW
) {
4361 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4363 : wfTimestamp( $format, $expiry );
4367 * Allow or deny "big selects" for this session only. This is done by setting
4368 * the sql_big_selects session variable.
4370 * This is a MySQL-specific feature.
4372 * @param bool|string $value True for allow, false for deny, or "default" to
4373 * restore the initial value
4375 public function setBigSelects( $value = true ) {
4383 public function __toString() {
4384 return (string)$this->mConn
;
4388 * Run a few simple sanity checks
4390 public function __destruct() {
4391 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
4392 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4394 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
4396 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
4397 $callers[] = $callbackInfo[1];
4399 $callers = implode( ', ', $callers );
4400 trigger_error( "DB transaction callbacks still pending (from $callers)." );