3 * @defgroup Database Database
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
28 * Base interface for all DBMS-specific code. At a bare minimum, all of the
29 * following must be implemented to support MediaWiki
34 interface DatabaseType
{
36 * Get the type of the DBMS, as it appears in $wgDBtype.
43 * Open a connection to the database. Usually aborts on failure
45 * @param string $server database server host
46 * @param string $user database user name
47 * @param string $password database user password
48 * @param string $dbName database name
50 * @throws DBConnectionError
52 function open( $server, $user, $password, $dbName );
55 * Fetch the next row from the given result object, in object form.
56 * Fields can be retrieved with $row->fieldname, with fields acting like
58 * If no more rows are available, false is returned.
60 * @param $res ResultWrapper|object as returned from DatabaseBase::query(), etc.
62 * @throws DBUnexpectedError Thrown if the database returns an error
64 function fetchObject( $res );
67 * Fetch the next row from the given result object, in associative array
68 * form. Fields are retrieved with $row['fieldname'].
69 * If no more rows are available, false is returned.
71 * @param $res ResultWrapper result object as returned from DatabaseBase::query(), etc.
73 * @throws DBUnexpectedError Thrown if the database returns an error
75 function fetchRow( $res );
78 * Get the number of rows in a result object
80 * @param $res Mixed: A SQL result
83 function numRows( $res );
86 * Get the number of fields in a result object
87 * @see http://www.php.net/mysql_num_fields
89 * @param $res Mixed: A SQL result
92 function numFields( $res );
95 * Get a field name in a result object
96 * @see http://www.php.net/mysql_field_name
98 * @param $res Mixed: A SQL result
102 function fieldName( $res, $n );
105 * Get the inserted value of an auto-increment row
107 * The value inserted should be fetched from nextSequenceValue()
110 * $id = $dbw->nextSequenceValue( 'page_page_id_seq' );
111 * $dbw->insert( 'page', array( 'page_id' => $id ) );
112 * $id = $dbw->insertId();
119 * Change the position of the cursor in a result object
120 * @see http://www.php.net/mysql_data_seek
122 * @param $res Mixed: A SQL result
123 * @param $row Mixed: Either MySQL row or ResultWrapper
125 function dataSeek( $res, $row );
128 * Get the last error number
129 * @see http://www.php.net/mysql_errno
133 function lastErrno();
136 * Get a description of the last error
137 * @see http://www.php.net/mysql_error
141 function lastError();
144 * mysql_fetch_field() wrapper
145 * Returns false if the field doesn't exist
147 * @param string $table table name
148 * @param string $field field name
152 function fieldInfo( $table, $field );
155 * Get information about an index into an object
156 * @param string $table Table name
157 * @param string $index Index name
158 * @param string $fname Calling function name
159 * @return Mixed: Database-specific index description class or false if the index does not exist
161 function indexInfo( $table, $index, $fname = __METHOD__
);
164 * Get the number of rows affected by the last write query
165 * @see http://www.php.net/mysql_affected_rows
169 function affectedRows();
172 * Wrapper for addslashes()
174 * @param string $s to be slashed.
175 * @return string: slashed string.
177 function strencode( $s );
180 * Returns a wikitext link to the DB's website, e.g.,
181 * return "[http://www.mysql.com/ MySQL]";
182 * Should at least contain plain text, if for some reason
183 * your database has no website.
185 * @return string: wikitext of a link to the server software's web site
187 function getSoftwareLink();
190 * A string describing the current software version, like from
191 * mysql_get_server_info().
193 * @return string: Version information from the database server.
195 function getServerVersion();
198 * A string describing the current software version, and possibly
199 * other details in a user-friendly way. Will be listed on Special:Version, etc.
200 * Use getServerVersion() to get machine-friendly information.
202 * @return string: Version information from the database server
204 function getServerInfo();
208 * Interface for classes that implement or wrap DatabaseBase
211 interface IDatabase
{}
214 * Database abstraction object
217 abstract class DatabaseBase
implements IDatabase
, DatabaseType
{
218 /** Number of times to re-try an operation in case of deadlock */
219 const DEADLOCK_TRIES
= 4;
220 /** Minimum time to wait before retry, in microseconds */
221 const DEADLOCK_DELAY_MIN
= 500000;
222 /** Maximum time to wait before retry */
223 const DEADLOCK_DELAY_MAX
= 1500000;
225 # ------------------------------------------------------------------------------
227 # ------------------------------------------------------------------------------
229 protected $mLastQuery = '';
230 protected $mDoneWrites = false;
231 protected $mPHPError = false;
233 protected $mServer, $mUser, $mPassword, $mDBname;
235 protected $mConn = null;
236 protected $mOpened = false;
238 /** @var callable[] */
239 protected $mTrxIdleCallbacks = array();
240 /** @var callable[] */
241 protected $mTrxPreCommitCallbacks = array();
243 protected $mTablePrefix;
246 protected $mTrxLevel = 0;
247 protected $mErrorCount = 0;
248 protected $mLBInfo = array();
249 protected $mFakeSlaveLag = null, $mFakeMaster = false;
250 protected $mDefaultBigSelects = null;
251 protected $mSchemaVars = false;
253 protected $preparedArgs;
255 protected $htmlErrors;
257 protected $delimiter = ';';
260 * Remembers the function name given for starting the most recent transaction via begin().
261 * Used to provide additional context for error reporting.
264 * @see DatabaseBase::mTrxLevel
266 private $mTrxFname = null;
269 * Record if possible write queries were done in the last transaction started
272 * @see DatabaseBase::mTrxLevel
274 private $mTrxDoneWrites = false;
277 * Record if the current transaction was started implicitly due to DBO_TRX being set.
280 * @see DatabaseBase::mTrxLevel
282 private $mTrxAutomatic = false;
285 * Array of levels of atomicity within transactions
289 private $mTrxAtomicLevels;
292 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
296 private $mTrxAutomaticAtomic = false;
300 * @var file handle for upgrade
302 protected $fileHandle = null;
306 * @var Process cache of VIEWs names in the database
308 protected $allViews = null;
310 # ------------------------------------------------------------------------------
312 # ------------------------------------------------------------------------------
313 # These optionally set a variable and return the previous state
316 * A string describing the current software version, and possibly
317 * other details in a user-friendly way. Will be listed on Special:Version, etc.
318 * Use getServerVersion() to get machine-friendly information.
320 * @return string: Version information from the database server
322 public function getServerInfo() {
323 return $this->getServerVersion();
327 * @return string: command delimiter used by this database engine
329 public function getDelimiter() {
330 return $this->delimiter
;
334 * Boolean, controls output of large amounts of debug information.
335 * @param $debug bool|null
336 * - true to enable debugging
337 * - false to disable debugging
338 * - omitted or null to do nothing
340 * @return bool|null previous value of the flag
342 public function debug( $debug = null ) {
343 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
347 * Turns buffering of SQL result sets on (true) or off (false). Default is
350 * Unbuffered queries are very troublesome in MySQL:
352 * - If another query is executed while the first query is being read
353 * out, the first query is killed. This means you can't call normal
354 * MediaWiki functions while you are reading an unbuffered query result
355 * from a normal wfGetDB() connection.
357 * - Unbuffered queries cause the MySQL server to use large amounts of
358 * memory and to hold broad locks which block other queries.
360 * If you want to limit client-side memory, it's almost always better to
361 * split up queries into batches using a LIMIT clause than to switch off
364 * @param $buffer null|bool
366 * @return null|bool The previous value of the flag
368 public function bufferResults( $buffer = null ) {
369 if ( is_null( $buffer ) ) {
370 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
372 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
377 * Turns on (false) or off (true) the automatic generation and sending
378 * of a "we're sorry, but there has been a database error" page on
379 * database errors. Default is on (false). When turned off, the
380 * code should use lastErrno() and lastError() to handle the
381 * situation as appropriate.
383 * Do not use this function outside of the Database classes.
385 * @param $ignoreErrors bool|null
387 * @return bool The previous value of the flag.
389 public function ignoreErrors( $ignoreErrors = null ) {
390 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
394 * Gets or sets the current transaction level.
396 * Historically, transactions were allowed to be "nested". This is no
397 * longer supported, so this function really only returns a boolean.
399 * @param int $level An integer (0 or 1), or omitted to leave it unchanged.
400 * @return int The previous value
402 public function trxLevel( $level = null ) {
403 return wfSetVar( $this->mTrxLevel
, $level );
407 * Get/set the number of errors logged. Only useful when errors are ignored
408 * @param int $count The count to set, or omitted to leave it unchanged.
409 * @return int The error count
411 public function errorCount( $count = null ) {
412 return wfSetVar( $this->mErrorCount
, $count );
416 * Get/set the table prefix.
417 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
418 * @return string The previous table prefix.
420 public function tablePrefix( $prefix = null ) {
421 return wfSetVar( $this->mTablePrefix
, $prefix );
425 * Set the filehandle to copy write statements to.
427 * @param $fh filehandle
429 public function setFileHandle( $fh ) {
430 $this->fileHandle
= $fh;
434 * Get properties passed down from the server info array of the load
437 * @param string $name The entry of the info array to get, or null to get the
440 * @return LoadBalancer|null
442 public function getLBInfo( $name = null ) {
443 if ( is_null( $name ) ) {
444 return $this->mLBInfo
;
446 if ( array_key_exists( $name, $this->mLBInfo
) ) {
447 return $this->mLBInfo
[$name];
455 * Set the LB info array, or a member of it. If called with one parameter,
456 * the LB info array is set to that parameter. If it is called with two
457 * parameters, the member with the given name is set to the given value.
462 public function setLBInfo( $name, $value = null ) {
463 if ( is_null( $value ) ) {
464 $this->mLBInfo
= $name;
466 $this->mLBInfo
[$name] = $value;
471 * Set lag time in seconds for a fake slave
475 public function setFakeSlaveLag( $lag ) {
476 $this->mFakeSlaveLag
= $lag;
480 * Make this connection a fake master
482 * @param $enabled bool
484 public function setFakeMaster( $enabled = true ) {
485 $this->mFakeMaster
= $enabled;
489 * Returns true if this database supports (and uses) cascading deletes
493 public function cascadingDeletes() {
498 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
502 public function cleanupTriggers() {
507 * Returns true if this database is strict about what can be put into an IP field.
508 * Specifically, it uses a NULL value instead of an empty string.
512 public function strictIPs() {
517 * Returns true if this database uses timestamps rather than integers
521 public function realTimestamps() {
526 * Returns true if this database does an implicit sort when doing GROUP BY
530 public function implicitGroupby() {
535 * Returns true if this database does an implicit order by when the column has an index
536 * For example: SELECT page_title FROM page LIMIT 1
540 public function implicitOrderby() {
545 * Returns true if this database can do a native search on IP columns
546 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
550 public function searchableIPs() {
555 * Returns true if this database can use functional indexes
559 public function functionalIndexes() {
564 * Return the last query that went through DatabaseBase::query()
567 public function lastQuery() {
568 return $this->mLastQuery
;
572 * Returns true if the connection may have been used for write queries.
573 * Should return true if unsure.
577 public function doneWrites() {
578 return $this->mDoneWrites
;
582 * Returns true if there is a transaction open with possible write
583 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
587 public function writesOrCallbacksPending() {
588 return $this->mTrxLevel
&& (
589 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
594 * Is a connection to the database open?
597 public function isOpen() {
598 return $this->mOpened
;
602 * Set a flag for this connection
604 * @param $flag Integer: DBO_* constants from Defines.php:
605 * - DBO_DEBUG: output some debug info (same as debug())
606 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
607 * - DBO_TRX: automatically start transactions
608 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
609 * and removes it in command line mode
610 * - DBO_PERSISTENT: use persistant database connection
612 public function setFlag( $flag ) {
613 global $wgDebugDBTransactions;
614 $this->mFlags |
= $flag;
615 if ( ( $flag & DBO_TRX
) & $wgDebugDBTransactions ) {
616 wfDebug( "Implicit transactions are now disabled.\n" );
621 * Clear a flag for this connection
623 * @param $flag: same as setFlag()'s $flag param
625 public function clearFlag( $flag ) {
626 global $wgDebugDBTransactions;
627 $this->mFlags
&= ~
$flag;
628 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
629 wfDebug( "Implicit transactions are now disabled.\n" );
634 * Returns a boolean whether the flag $flag is set for this connection
636 * @param $flag: same as setFlag()'s $flag param
639 public function getFlag( $flag ) {
640 return !!( $this->mFlags
& $flag );
644 * General read-only accessor
646 * @param $name string
650 public function getProperty( $name ) {
657 public function getWikiID() {
658 if ( $this->mTablePrefix
) {
659 return "{$this->mDBname}-{$this->mTablePrefix}";
661 return $this->mDBname
;
666 * Return a path to the DBMS-specific schema file, otherwise default to tables.sql
670 public function getSchemaPath() {
672 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
673 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
675 return "$IP/maintenance/tables.sql";
679 # ------------------------------------------------------------------------------
681 # ------------------------------------------------------------------------------
686 * FIXME: It is possible to construct a Database object with no associated
687 * connection object, by specifying no parameters to __construct(). This
688 * feature is deprecated and should be removed.
690 * FIXME: The long list of formal parameters here is not really appropriate
691 * for MySQL, and not at all appropriate for any other DBMS. It should be
692 * replaced by named parameters as in DatabaseBase::factory().
694 * DatabaseBase subclasses should not be constructed directly in external
695 * code. DatabaseBase::factory() should be used instead.
697 * @param string $server database server host
698 * @param string $user database user name
699 * @param string $password database user password
700 * @param string $dbName database name
702 * @param string $tablePrefix database table prefixes. By default use the prefix gave in LocalSettings.php
703 * @param bool $foreign disable some operations specific to local databases
705 function __construct( $server = false, $user = false, $password = false, $dbName = false,
706 $flags = 0, $tablePrefix = 'get from global', $foreign = false
708 global $wgDBprefix, $wgCommandLineMode, $wgDebugDBTransactions;
710 $this->mTrxAtomicLevels
= new SplStack
;
711 $this->mFlags
= $flags;
713 if ( $this->mFlags
& DBO_DEFAULT
) {
714 if ( $wgCommandLineMode ) {
715 $this->mFlags
&= ~DBO_TRX
;
716 if ( $wgDebugDBTransactions ) {
717 wfDebug( "Implicit transaction open disabled.\n" );
720 $this->mFlags |
= DBO_TRX
;
721 if ( $wgDebugDBTransactions ) {
722 wfDebug( "Implicit transaction open enabled.\n" );
727 /** Get the default table prefix*/
728 if ( $tablePrefix == 'get from global' ) {
729 $this->mTablePrefix
= $wgDBprefix;
731 $this->mTablePrefix
= $tablePrefix;
734 $this->mForeign
= $foreign;
737 $this->open( $server, $user, $password, $dbName );
742 * Called by serialize. Throw an exception when DB connection is serialized.
743 * This causes problems on some database engines because the connection is
744 * not restored on unserialize.
746 public function __sleep() {
747 throw new MWException( 'Database serialization may cause problems, since the connection is not restored on wakeup.' );
751 * Given a DB type, construct the name of the appropriate child class of
752 * DatabaseBase. This is designed to replace all of the manual stuff like:
753 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
754 * as well as validate against the canonical list of DB types we have
756 * This factory function is mostly useful for when you need to connect to a
757 * database other than the MediaWiki default (such as for external auth,
758 * an extension, et cetera). Do not use this to connect to the MediaWiki
759 * database. Example uses in core:
760 * @see LoadBalancer::reallyOpenConnection()
761 * @see ForeignDBRepo::getMasterDB()
762 * @see WebInstaller_DBConnect::execute()
766 * @param string $dbType A possible DB type
767 * @param array $p An array of options to pass to the constructor.
768 * Valid options are: host, user, password, dbname, flags, tablePrefix, driver
769 * @return DatabaseBase subclass or null
771 final public static function factory( $dbType, $p = array() ) {
772 $canonicalDBTypes = array(
773 'mysql' => array( 'mysqli', 'mysql' ),
774 'postgres' => array(),
781 $dbType = strtolower( $dbType );
782 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
783 $possibleDrivers = $canonicalDBTypes[$dbType];
784 if ( !empty( $p['driver'] ) ) {
785 if ( in_array( $p['driver'], $possibleDrivers ) ) {
786 $driver = $p['driver'];
788 throw new MWException( __METHOD__
.
789 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
792 foreach ( $possibleDrivers as $posDriver ) {
793 if ( extension_loaded( $posDriver ) ) {
794 $driver = $posDriver;
802 if ( $driver === false ) {
803 throw new MWException( __METHOD__
.
804 " no viable database extension found for type '$dbType'" );
807 $class = 'Database' . ucfirst( $driver );
808 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
810 isset( $p['host'] ) ?
$p['host'] : false,
811 isset( $p['user'] ) ?
$p['user'] : false,
812 isset( $p['password'] ) ?
$p['password'] : false,
813 isset( $p['dbname'] ) ?
$p['dbname'] : false,
814 isset( $p['flags'] ) ?
$p['flags'] : 0,
815 isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global',
816 isset( $p['foreign'] ) ?
$p['foreign'] : false
823 protected function installErrorHandler() {
824 $this->mPHPError
= false;
825 $this->htmlErrors
= ini_set( 'html_errors', '0' );
826 set_error_handler( array( $this, 'connectionErrorHandler' ) );
830 * @return bool|string
832 protected function restoreErrorHandler() {
833 restore_error_handler();
834 if ( $this->htmlErrors
!== false ) {
835 ini_set( 'html_errors', $this->htmlErrors
);
837 if ( $this->mPHPError
) {
838 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
839 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
851 public function connectionErrorHandler( $errno, $errstr ) {
852 $this->mPHPError
= $errstr;
856 * Closes a database connection.
857 * if it is open : commits any open transactions
859 * @throws MWException
860 * @return Bool operation success. true if already closed.
862 public function close() {
863 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
864 throw new MWException( "Transaction idle callbacks still pending." );
866 $this->mOpened
= false;
867 if ( $this->mConn
) {
868 if ( $this->trxLevel() ) {
869 if ( !$this->mTrxAutomatic
) {
870 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
871 " performing implicit commit before closing connection!" );
874 $this->commit( __METHOD__
, 'flush' );
877 $ret = $this->closeConnection();
878 $this->mConn
= false;
886 * Closes underlying database connection
888 * @return bool: Whether connection was closed successfully
890 abstract protected function closeConnection();
893 * @param string $error fallback error message, used if none is given by DB
894 * @throws DBConnectionError
896 function reportConnectionError( $error = 'Unknown error' ) {
897 $myError = $this->lastError();
903 throw new DBConnectionError( $this, $error );
907 * The DBMS-dependent part of query()
909 * @param $sql String: SQL query.
910 * @return ResultWrapper Result object to feed to fetchObject, fetchRow, ...; or false on failure
912 abstract protected function doQuery( $sql );
915 * Determine whether a query writes to the DB.
916 * Should return true if unsure.
922 public function isWriteQuery( $sql ) {
923 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
927 * Run an SQL query and return the result. Normally throws a DBQueryError
928 * on failure. If errors are ignored, returns false instead.
930 * In new code, the query wrappers select(), insert(), update(), delete(),
931 * etc. should be used where possible, since they give much better DBMS
932 * independence and automatically quote or validate user input in a variety
933 * of contexts. This function is generally only useful for queries which are
934 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
937 * However, the query wrappers themselves should call this function.
939 * @param $sql String: SQL query
940 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
941 * comment (you can use __METHOD__ or add some extra info)
942 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
943 * maybe best to catch the exception instead?
944 * @throws MWException
945 * @return boolean|ResultWrapper. true for a successful write query, ResultWrapper object
946 * for a successful read query, or false on failure if $tempIgnore set
948 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
949 global $wgUser, $wgDebugDBTransactions;
951 $this->mLastQuery
= $sql;
952 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
953 # Set a flag indicating that writes have been done
954 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
955 $this->mDoneWrites
= true;
958 # Add a comment for easy SHOW PROCESSLIST interpretation
959 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
960 $userName = $wgUser->getName();
961 if ( mb_strlen( $userName ) > 15 ) {
962 $userName = mb_substr( $userName, 0, 15 ) . '...';
964 $userName = str_replace( '/', '', $userName );
969 // Add trace comment to the begin of the sql string, right after the operator.
970 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
971 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
973 # If DBO_TRX is set, start a transaction
974 if ( ( $this->mFlags
& DBO_TRX
) && !$this->mTrxLevel
&&
975 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' )
977 # Avoid establishing transactions for SHOW and SET statements too -
978 # that would delay transaction initializations to once connection
979 # is really used by application
980 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
981 if ( strpos( $sqlstart, "SHOW " ) !== 0 && strpos( $sqlstart, "SET " ) !== 0 ) {
982 if ( $wgDebugDBTransactions ) {
983 wfDebug( "Implicit transaction start.\n" );
985 $this->begin( __METHOD__
. " ($fname)" );
986 $this->mTrxAutomatic
= true;
990 # Keep track of whether the transaction has write queries pending
991 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $this->isWriteQuery( $sql ) ) {
992 $this->mTrxDoneWrites
= true;
993 Profiler
::instance()->transactionWritingIn( $this->mServer
, $this->mDBname
);
996 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
997 if ( !Profiler
::instance()->isStub() ) {
998 # generalizeSQL will probably cut down the query to reasonable
999 # logging size most of the time. The substr is really just a sanity check.
1001 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1002 $totalProf = 'DatabaseBase::query-master';
1004 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1005 $totalProf = 'DatabaseBase::query';
1007 wfProfileIn( $totalProf );
1008 wfProfileIn( $queryProf );
1011 if ( $this->debug() ) {
1015 $sqlx = substr( $commentedSql, 0, 500 );
1016 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1018 $master = $isMaster ?
'master' : 'slave';
1019 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1022 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
1024 # Do the query and handle errors
1025 $ret = $this->doQuery( $commentedSql );
1027 MWDebug
::queryTime( $queryId );
1029 # Try reconnecting if the connection was lost
1030 if ( false === $ret && $this->wasErrorReissuable() ) {
1031 # Transaction is gone, like it or not
1032 $this->mTrxLevel
= 0;
1033 $this->mTrxIdleCallbacks
= array(); // cancel
1034 $this->mTrxPreCommitCallbacks
= array(); // cancel
1035 wfDebug( "Connection lost, reconnecting...\n" );
1037 if ( $this->ping() ) {
1038 wfDebug( "Reconnected\n" );
1039 $sqlx = substr( $commentedSql, 0, 500 );
1040 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1041 global $wgRequestTime;
1042 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
1043 if ( $elapsed < 300 ) {
1044 # Not a database error to lose a transaction after a minute or two
1045 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
1047 $ret = $this->doQuery( $commentedSql );
1049 wfDebug( "Failed\n" );
1053 if ( false === $ret ) {
1054 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1057 if ( !Profiler
::instance()->isStub() ) {
1058 wfProfileOut( $queryProf );
1059 wfProfileOut( $totalProf );
1062 return $this->resultObject( $ret );
1066 * Report a query error. Log the error, and if neither the object ignore
1067 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1069 * @param $error String
1070 * @param $errno Integer
1071 * @param $sql String
1072 * @param $fname String
1073 * @param $tempIgnore Boolean
1074 * @throws DBQueryError
1076 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1077 # Ignore errors during error handling to avoid infinite recursion
1078 $ignore = $this->ignoreErrors( true );
1079 ++
$this->mErrorCount
;
1081 if ( $ignore ||
$tempIgnore ) {
1082 wfDebug( "SQL ERROR (ignored): $error\n" );
1083 $this->ignoreErrors( $ignore );
1085 $sql1line = str_replace( "\n", "\\n", $sql );
1086 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
1087 wfDebug( "SQL ERROR: " . $error . "\n" );
1088 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1093 * Intended to be compatible with the PEAR::DB wrapper functions.
1094 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1096 * ? = scalar value, quoted as necessary
1097 * ! = raw SQL bit (a function for instance)
1098 * & = filename; reads the file and inserts as a blob
1099 * (we don't use this though...)
1101 * @param $sql string
1102 * @param $func string
1106 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1107 /* MySQL doesn't support prepared statements (yet), so just
1108 pack up the query for reference. We'll manually replace
1110 return array( 'query' => $sql, 'func' => $func );
1114 * Free a prepared query, generated by prepare().
1117 protected function freePrepared( $prepared ) {
1118 /* No-op by default */
1122 * Execute a prepared query with the various arguments
1123 * @param string $prepared the prepared sql
1124 * @param $args Mixed: Either an array here, or put scalars as varargs
1126 * @return ResultWrapper
1128 public function execute( $prepared, $args = null ) {
1129 if ( !is_array( $args ) ) {
1131 $args = func_get_args();
1132 array_shift( $args );
1135 $sql = $this->fillPrepared( $prepared['query'], $args );
1137 return $this->query( $sql, $prepared['func'] );
1141 * For faking prepared SQL statements on DBs that don't support it directly.
1143 * @param string $preparedQuery a 'preparable' SQL statement
1144 * @param array $args of arguments to fill it with
1145 * @return string executable SQL
1147 public function fillPrepared( $preparedQuery, $args ) {
1149 $this->preparedArgs
=& $args;
1151 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1152 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1156 * preg_callback func for fillPrepared()
1157 * The arguments should be in $this->preparedArgs and must not be touched
1158 * while we're doing this.
1160 * @param $matches Array
1161 * @throws DBUnexpectedError
1164 protected function fillPreparedArg( $matches ) {
1165 switch ( $matches[1] ) {
1174 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1176 switch ( $matches[1] ) {
1178 return $this->addQuotes( $arg );
1182 # return $this->addQuotes( file_get_contents( $arg ) );
1183 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
1185 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
1190 * Free a result object returned by query() or select(). It's usually not
1191 * necessary to call this, just use unset() or let the variable holding
1192 * the result object go out of scope.
1194 * @param $res Mixed: A SQL result
1196 public function freeResult( $res ) {
1200 * A SELECT wrapper which returns a single field from a single result row.
1202 * Usually throws a DBQueryError on failure. If errors are explicitly
1203 * ignored, returns false on failure.
1205 * If no result rows are returned from the query, false is returned.
1207 * @param string|array $table Table name. See DatabaseBase::select() for details.
1208 * @param string $var The field name to select. This must be a valid SQL
1209 * fragment: do not use unvalidated user input.
1210 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1211 * @param string $fname The function name of the caller.
1212 * @param string|array $options The query options. See DatabaseBase::select() for details.
1214 * @return bool|mixed The value from the field, or false on failure.
1216 public function selectField( $table, $var, $cond = '', $fname = __METHOD__
,
1219 if ( !is_array( $options ) ) {
1220 $options = array( $options );
1223 $options['LIMIT'] = 1;
1225 $res = $this->select( $table, $var, $cond, $fname, $options );
1227 if ( $res === false ||
!$this->numRows( $res ) ) {
1231 $row = $this->fetchRow( $res );
1233 if ( $row !== false ) {
1234 return reset( $row );
1241 * Returns an optional USE INDEX clause to go after the table, and a
1242 * string to go at the end of the query.
1244 * @param array $options associative array of options to be turned into
1245 * an SQL query, valid keys are listed in the function.
1247 * @see DatabaseBase::select()
1249 public function makeSelectOptions( $options ) {
1250 $preLimitTail = $postLimitTail = '';
1253 $noKeyOptions = array();
1255 foreach ( $options as $key => $option ) {
1256 if ( is_numeric( $key ) ) {
1257 $noKeyOptions[$option] = true;
1261 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1263 $preLimitTail .= $this->makeOrderBy( $options );
1265 // if (isset($options['LIMIT'])) {
1266 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1267 // isset($options['OFFSET']) ? $options['OFFSET']
1271 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1272 $postLimitTail .= ' FOR UPDATE';
1275 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1276 $postLimitTail .= ' LOCK IN SHARE MODE';
1279 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1280 $startOpts .= 'DISTINCT';
1283 # Various MySQL extensions
1284 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1285 $startOpts .= ' /*! STRAIGHT_JOIN */';
1288 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1289 $startOpts .= ' HIGH_PRIORITY';
1292 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1293 $startOpts .= ' SQL_BIG_RESULT';
1296 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1297 $startOpts .= ' SQL_BUFFER_RESULT';
1300 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1301 $startOpts .= ' SQL_SMALL_RESULT';
1304 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1305 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1308 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1309 $startOpts .= ' SQL_CACHE';
1312 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1313 $startOpts .= ' SQL_NO_CACHE';
1316 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1317 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1322 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1326 * Returns an optional GROUP BY with an optional HAVING
1328 * @param array $options associative array of options
1330 * @see DatabaseBase::select()
1333 public function makeGroupByWithHaving( $options ) {
1335 if ( isset( $options['GROUP BY'] ) ) {
1336 $gb = is_array( $options['GROUP BY'] )
1337 ?
implode( ',', $options['GROUP BY'] )
1338 : $options['GROUP BY'];
1339 $sql .= ' GROUP BY ' . $gb;
1341 if ( isset( $options['HAVING'] ) ) {
1342 $having = is_array( $options['HAVING'] )
1343 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1344 : $options['HAVING'];
1345 $sql .= ' HAVING ' . $having;
1351 * Returns an optional ORDER BY
1353 * @param array $options associative array of options
1355 * @see DatabaseBase::select()
1358 public function makeOrderBy( $options ) {
1359 if ( isset( $options['ORDER BY'] ) ) {
1360 $ob = is_array( $options['ORDER BY'] )
1361 ?
implode( ',', $options['ORDER BY'] )
1362 : $options['ORDER BY'];
1363 return ' ORDER BY ' . $ob;
1369 * Execute a SELECT query constructed using the various parameters provided.
1370 * See below for full details of the parameters.
1372 * @param string|array $table Table name
1373 * @param string|array $vars Field names
1374 * @param string|array $conds Conditions
1375 * @param string $fname Caller function name
1376 * @param array $options Query options
1377 * @param $join_conds Array Join conditions
1379 * @param $table string|array
1381 * May be either an array of table names, or a single string holding a table
1382 * name. If an array is given, table aliases can be specified, for example:
1384 * array( 'a' => 'user' )
1386 * This includes the user table in the query, with the alias "a" available
1387 * for use in field names (e.g. a.user_name).
1389 * All of the table names given here are automatically run through
1390 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1391 * added, and various other table name mappings to be performed.
1394 * @param $vars string|array
1396 * May be either a field name or an array of field names. The field names
1397 * can be complete fragments of SQL, for direct inclusion into the SELECT
1398 * query. If an array is given, field aliases can be specified, for example:
1400 * array( 'maxrev' => 'MAX(rev_id)' )
1402 * This includes an expression with the alias "maxrev" in the query.
1404 * If an expression is given, care must be taken to ensure that it is
1408 * @param $conds string|array
1410 * May be either a string containing a single condition, or an array of
1411 * conditions. If an array is given, the conditions constructed from each
1412 * element are combined with AND.
1414 * Array elements may take one of two forms:
1416 * - Elements with a numeric key are interpreted as raw SQL fragments.
1417 * - Elements with a string key are interpreted as equality conditions,
1418 * where the key is the field name.
1419 * - If the value of such an array element is a scalar (such as a
1420 * string), it will be treated as data and thus quoted appropriately.
1421 * If it is null, an IS NULL clause will be added.
1422 * - If the value is an array, an IN(...) clause will be constructed,
1423 * such that the field name may match any of the elements in the
1424 * array. The elements of the array will be quoted.
1426 * Note that expressions are often DBMS-dependent in their syntax.
1427 * DBMS-independent wrappers are provided for constructing several types of
1428 * expression commonly used in condition queries. See:
1429 * - DatabaseBase::buildLike()
1430 * - DatabaseBase::conditional()
1433 * @param $options string|array
1435 * Optional: Array of query options. Boolean options are specified by
1436 * including them in the array as a string value with a numeric key, for
1439 * array( 'FOR UPDATE' )
1441 * The supported options are:
1443 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1444 * with LIMIT can theoretically be used for paging through a result set,
1445 * but this is discouraged in MediaWiki for performance reasons.
1447 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1448 * and then the first rows are taken until the limit is reached. LIMIT
1449 * is applied to a result set after OFFSET.
1451 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1452 * changed until the next COMMIT.
1454 * - DISTINCT: Boolean: return only unique result rows.
1456 * - GROUP BY: May be either an SQL fragment string naming a field or
1457 * expression to group by, or an array of such SQL fragments.
1459 * - HAVING: May be either an string containing a HAVING clause or an array of
1460 * conditions building the HAVING clause. If an array is given, the conditions
1461 * constructed from each element are combined with AND.
1463 * - ORDER BY: May be either an SQL fragment giving a field name or
1464 * expression to order by, or an array of such SQL fragments.
1466 * - USE INDEX: This may be either a string giving the index name to use
1467 * for the query, or an array. If it is an associative array, each key
1468 * gives the table name (or alias), each value gives the index name to
1469 * use for that table. All strings are SQL fragments and so should be
1470 * validated by the caller.
1472 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1473 * instead of SELECT.
1475 * And also the following boolean MySQL extensions, see the MySQL manual
1476 * for documentation:
1478 * - LOCK IN SHARE MODE
1482 * - SQL_BUFFER_RESULT
1483 * - SQL_SMALL_RESULT
1484 * - SQL_CALC_FOUND_ROWS
1489 * @param $join_conds string|array
1491 * Optional associative array of table-specific join conditions. In the
1492 * most common case, this is unnecessary, since the join condition can be
1493 * in $conds. However, it is useful for doing a LEFT JOIN.
1495 * The key of the array contains the table name or alias. The value is an
1496 * array with two elements, numbered 0 and 1. The first gives the type of
1497 * join, the second is an SQL fragment giving the join condition for that
1498 * table. For example:
1500 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1502 * @return ResultWrapper. If the query returned no rows, a ResultWrapper
1503 * with no rows in it will be returned. If there was a query error, a
1504 * DBQueryError exception will be thrown, except if the "ignore errors"
1505 * option was set, in which case false will be returned.
1507 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1508 $options = array(), $join_conds = array() ) {
1509 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1511 return $this->query( $sql, $fname );
1515 * The equivalent of DatabaseBase::select() except that the constructed SQL
1516 * is returned, instead of being immediately executed. This can be useful for
1517 * doing UNION queries, where the SQL text of each query is needed. In general,
1518 * however, callers outside of Database classes should just use select().
1520 * @param string|array $table Table name
1521 * @param string|array $vars Field names
1522 * @param string|array $conds Conditions
1523 * @param string $fname Caller function name
1524 * @param string|array $options Query options
1525 * @param $join_conds string|array Join conditions
1527 * @return string SQL query string.
1528 * @see DatabaseBase::select()
1530 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1531 $options = array(), $join_conds = array() )
1533 if ( is_array( $vars ) ) {
1534 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1537 $options = (array)$options;
1538 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1539 ?
$options['USE INDEX']
1542 if ( is_array( $table ) ) {
1544 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1545 } elseif ( $table != '' ) {
1546 if ( $table[0] == ' ' ) {
1547 $from = ' FROM ' . $table;
1550 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1556 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1557 $this->makeSelectOptions( $options );
1559 if ( !empty( $conds ) ) {
1560 if ( is_array( $conds ) ) {
1561 $conds = $this->makeList( $conds, LIST_AND
);
1563 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1565 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1568 if ( isset( $options['LIMIT'] ) ) {
1569 $sql = $this->limitResult( $sql, $options['LIMIT'],
1570 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1572 $sql = "$sql $postLimitTail";
1574 if ( isset( $options['EXPLAIN'] ) ) {
1575 $sql = 'EXPLAIN ' . $sql;
1582 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1583 * that a single row object is returned. If the query returns no rows,
1584 * false is returned.
1586 * @param string|array $table Table name
1587 * @param string|array $vars Field names
1588 * @param array $conds Conditions
1589 * @param string $fname Caller function name
1590 * @param string|array $options Query options
1591 * @param $join_conds array|string Join conditions
1593 * @return object|bool
1595 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1596 $options = array(), $join_conds = array() )
1598 $options = (array)$options;
1599 $options['LIMIT'] = 1;
1600 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1602 if ( $res === false ) {
1606 if ( !$this->numRows( $res ) ) {
1610 $obj = $this->fetchObject( $res );
1616 * Estimate rows in dataset.
1618 * MySQL allows you to estimate the number of rows that would be returned
1619 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1620 * index cardinality statistics, and is notoriously inaccurate, especially
1621 * when large numbers of rows have recently been added or deleted.
1623 * For DBMSs that don't support fast result size estimation, this function
1624 * will actually perform the SELECT COUNT(*).
1626 * Takes the same arguments as DatabaseBase::select().
1628 * @param string $table table name
1629 * @param array|string $vars : unused
1630 * @param array|string $conds : filters on the table
1631 * @param string $fname function name for profiling
1632 * @param array $options options for select
1633 * @return Integer: row count
1635 public function estimateRowCount( $table, $vars = '*', $conds = '',
1636 $fname = __METHOD__
, $options = array() )
1639 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1642 $row = $this->fetchRow( $res );
1643 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1650 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1651 * It's only slightly flawed. Don't use for anything important.
1653 * @param string $sql A SQL Query
1657 static function generalizeSQL( $sql ) {
1658 # This does the same as the regexp below would do, but in such a way
1659 # as to avoid crashing php on some large strings.
1660 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1662 $sql = str_replace( "\\\\", '', $sql );
1663 $sql = str_replace( "\\'", '', $sql );
1664 $sql = str_replace( "\\\"", '', $sql );
1665 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1666 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1668 # All newlines, tabs, etc replaced by single space
1669 $sql = preg_replace( '/\s+/', ' ', $sql );
1672 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1673 $sql = preg_replace( '/-?\d+/s', 'N', $sql );
1679 * Determines whether a field exists in a table
1681 * @param string $table table name
1682 * @param string $field filed to check on that table
1683 * @param string $fname calling function name (optional)
1684 * @return Boolean: whether $table has filed $field
1686 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1687 $info = $this->fieldInfo( $table, $field );
1693 * Determines whether an index exists
1694 * Usually throws a DBQueryError on failure
1695 * If errors are explicitly ignored, returns NULL on failure
1699 * @param $fname string
1703 public function indexExists( $table, $index, $fname = __METHOD__
) {
1704 if ( !$this->tableExists( $table ) ) {
1708 $info = $this->indexInfo( $table, $index, $fname );
1709 if ( is_null( $info ) ) {
1712 return $info !== false;
1717 * Query whether a given table exists
1719 * @param $table string
1720 * @param $fname string
1724 public function tableExists( $table, $fname = __METHOD__
) {
1725 $table = $this->tableName( $table );
1726 $old = $this->ignoreErrors( true );
1727 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1728 $this->ignoreErrors( $old );
1734 * mysql_field_type() wrapper
1739 public function fieldType( $res, $index ) {
1740 if ( $res instanceof ResultWrapper
) {
1741 $res = $res->result
;
1744 return mysql_field_type( $res, $index );
1748 * Determines if a given index is unique
1750 * @param $table string
1751 * @param $index string
1755 public function indexUnique( $table, $index ) {
1756 $indexInfo = $this->indexInfo( $table, $index );
1758 if ( !$indexInfo ) {
1762 return !$indexInfo[0]->Non_unique
;
1766 * Helper for DatabaseBase::insert().
1768 * @param $options array
1771 protected function makeInsertOptions( $options ) {
1772 return implode( ' ', $options );
1776 * INSERT wrapper, inserts an array into a table.
1780 * - A single associative array. The array keys are the field names, and
1781 * the values are the values to insert. The values are treated as data
1782 * and will be quoted appropriately. If NULL is inserted, this will be
1783 * converted to a database NULL.
1784 * - An array with numeric keys, holding a list of associative arrays.
1785 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1786 * each subarray must be identical to each other, and in the same order.
1788 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1791 * $options is an array of options, with boolean options encoded as values
1792 * with numeric keys, in the same style as $options in
1793 * DatabaseBase::select(). Supported options are:
1795 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1796 * any rows which cause duplicate key errors are not inserted. It's
1797 * possible to determine how many rows were successfully inserted using
1798 * DatabaseBase::affectedRows().
1800 * @param $table String Table name. This will be passed through
1801 * DatabaseBase::tableName().
1802 * @param $a Array of rows to insert
1803 * @param $fname String Calling function name (use __METHOD__) for logs/profiling
1804 * @param array $options of options
1808 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
1809 # No rows to insert, easy just return now
1810 if ( !count( $a ) ) {
1814 $table = $this->tableName( $table );
1816 if ( !is_array( $options ) ) {
1817 $options = array( $options );
1821 if ( isset( $options['fileHandle'] ) ) {
1822 $fh = $options['fileHandle'];
1824 $options = $this->makeInsertOptions( $options );
1826 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1828 $keys = array_keys( $a[0] );
1831 $keys = array_keys( $a );
1834 $sql = 'INSERT ' . $options .
1835 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1839 foreach ( $a as $row ) {
1845 $sql .= '(' . $this->makeList( $row ) . ')';
1848 $sql .= '(' . $this->makeList( $a ) . ')';
1851 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1853 } elseif ( $fh !== null ) {
1857 return (bool)$this->query( $sql, $fname );
1861 * Make UPDATE options for the DatabaseBase::update function
1863 * @param array $options The options passed to DatabaseBase::update
1866 protected function makeUpdateOptions( $options ) {
1867 if ( !is_array( $options ) ) {
1868 $options = array( $options );
1873 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1874 $opts[] = $this->lowPriorityOption();
1877 if ( in_array( 'IGNORE', $options ) ) {
1881 return implode( ' ', $opts );
1885 * UPDATE wrapper. Takes a condition array and a SET array.
1887 * @param $table String name of the table to UPDATE. This will be passed through
1888 * DatabaseBase::tableName().
1890 * @param array $values An array of values to SET. For each array element,
1891 * the key gives the field name, and the value gives the data
1892 * to set that field to. The data will be quoted by
1893 * DatabaseBase::addQuotes().
1895 * @param $conds Array: An array of conditions (WHERE). See
1896 * DatabaseBase::select() for the details of the format of
1897 * condition arrays. Use '*' to update all rows.
1899 * @param $fname String: The function name of the caller (from __METHOD__),
1900 * for logging and profiling.
1902 * @param array $options An array of UPDATE options, can be:
1903 * - IGNORE: Ignore unique key conflicts
1904 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1907 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
1908 $table = $this->tableName( $table );
1909 $opts = $this->makeUpdateOptions( $options );
1910 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1912 if ( $conds !== array() && $conds !== '*' ) {
1913 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1916 return $this->query( $sql, $fname );
1920 * Makes an encoded list of strings from an array
1921 * @param array $a containing the data
1922 * @param int $mode Constant
1923 * - LIST_COMMA: comma separated, no field names
1924 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
1925 * the documentation for $conds in DatabaseBase::select().
1926 * - LIST_OR: ORed WHERE clause (without the WHERE)
1927 * - LIST_SET: comma separated with field names, like a SET clause
1928 * - LIST_NAMES: comma separated field names
1930 * @throws MWException|DBUnexpectedError
1933 public function makeList( $a, $mode = LIST_COMMA
) {
1934 if ( !is_array( $a ) ) {
1935 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1941 foreach ( $a as $field => $value ) {
1943 if ( $mode == LIST_AND
) {
1945 } elseif ( $mode == LIST_OR
) {
1954 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1955 $list .= "($value)";
1956 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1958 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1959 if ( count( $value ) == 0 ) {
1960 throw new MWException( __METHOD__
. ": empty input for field $field" );
1961 } elseif ( count( $value ) == 1 ) {
1962 // Special-case single values, as IN isn't terribly efficient
1963 // Don't necessarily assume the single key is 0; we don't
1964 // enforce linear numeric ordering on other arrays here.
1965 $value = array_values( $value );
1966 $list .= $field . " = " . $this->addQuotes( $value[0] );
1968 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1970 } elseif ( $value === null ) {
1971 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1972 $list .= "$field IS ";
1973 } elseif ( $mode == LIST_SET
) {
1974 $list .= "$field = ";
1978 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1979 $list .= "$field = ";
1981 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1989 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1990 * The keys on each level may be either integers or strings.
1992 * @param array $data organized as 2-d
1993 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
1994 * @param string $baseKey field name to match the base-level keys to (eg 'pl_namespace')
1995 * @param string $subKey field name to match the sub-level keys to (eg 'pl_title')
1996 * @return Mixed: string SQL fragment, or false if no items in array.
1998 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2001 foreach ( $data as $base => $sub ) {
2002 if ( count( $sub ) ) {
2003 $conds[] = $this->makeList(
2004 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2010 return $this->makeList( $conds, LIST_OR
);
2012 // Nothing to search for...
2018 * Return aggregated value alias
2021 * @param $valuename string
2025 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2033 public function bitNot( $field ) {
2039 * @param $fieldRight
2042 public function bitAnd( $fieldLeft, $fieldRight ) {
2043 return "($fieldLeft & $fieldRight)";
2048 * @param $fieldRight
2051 public function bitOr( $fieldLeft, $fieldRight ) {
2052 return "($fieldLeft | $fieldRight)";
2056 * Build a concatenation list to feed into a SQL query
2057 * @param array $stringList list of raw SQL expressions; caller is responsible for any quoting
2060 public function buildConcat( $stringList ) {
2061 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2065 * Change the current database
2067 * @todo Explain what exactly will fail if this is not overridden.
2071 * @return bool Success or failure
2073 public function selectDB( $db ) {
2074 # Stub. Shouldn't cause serious problems if it's not overridden, but
2075 # if your database engine supports a concept similar to MySQL's
2076 # databases you may as well.
2077 $this->mDBname
= $db;
2082 * Get the current DB name
2084 public function getDBname() {
2085 return $this->mDBname
;
2089 * Get the server hostname or IP address
2091 public function getServer() {
2092 return $this->mServer
;
2096 * Format a table name ready for use in constructing an SQL query
2098 * This does two important things: it quotes the table names to clean them up,
2099 * and it adds a table prefix if only given a table name with no quotes.
2101 * All functions of this object which require a table name call this function
2102 * themselves. Pass the canonical name to such functions. This is only needed
2103 * when calling query() directly.
2105 * @param string $name database table name
2106 * @param string $format One of:
2107 * quoted - Automatically pass the table name through addIdentifierQuotes()
2108 * so that it can be used in a query.
2109 * raw - Do not add identifier quotes to the table name
2110 * @return String: full database name
2112 public function tableName( $name, $format = 'quoted' ) {
2113 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
2114 # Skip the entire process when we have a string quoted on both ends.
2115 # Note that we check the end so that we will still quote any use of
2116 # use of `database`.table. But won't break things if someone wants
2117 # to query a database table with a dot in the name.
2118 if ( $this->isQuotedIdentifier( $name ) ) {
2122 # Lets test for any bits of text that should never show up in a table
2123 # name. Basically anything like JOIN or ON which are actually part of
2124 # SQL queries, but may end up inside of the table value to combine
2125 # sql. Such as how the API is doing.
2126 # Note that we use a whitespace test rather than a \b test to avoid
2127 # any remote case where a word like on may be inside of a table name
2128 # surrounded by symbols which may be considered word breaks.
2129 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2133 # Split database and table into proper variables.
2134 # We reverse the explode so that database.table and table both output
2135 # the correct table.
2136 $dbDetails = explode( '.', $name, 2 );
2137 if ( count( $dbDetails ) == 2 ) {
2138 list( $database, $table ) = $dbDetails;
2139 # We don't want any prefix added in this case
2142 list( $table ) = $dbDetails;
2143 if ( $wgSharedDB !== null # We have a shared database
2144 && $this->mForeign
== false # We're not working on a foreign database
2145 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
2146 && in_array( $table, $wgSharedTables ) # A shared table is selected
2148 $database = $wgSharedDB;
2149 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
2152 $prefix = $this->mTablePrefix
; # Default prefix
2156 # Quote $table and apply the prefix if not quoted.
2157 $tableName = "{$prefix}{$table}";
2158 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) ) {
2159 $tableName = $this->addIdentifierQuotes( $tableName );
2162 # Quote $database and merge it with the table name if needed
2163 if ( $database !== null ) {
2164 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2165 $database = $this->addIdentifierQuotes( $database );
2167 $tableName = $database . '.' . $tableName;
2174 * Fetch a number of table names into an array
2175 * This is handy when you need to construct SQL for joins
2178 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2179 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2180 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2184 public function tableNames() {
2185 $inArray = func_get_args();
2188 foreach ( $inArray as $name ) {
2189 $retVal[$name] = $this->tableName( $name );
2196 * Fetch a number of table names into an zero-indexed numerical array
2197 * This is handy when you need to construct SQL for joins
2200 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2201 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2202 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2206 public function tableNamesN() {
2207 $inArray = func_get_args();
2210 foreach ( $inArray as $name ) {
2211 $retVal[] = $this->tableName( $name );
2218 * Get an aliased table name
2219 * e.g. tableName AS newTableName
2221 * @param string $name Table name, see tableName()
2222 * @param string|bool $alias Alias (optional)
2223 * @return string SQL name for aliased table. Will not alias a table to its own name
2225 public function tableNameWithAlias( $name, $alias = false ) {
2226 if ( !$alias ||
$alias == $name ) {
2227 return $this->tableName( $name );
2229 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2234 * Gets an array of aliased table names
2236 * @param $tables array( [alias] => table )
2237 * @return array of strings, see tableNameWithAlias()
2239 public function tableNamesWithAlias( $tables ) {
2241 foreach ( $tables as $alias => $table ) {
2242 if ( is_numeric( $alias ) ) {
2245 $retval[] = $this->tableNameWithAlias( $table, $alias );
2251 * Get an aliased field name
2252 * e.g. fieldName AS newFieldName
2254 * @param string $name Field name
2255 * @param string|bool $alias Alias (optional)
2256 * @return string SQL name for aliased field. Will not alias a field to its own name
2258 public function fieldNameWithAlias( $name, $alias = false ) {
2259 if ( !$alias ||
(string)$alias === (string)$name ) {
2262 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2267 * Gets an array of aliased field names
2269 * @param $fields array( [alias] => field )
2270 * @return array of strings, see fieldNameWithAlias()
2272 public function fieldNamesWithAlias( $fields ) {
2274 foreach ( $fields as $alias => $field ) {
2275 if ( is_numeric( $alias ) ) {
2278 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2284 * Get the aliased table name clause for a FROM clause
2285 * which might have a JOIN and/or USE INDEX clause
2287 * @param array $tables ( [alias] => table )
2288 * @param $use_index array Same as for select()
2289 * @param $join_conds array Same as for select()
2292 protected function tableNamesWithUseIndexOrJOIN(
2293 $tables, $use_index = array(), $join_conds = array()
2297 $use_index = (array)$use_index;
2298 $join_conds = (array)$join_conds;
2300 foreach ( $tables as $alias => $table ) {
2301 if ( !is_string( $alias ) ) {
2302 // No alias? Set it equal to the table name
2305 // Is there a JOIN clause for this table?
2306 if ( isset( $join_conds[$alias] ) ) {
2307 list( $joinType, $conds ) = $join_conds[$alias];
2308 $tableClause = $joinType;
2309 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2310 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2311 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2313 $tableClause .= ' ' . $use;
2316 $on = $this->makeList( (array)$conds, LIST_AND
);
2318 $tableClause .= ' ON (' . $on . ')';
2321 $retJOIN[] = $tableClause;
2322 // Is there an INDEX clause for this table?
2323 } elseif ( isset( $use_index[$alias] ) ) {
2324 $tableClause = $this->tableNameWithAlias( $table, $alias );
2325 $tableClause .= ' ' . $this->useIndexClause(
2326 implode( ',', (array)$use_index[$alias] ) );
2328 $ret[] = $tableClause;
2330 $tableClause = $this->tableNameWithAlias( $table, $alias );
2332 $ret[] = $tableClause;
2336 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2337 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2338 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2340 // Compile our final table clause
2341 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2345 * Get the name of an index in a given table
2351 protected function indexName( $index ) {
2352 // Backwards-compatibility hack
2354 'ar_usertext_timestamp' => 'usertext_timestamp',
2355 'un_user_id' => 'user_id',
2356 'un_user_ip' => 'user_ip',
2359 if ( isset( $renamed[$index] ) ) {
2360 return $renamed[$index];
2367 * Adds quotes and backslashes.
2373 public function addQuotes( $s ) {
2374 if ( $s === null ) {
2377 # This will also quote numeric values. This should be harmless,
2378 # and protects against weird problems that occur when they really
2379 # _are_ strings such as article titles and string->number->string
2380 # conversion is not 1:1.
2381 return "'" . $this->strencode( $s ) . "'";
2386 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2387 * MySQL uses `backticks` while basically everything else uses double quotes.
2388 * Since MySQL is the odd one out here the double quotes are our generic
2389 * and we implement backticks in DatabaseMysql.
2395 public function addIdentifierQuotes( $s ) {
2396 return '"' . str_replace( '"', '""', $s ) . '"';
2400 * Returns if the given identifier looks quoted or not according to
2401 * the database convention for quoting identifiers .
2403 * @param $name string
2407 public function isQuotedIdentifier( $name ) {
2408 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2415 protected function escapeLikeInternal( $s ) {
2416 $s = str_replace( '\\', '\\\\', $s );
2417 $s = $this->strencode( $s );
2418 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
2424 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
2425 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
2426 * Alternatively, the function could be provided with an array of aforementioned parameters.
2428 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
2429 * for subpages of 'My page title'.
2430 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
2433 * @return String: fully built LIKE statement
2435 public function buildLike() {
2436 $params = func_get_args();
2438 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2439 $params = $params[0];
2444 foreach ( $params as $value ) {
2445 if ( $value instanceof LikeMatch
) {
2446 $s .= $value->toString();
2448 $s .= $this->escapeLikeInternal( $value );
2452 return " LIKE '" . $s . "' ";
2456 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2460 public function anyChar() {
2461 return new LikeMatch( '_' );
2465 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2469 public function anyString() {
2470 return new LikeMatch( '%' );
2474 * Returns an appropriately quoted sequence value for inserting a new row.
2475 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2476 * subclass will return an integer, and save the value for insertId()
2478 * Any implementation of this function should *not* involve reusing
2479 * sequence numbers created for rolled-back transactions.
2480 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2481 * @param $seqName string
2484 public function nextSequenceValue( $seqName ) {
2489 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2490 * is only needed because a) MySQL must be as efficient as possible due to
2491 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2492 * which index to pick. Anyway, other databases might have different
2493 * indexes on a given table. So don't bother overriding this unless you're
2498 public function useIndexClause( $index ) {
2503 * REPLACE query wrapper.
2505 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2506 * except that when there is a duplicate key error, the old row is deleted
2507 * and the new row is inserted in its place.
2509 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2510 * perform the delete, we need to know what the unique indexes are so that
2511 * we know how to find the conflicting rows.
2513 * It may be more efficient to leave off unique indexes which are unlikely
2514 * to collide. However if you do this, you run the risk of encountering
2515 * errors which wouldn't have occurred in MySQL.
2517 * @param string $table The table to replace the row(s) in.
2518 * @param array $rows Can be either a single row to insert, or multiple rows,
2519 * in the same format as for DatabaseBase::insert()
2520 * @param array $uniqueIndexes is an array of indexes. Each element may be either
2521 * a field name or an array of field names
2522 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2524 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2525 $quotedTable = $this->tableName( $table );
2527 if ( count( $rows ) == 0 ) {
2532 if ( !is_array( reset( $rows ) ) ) {
2533 $rows = array( $rows );
2536 foreach ( $rows as $row ) {
2537 # Delete rows which collide
2538 if ( $uniqueIndexes ) {
2539 $sql = "DELETE FROM $quotedTable WHERE ";
2541 foreach ( $uniqueIndexes as $index ) {
2548 if ( is_array( $index ) ) {
2550 foreach ( $index as $col ) {
2556 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2559 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2563 $this->query( $sql, $fname );
2566 # Now insert the row
2567 $this->insert( $table, $row, $fname );
2572 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2575 * @param string $table Table name
2576 * @param array $rows Rows to insert
2577 * @param string $fname Caller function name
2579 * @return ResultWrapper
2581 protected function nativeReplace( $table, $rows, $fname ) {
2582 $table = $this->tableName( $table );
2585 if ( !is_array( reset( $rows ) ) ) {
2586 $rows = array( $rows );
2589 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2592 foreach ( $rows as $row ) {
2599 $sql .= '(' . $this->makeList( $row ) . ')';
2602 return $this->query( $sql, $fname );
2606 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2608 * This updates any conflicting rows (according to the unique indexes) using
2609 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2611 * $rows may be either:
2612 * - A single associative array. The array keys are the field names, and
2613 * the values are the values to insert. The values are treated as data
2614 * and will be quoted appropriately. If NULL is inserted, this will be
2615 * converted to a database NULL.
2616 * - An array with numeric keys, holding a list of associative arrays.
2617 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2618 * each subarray must be identical to each other, and in the same order.
2620 * It may be more efficient to leave off unique indexes which are unlikely
2621 * to collide. However if you do this, you run the risk of encountering
2622 * errors which wouldn't have occurred in MySQL.
2624 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2627 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2628 * @param array $rows A single row or list of rows to insert
2629 * @param array $uniqueIndexes List of single field names or field name tuples
2630 * @param array $set An array of values to SET. For each array element,
2631 * the key gives the field name, and the value gives the data
2632 * to set that field to. The data will be quoted by
2633 * DatabaseBase::addQuotes().
2634 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2635 * @param array $options of options
2640 public function upsert(
2641 $table, array $rows, array $uniqueIndexes, array $set, $fname = __METHOD__
2643 if ( !count( $rows ) ) {
2644 return true; // nothing to do
2646 $rows = is_array( reset( $rows ) ) ?
$rows : array( $rows );
2648 if ( count( $uniqueIndexes ) ) {
2649 $clauses = array(); // list WHERE clauses that each identify a single row
2650 foreach ( $rows as $row ) {
2651 foreach ( $uniqueIndexes as $index ) {
2652 $index = is_array( $index ) ?
$index : array( $index ); // columns
2653 $rowKey = array(); // unique key to this row
2654 foreach ( $index as $column ) {
2655 $rowKey[$column] = $row[$column];
2657 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2660 $where = array( $this->makeList( $clauses, LIST_OR
) );
2665 $useTrx = !$this->mTrxLevel
;
2667 $this->begin( $fname );
2670 # Update any existing conflicting row(s)
2671 if ( $where !== false ) {
2672 $ok = $this->update( $table, $set, $where, $fname );
2676 # Now insert any non-conflicting row(s)
2677 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2678 } catch ( Exception
$e ) {
2680 $this->rollback( $fname );
2685 $this->commit( $fname );
2692 * DELETE where the condition is a join.
2694 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2695 * we use sub-selects
2697 * For safety, an empty $conds will not delete everything. If you want to
2698 * delete all rows where the join condition matches, set $conds='*'.
2700 * DO NOT put the join condition in $conds.
2702 * @param $delTable String: The table to delete from.
2703 * @param $joinTable String: The other table.
2704 * @param $delVar String: The variable to join on, in the first table.
2705 * @param $joinVar String: The variable to join on, in the second table.
2706 * @param $conds Array: Condition array of field names mapped to variables,
2707 * ANDed together in the WHERE clause
2708 * @param $fname String: Calling function name (use __METHOD__) for
2710 * @throws DBUnexpectedError
2712 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2713 $fname = __METHOD__
)
2716 throw new DBUnexpectedError( $this,
2717 'DatabaseBase::deleteJoin() called with empty $conds' );
2720 $delTable = $this->tableName( $delTable );
2721 $joinTable = $this->tableName( $joinTable );
2722 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2723 if ( $conds != '*' ) {
2724 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2728 $this->query( $sql, $fname );
2732 * Returns the size of a text field, or -1 for "unlimited"
2734 * @param $table string
2735 * @param $field string
2739 public function textFieldSize( $table, $field ) {
2740 $table = $this->tableName( $table );
2741 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2742 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2743 $row = $this->fetchObject( $res );
2747 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2757 * A string to insert into queries to show that they're low-priority, like
2758 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2759 * string and nothing bad should happen.
2761 * @return string Returns the text of the low priority option if it is
2762 * supported, or a blank string otherwise
2764 public function lowPriorityOption() {
2769 * DELETE query wrapper.
2771 * @param array $table Table name
2772 * @param string|array $conds of conditions. See $conds in DatabaseBase::select() for
2773 * the format. Use $conds == "*" to delete all rows
2774 * @param string $fname name of the calling function
2776 * @throws DBUnexpectedError
2777 * @return bool|ResultWrapper
2779 public function delete( $table, $conds, $fname = __METHOD__
) {
2781 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2784 $table = $this->tableName( $table );
2785 $sql = "DELETE FROM $table";
2787 if ( $conds != '*' ) {
2788 if ( is_array( $conds ) ) {
2789 $conds = $this->makeList( $conds, LIST_AND
);
2791 $sql .= ' WHERE ' . $conds;
2794 return $this->query( $sql, $fname );
2798 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2799 * into another table.
2801 * @param string $destTable The table name to insert into
2802 * @param string|array $srcTable May be either a table name, or an array of table names
2803 * to include in a join.
2805 * @param array $varMap must be an associative array of the form
2806 * array( 'dest1' => 'source1', ...). Source items may be literals
2807 * rather than field names, but strings should be quoted with
2808 * DatabaseBase::addQuotes()
2810 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
2811 * the details of the format of condition arrays. May be "*" to copy the
2814 * @param string $fname The function name of the caller, from __METHOD__
2816 * @param array $insertOptions Options for the INSERT part of the query, see
2817 * DatabaseBase::insert() for details.
2818 * @param array $selectOptions Options for the SELECT part of the query, see
2819 * DatabaseBase::select() for details.
2821 * @return ResultWrapper
2823 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2824 $fname = __METHOD__
,
2825 $insertOptions = array(), $selectOptions = array() )
2827 $destTable = $this->tableName( $destTable );
2829 if ( is_array( $insertOptions ) ) {
2830 $insertOptions = implode( ' ', $insertOptions );
2833 if ( !is_array( $selectOptions ) ) {
2834 $selectOptions = array( $selectOptions );
2837 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2839 if ( is_array( $srcTable ) ) {
2840 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2842 $srcTable = $this->tableName( $srcTable );
2845 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2846 " SELECT $startOpts " . implode( ',', $varMap ) .
2847 " FROM $srcTable $useIndex ";
2849 if ( $conds != '*' ) {
2850 if ( is_array( $conds ) ) {
2851 $conds = $this->makeList( $conds, LIST_AND
);
2853 $sql .= " WHERE $conds";
2856 $sql .= " $tailOpts";
2858 return $this->query( $sql, $fname );
2862 * Construct a LIMIT query with optional offset. This is used for query
2863 * pages. The SQL should be adjusted so that only the first $limit rows
2864 * are returned. If $offset is provided as well, then the first $offset
2865 * rows should be discarded, and the next $limit rows should be returned.
2866 * If the result of the query is not ordered, then the rows to be returned
2867 * are theoretically arbitrary.
2869 * $sql is expected to be a SELECT, if that makes a difference.
2871 * The version provided by default works in MySQL and SQLite. It will very
2872 * likely need to be overridden for most other DBMSes.
2874 * @param string $sql SQL query we will append the limit too
2875 * @param $limit Integer the SQL limit
2876 * @param $offset Integer|bool the SQL offset (default false)
2878 * @throws DBUnexpectedError
2881 public function limitResult( $sql, $limit, $offset = false ) {
2882 if ( !is_numeric( $limit ) ) {
2883 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2885 return "$sql LIMIT "
2886 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2891 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2892 * within the UNION construct.
2895 public function unionSupportsOrderAndLimit() {
2896 return true; // True for almost every DB supported
2900 * Construct a UNION query
2901 * This is used for providing overload point for other DB abstractions
2902 * not compatible with the MySQL syntax.
2903 * @param array $sqls SQL statements to combine
2904 * @param $all Boolean: use UNION ALL
2905 * @return String: SQL fragment
2907 public function unionQueries( $sqls, $all ) {
2908 $glue = $all ?
') UNION ALL (' : ') UNION (';
2909 return '(' . implode( $glue, $sqls ) . ')';
2913 * Returns an SQL expression for a simple conditional. This doesn't need
2914 * to be overridden unless CASE isn't supported in your DBMS.
2916 * @param string|array $cond SQL expression which will result in a boolean value
2917 * @param string $trueVal SQL expression to return if true
2918 * @param string $falseVal SQL expression to return if false
2919 * @return String: SQL fragment
2921 public function conditional( $cond, $trueVal, $falseVal ) {
2922 if ( is_array( $cond ) ) {
2923 $cond = $this->makeList( $cond, LIST_AND
);
2925 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2929 * Returns a comand for str_replace function in SQL query.
2930 * Uses REPLACE() in MySQL
2932 * @param string $orig column to modify
2933 * @param string $old column to seek
2934 * @param string $new column to replace with
2938 public function strreplace( $orig, $old, $new ) {
2939 return "REPLACE({$orig}, {$old}, {$new})";
2943 * Determines how long the server has been up
2948 public function getServerUptime() {
2953 * Determines if the last failure was due to a deadlock
2958 public function wasDeadlock() {
2963 * Determines if the last failure was due to a lock timeout
2968 public function wasLockTimeout() {
2973 * Determines if the last query error was something that should be dealt
2974 * with by pinging the connection and reissuing the query.
2979 public function wasErrorReissuable() {
2984 * Determines if the last failure was due to the database being read-only.
2989 public function wasReadOnlyError() {
2994 * Perform a deadlock-prone transaction.
2996 * This function invokes a callback function to perform a set of write
2997 * queries. If a deadlock occurs during the processing, the transaction
2998 * will be rolled back and the callback function will be called again.
3001 * $dbw->deadlockLoop( callback, ... );
3003 * Extra arguments are passed through to the specified callback function.
3005 * Returns whatever the callback function returned on its successful,
3006 * iteration, or false on error, for example if the retry limit was
3011 public function deadlockLoop() {
3012 $this->begin( __METHOD__
);
3013 $args = func_get_args();
3014 $function = array_shift( $args );
3015 $oldIgnore = $this->ignoreErrors( true );
3016 $tries = self
::DEADLOCK_TRIES
;
3018 if ( is_array( $function ) ) {
3019 $fname = $function[0];
3025 $retVal = call_user_func_array( $function, $args );
3026 $error = $this->lastError();
3027 $errno = $this->lastErrno();
3028 $sql = $this->lastQuery();
3031 if ( $this->wasDeadlock() ) {
3033 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3035 $this->reportQueryError( $error, $errno, $sql, $fname );
3038 } while ( $this->wasDeadlock() && --$tries > 0 );
3040 $this->ignoreErrors( $oldIgnore );
3042 if ( $tries <= 0 ) {
3043 $this->rollback( __METHOD__
);
3044 $this->reportQueryError( $error, $errno, $sql, $fname );
3047 $this->commit( __METHOD__
);
3053 * Wait for the slave to catch up to a given master position.
3055 * @param $pos DBMasterPos object
3056 * @param $timeout Integer: the maximum number of seconds to wait for
3059 * @return integer: zero if the slave was past that position already,
3060 * greater than zero if we waited for some period of time, less than
3061 * zero if we timed out.
3063 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3064 wfProfileIn( __METHOD__
);
3066 if ( !is_null( $this->mFakeSlaveLag
) ) {
3067 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
3069 if ( $wait > $timeout * 1e6
) {
3070 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
3071 wfProfileOut( __METHOD__
);
3073 } elseif ( $wait > 0 ) {
3074 wfDebug( "Fake slave waiting $wait us\n" );
3076 wfProfileOut( __METHOD__
);
3079 wfDebug( "Fake slave up to date ($wait us)\n" );
3080 wfProfileOut( __METHOD__
);
3085 wfProfileOut( __METHOD__
);
3087 # Real waits are implemented in the subclass.
3092 * Get the replication position of this slave
3094 * @return DBMasterPos, or false if this is not a slave.
3096 public function getSlavePos() {
3097 if ( !is_null( $this->mFakeSlaveLag
) ) {
3098 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
3099 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
3108 * Get the position of this master
3110 * @return DBMasterPos, or false if this is not a master
3112 public function getMasterPos() {
3113 if ( $this->mFakeMaster
) {
3114 return new MySQLMasterPos( 'fake', microtime( true ) );
3121 * Run an anonymous function as soon as there is no transaction pending.
3122 * If there is a transaction and it is rolled back, then the callback is cancelled.
3123 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3124 * Callbacks must commit any transactions that they begin.
3126 * This is useful for updates to different systems or when separate transactions are needed.
3127 * For example, one might want to enqueue jobs into a system outside the database, but only
3128 * after the database is updated so that the jobs will see the data when they actually run.
3129 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3131 * @param callable $callback
3134 final public function onTransactionIdle( $callback ) {
3135 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
3136 if ( !$this->mTrxLevel
) {
3137 $this->runOnTransactionIdleCallbacks();
3142 * Run an anonymous function before the current transaction commits or now if there is none.
3143 * If there is a transaction and it is rolled back, then the callback is cancelled.
3144 * Callbacks must not start nor commit any transactions.
3146 * This is useful for updates that easily cause deadlocks if locks are held too long
3147 * but where atomicity is strongly desired for these updates and some related updates.
3149 * @param callable $callback
3152 final public function onTransactionPreCommitOrIdle( $callback ) {
3153 if ( $this->mTrxLevel
) {
3154 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
3156 $this->onTransactionIdle( $callback ); // this will trigger immediately
3161 * Actually any "on transaction idle" callbacks.
3165 protected function runOnTransactionIdleCallbacks() {
3166 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
3168 $e = null; // last exception
3169 do { // callbacks may add callbacks :)
3170 $callbacks = $this->mTrxIdleCallbacks
;
3171 $this->mTrxIdleCallbacks
= array(); // recursion guard
3172 foreach ( $callbacks as $callback ) {
3174 list( $phpCallback ) = $callback;
3175 $this->clearFlag( DBO_TRX
); // make each query its own transaction
3176 call_user_func( $phpCallback );
3177 $this->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
3178 } catch ( Exception
$e ) {}
3180 } while ( count( $this->mTrxIdleCallbacks
) );
3182 if ( $e instanceof Exception
) {
3183 throw $e; // re-throw any last exception
3188 * Actually any "on transaction pre-commit" callbacks.
3192 protected function runOnTransactionPreCommitCallbacks() {
3193 $e = null; // last exception
3194 do { // callbacks may add callbacks :)
3195 $callbacks = $this->mTrxPreCommitCallbacks
;
3196 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
3197 foreach ( $callbacks as $callback ) {
3199 list( $phpCallback ) = $callback;
3200 call_user_func( $phpCallback );
3201 } catch ( Exception
$e ) {}
3203 } while ( count( $this->mTrxPreCommitCallbacks
) );
3205 if ( $e instanceof Exception
) {
3206 throw $e; // re-throw any last exception
3211 * Begin an atomic section of statements
3213 * If a transaction has been started already, just keep track of the given
3214 * section name to make sure the transaction is not committed pre-maturely.
3215 * This function can be used in layers (with sub-sections), so use a stack
3216 * to keep track of the different atomic sections. If there is no transaction,
3217 * start one implicitly.
3219 * The goal of this function is to create an atomic section of SQL queries
3220 * without having to start a new transaction if it already exists.
3222 * Atomic sections are more strict than transactions. With transactions,
3223 * attempting to begin a new transaction when one is already running results
3224 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3225 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3226 * and any database transactions cannot be began or committed until all atomic
3227 * levels are closed. There is no such thing as implicitly opening or closing
3228 * an atomic section.
3231 * @param string $fname
3233 final public function startAtomic( $fname = __METHOD__
) {
3234 if ( !$this->mTrxLevel
) {
3235 $this->begin( $fname );
3236 $this->mTrxAutomatic
= true;
3237 $this->mTrxAutomaticAtomic
= true;
3240 $this->mTrxAtomicLevels
->push( $fname );
3244 * Begin a transaction. If a transaction is already in progress, that transaction will be committed before the
3245 * new transaction is started.
3247 * Note that when the DBO_TRX flag is set (which is usually the case for web requests, but not for maintenance scripts),
3248 * any previous database query will have started a transaction automatically.
3250 * Nesting of transactions is not supported. Attempts to nest transactions will cause a warning, unless the current
3251 * transaction was started automatically because of the DBO_TRX flag.
3253 * @param $fname string
3255 final public function begin( $fname = __METHOD__
) {
3256 global $wgDebugDBTransactions;
3258 if ( $this->mTrxLevel
) { // implicit commit
3259 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3260 // If the current transaction was an automatic atomic one, then we definitely have
3261 // a problem. Same if there is any unclosed atomic level.
3262 throw new DBUnexpectedError( $this,
3263 "Attempted to start explicit transaction when atomic levels are still open."
3265 } elseif ( !$this->mTrxAutomatic
) {
3266 // We want to warn about inadvertently nested begin/commit pairs, but not about
3267 // auto-committing implicit transactions that were started by query() via DBO_TRX
3268 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3269 " performing implicit commit!";
3271 wfLogDBError( $msg );
3273 // if the transaction was automatic and has done write operations,
3274 // log it if $wgDebugDBTransactions is enabled.
3275 if ( $this->mTrxDoneWrites
&& $wgDebugDBTransactions ) {
3276 wfDebug( "$fname: Automatic transaction with writes in progress" .
3277 " (from {$this->mTrxFname}), performing implicit commit!\n"
3282 $this->runOnTransactionPreCommitCallbacks();
3283 $this->doCommit( $fname );
3284 if ( $this->mTrxDoneWrites
) {
3285 Profiler
::instance()->transactionWritingOut( $this->mServer
, $this->mDBname
);
3287 $this->runOnTransactionIdleCallbacks();
3290 $this->doBegin( $fname );
3291 $this->mTrxFname
= $fname;
3292 $this->mTrxDoneWrites
= false;
3293 $this->mTrxAutomatic
= false;
3294 $this->mTrxAutomaticAtomic
= false;
3295 $this->mTrxAtomicLevels
= new SplStack
;
3299 * Issues the BEGIN command to the database server.
3301 * @see DatabaseBase::begin()
3302 * @param type $fname
3304 protected function doBegin( $fname ) {
3305 $this->query( 'BEGIN', $fname );
3306 $this->mTrxLevel
= 1;
3310 * Ends an atomic section of SQL statements
3312 * Ends the next section of atomic SQL statements and commits the transaction
3316 * @see DatabaseBase::startAtomic
3317 * @param string $fname
3319 final public function endAtomic( $fname = __METHOD__
) {
3320 if ( $this->mTrxAtomicLevels
->isEmpty() ||
3321 $this->mTrxAtomicLevels
->pop() !== $fname
3323 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3326 if ( $this->mTrxAtomicLevels
->isEmpty() && $this->mTrxAutomaticAtomic
) {
3327 $this->commit( $fname, 'flush' );
3332 * Commits a transaction previously started using begin().
3333 * If no transaction is in progress, a warning is issued.
3335 * Nesting of transactions is not supported.
3337 * @param $fname string
3338 * @param string $flush Flush flag, set to 'flush' to disable warnings about explicitly committing implicit
3339 * transactions, or calling commit when no transaction is in progress.
3340 * This will silently break any ongoing explicit transaction. Only set the flush flag if you are sure
3341 * that it is safe to ignore these warnings in your context.
3343 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3344 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3345 // There are still atomic sections open. This cannot be ignored
3346 throw new DBUnexpectedError( $this, "Attempted to commit transaction while atomic sections are still open" );
3349 if ( $flush != 'flush' ) {
3350 if ( !$this->mTrxLevel
) {
3351 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3352 } elseif ( $this->mTrxAutomatic
) {
3353 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3356 if ( !$this->mTrxLevel
) {
3357 return; // nothing to do
3358 } elseif ( !$this->mTrxAutomatic
) {
3359 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3363 $this->runOnTransactionPreCommitCallbacks();
3364 $this->doCommit( $fname );
3365 if ( $this->mTrxDoneWrites
) {
3366 Profiler
::instance()->transactionWritingOut( $this->mServer
, $this->mDBname
);
3368 $this->mTrxDoneWrites
= false;
3369 $this->runOnTransactionIdleCallbacks();
3373 * Issues the COMMIT command to the database server.
3375 * @see DatabaseBase::commit()
3376 * @param type $fname
3378 protected function doCommit( $fname ) {
3379 if ( $this->mTrxLevel
) {
3380 $this->query( 'COMMIT', $fname );
3381 $this->mTrxLevel
= 0;
3386 * Rollback a transaction previously started using begin().
3387 * If no transaction is in progress, a warning is issued.
3389 * No-op on non-transactional databases.
3391 * @param $fname string
3393 final public function rollback( $fname = __METHOD__
) {
3394 if ( !$this->mTrxLevel
) {
3395 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3397 $this->doRollback( $fname );
3398 $this->mTrxIdleCallbacks
= array(); // cancel
3399 $this->mTrxPreCommitCallbacks
= array(); // cancel
3400 $this->mTrxAtomicLevels
= new SplStack
;
3401 if ( $this->mTrxDoneWrites
) {
3402 Profiler
::instance()->transactionWritingOut( $this->mServer
, $this->mDBname
);
3404 $this->mTrxDoneWrites
= false;
3408 * Issues the ROLLBACK command to the database server.
3410 * @see DatabaseBase::rollback()
3411 * @param type $fname
3413 protected function doRollback( $fname ) {
3414 if ( $this->mTrxLevel
) {
3415 $this->query( 'ROLLBACK', $fname, true );
3416 $this->mTrxLevel
= 0;
3421 * Creates a new table with structure copied from existing table
3422 * Note that unlike most database abstraction functions, this function does not
3423 * automatically append database prefix, because it works at a lower
3424 * abstraction level.
3425 * The table names passed to this function shall not be quoted (this
3426 * function calls addIdentifierQuotes when needed).
3428 * @param string $oldName name of table whose structure should be copied
3429 * @param string $newName name of table to be created
3430 * @param $temporary Boolean: whether the new table should be temporary
3431 * @param string $fname calling function name
3432 * @throws MWException
3433 * @return Boolean: true if operation was successful
3435 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3438 throw new MWException(
3439 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3443 * List all tables on the database
3445 * @param string $prefix Only show tables with this prefix, e.g. mw_
3446 * @param string $fname calling function name
3447 * @throws MWException
3449 function listTables( $prefix = null, $fname = __METHOD__
) {
3450 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3454 * Reset the views process cache set by listViews()
3457 final public function clearViewsCache() {
3458 $this->allViews
= null;
3462 * Lists all the VIEWs in the database
3464 * For caching purposes the list of all views should be stored in
3465 * $this->allViews. The process cache can be cleared with clearViewsCache()
3467 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3468 * @param string $fname Name of calling function
3469 * @throws MWException
3472 public function listViews( $prefix = null, $fname = __METHOD__
) {
3473 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3477 * Differentiates between a TABLE and a VIEW
3479 * @param $name string: Name of the database-structure to test.
3480 * @throws MWException
3483 public function isView( $name ) {
3484 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3488 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3489 * to the format used for inserting into timestamp fields in this DBMS.
3491 * The result is unquoted, and needs to be passed through addQuotes()
3492 * before it can be included in raw SQL.
3494 * @param $ts string|int
3498 public function timestamp( $ts = 0 ) {
3499 return wfTimestamp( TS_MW
, $ts );
3503 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3504 * to the format used for inserting into timestamp fields in this DBMS. If
3505 * NULL is input, it is passed through, allowing NULL values to be inserted
3506 * into timestamp fields.
3508 * The result is unquoted, and needs to be passed through addQuotes()
3509 * before it can be included in raw SQL.
3511 * @param $ts string|int
3515 public function timestampOrNull( $ts = null ) {
3516 if ( is_null( $ts ) ) {
3519 return $this->timestamp( $ts );
3524 * Take the result from a query, and wrap it in a ResultWrapper if
3525 * necessary. Boolean values are passed through as is, to indicate success
3526 * of write queries or failure.
3528 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3529 * resource, and it was necessary to call this function to convert it to
3530 * a wrapper. Nowadays, raw database objects are never exposed to external
3531 * callers, so this is unnecessary in external code. For compatibility with
3532 * old code, ResultWrapper objects are passed through unaltered.
3534 * @param $result bool|ResultWrapper
3536 * @return bool|ResultWrapper
3538 public function resultObject( $result ) {
3539 if ( empty( $result ) ) {
3541 } elseif ( $result instanceof ResultWrapper
) {
3543 } elseif ( $result === true ) {
3544 // Successful write query
3547 return new ResultWrapper( $this, $result );
3552 * Ping the server and try to reconnect if it there is no connection
3554 * @return bool Success or failure
3556 public function ping() {
3557 # Stub. Not essential to override.
3562 * Get slave lag. Currently supported only by MySQL.
3564 * Note that this function will generate a fatal error on many
3565 * installations. Most callers should use LoadBalancer::safeGetLag()
3568 * @return int Database replication lag in seconds
3570 public function getLag() {
3571 return intval( $this->mFakeSlaveLag
);
3575 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3579 function maxListLen() {
3584 * Some DBMSs have a special format for inserting into blob fields, they
3585 * don't allow simple quoted strings to be inserted. To insert into such
3586 * a field, pass the data through this function before passing it to
3587 * DatabaseBase::insert().
3591 public function encodeBlob( $b ) {
3596 * Some DBMSs return a special placeholder object representing blob fields
3597 * in result objects. Pass the object through this function to return the
3602 public function decodeBlob( $b ) {
3607 * Override database's default behavior. $options include:
3608 * 'connTimeout' : Set the connection timeout value in seconds.
3609 * May be useful for very long batch queries such as
3610 * full-wiki dumps, where a single query reads out over
3613 * @param $options Array
3616 public function setSessionOptions( array $options ) {
3620 * Read and execute SQL commands from a file.
3622 * Returns true on success, error string or exception on failure (depending
3623 * on object's error ignore settings).
3625 * @param string $filename File name to open
3626 * @param bool|callable $lineCallback Optional function called before reading each line
3627 * @param bool|callable $resultCallback Optional function called for each MySQL result
3628 * @param bool|string $fname Calling function name or false if name should be
3629 * generated dynamically using $filename
3630 * @param bool|callable $inputCallback Callback: Optional function called for each complete line sent
3631 * @throws MWException
3632 * @throws Exception|MWException
3633 * @return bool|string
3635 public function sourceFile(
3636 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3638 wfSuppressWarnings();
3639 $fp = fopen( $filename, 'r' );
3640 wfRestoreWarnings();
3642 if ( false === $fp ) {
3643 throw new MWException( "Could not open \"{$filename}\".\n" );
3647 $fname = __METHOD__
. "( $filename )";
3651 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3653 catch ( MWException
$e ) {
3664 * Get the full path of a patch file. Originally based on archive()
3665 * from updaters.inc. Keep in mind this always returns a patch, as
3666 * it fails back to MySQL if no DB-specific patch can be found
3668 * @param string $patch The name of the patch, like patch-something.sql
3669 * @return String Full path to patch file
3671 public function patchPath( $patch ) {
3674 $dbType = $this->getType();
3675 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3676 return "$IP/maintenance/$dbType/archives/$patch";
3678 return "$IP/maintenance/archives/$patch";
3683 * Set variables to be used in sourceFile/sourceStream, in preference to the
3684 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3685 * all. If it's set to false, $GLOBALS will be used.
3687 * @param bool|array $vars mapping variable name to value.
3689 public function setSchemaVars( $vars ) {
3690 $this->mSchemaVars
= $vars;
3694 * Read and execute commands from an open file handle.
3696 * Returns true on success, error string or exception on failure (depending
3697 * on object's error ignore settings).
3699 * @param $fp Resource: File handle
3700 * @param $lineCallback Callback: Optional function called before reading each query
3701 * @param $resultCallback Callback: Optional function called for each MySQL result
3702 * @param string $fname Calling function name
3703 * @param $inputCallback Callback: Optional function called for each complete query sent
3704 * @return bool|string
3706 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3707 $fname = __METHOD__
, $inputCallback = false )
3711 while ( !feof( $fp ) ) {
3712 if ( $lineCallback ) {
3713 call_user_func( $lineCallback );
3716 $line = trim( fgets( $fp ) );
3718 if ( $line == '' ) {
3722 if ( '-' == $line[0] && '-' == $line[1] ) {
3730 $done = $this->streamStatementEnd( $cmd, $line );
3734 if ( $done ||
feof( $fp ) ) {
3735 $cmd = $this->replaceVars( $cmd );
3737 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3738 $res = $this->query( $cmd, $fname );
3740 if ( $resultCallback ) {
3741 call_user_func( $resultCallback, $res, $this );
3744 if ( false === $res ) {
3745 $err = $this->lastError();
3746 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3757 * Called by sourceStream() to check if we've reached a statement end
3759 * @param string $sql SQL assembled so far
3760 * @param string $newLine New line about to be added to $sql
3761 * @return Bool Whether $newLine contains end of the statement
3763 public function streamStatementEnd( &$sql, &$newLine ) {
3764 if ( $this->delimiter
) {
3766 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3767 if ( $newLine != $prev ) {
3775 * Database independent variable replacement. Replaces a set of variables
3776 * in an SQL statement with their contents as given by $this->getSchemaVars().
3778 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3780 * - '{$var}' should be used for text and is passed through the database's
3782 * - `{$var}` should be used for identifiers (eg: table and database names),
3783 * it is passed through the database's addIdentifierQuotes method which
3784 * can be overridden if the database uses something other than backticks.
3785 * - / *$var* / is just encoded, besides traditional table prefix and
3786 * table options its use should be avoided.
3788 * @param string $ins SQL statement to replace variables in
3789 * @return String The new SQL statement with variables replaced
3791 protected function replaceSchemaVars( $ins ) {
3792 $vars = $this->getSchemaVars();
3793 foreach ( $vars as $var => $value ) {
3795 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
3797 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
3799 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ), $ins );
3805 * Replace variables in sourced SQL
3807 * @param $ins string
3811 protected function replaceVars( $ins ) {
3812 $ins = $this->replaceSchemaVars( $ins );
3815 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3816 array( $this, 'tableNameCallback' ), $ins );
3819 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
3820 array( $this, 'indexNameCallback' ), $ins );
3826 * Get schema variables. If none have been set via setSchemaVars(), then
3827 * use some defaults from the current object.
3831 protected function getSchemaVars() {
3832 if ( $this->mSchemaVars
) {
3833 return $this->mSchemaVars
;
3835 return $this->getDefaultSchemaVars();
3840 * Get schema variables to use if none have been set via setSchemaVars().
3842 * Override this in derived classes to provide variables for tables.sql
3843 * and SQL patch files.
3847 protected function getDefaultSchemaVars() {
3852 * Table name callback
3854 * @param $matches array
3858 protected function tableNameCallback( $matches ) {
3859 return $this->tableName( $matches[1] );
3863 * Index name callback
3865 * @param $matches array
3869 protected function indexNameCallback( $matches ) {
3870 return $this->indexName( $matches[1] );
3874 * Check to see if a named lock is available. This is non-blocking.
3876 * @param string $lockName name of lock to poll
3877 * @param string $method name of method calling us
3881 public function lockIsFree( $lockName, $method ) {
3886 * Acquire a named lock
3888 * Abstracted from Filestore::lock() so child classes can implement for
3891 * @param string $lockName name of lock to aquire
3892 * @param string $method name of method calling us
3893 * @param $timeout Integer: timeout
3896 public function lock( $lockName, $method, $timeout = 5 ) {
3903 * @param string $lockName Name of lock to release
3904 * @param string $method Name of method calling us
3906 * @return int Returns 1 if the lock was released, 0 if the lock was not established
3907 * by this thread (in which case the lock is not released), and NULL if the named
3908 * lock did not exist
3910 public function unlock( $lockName, $method ) {
3915 * Lock specific tables
3917 * @param array $read of tables to lock for read access
3918 * @param array $write of tables to lock for write access
3919 * @param string $method name of caller
3920 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3924 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3929 * Unlock specific tables
3931 * @param string $method the caller
3935 public function unlockTables( $method ) {
3941 * @param $tableName string
3942 * @param $fName string
3943 * @return bool|ResultWrapper
3946 public function dropTable( $tableName, $fName = __METHOD__
) {
3947 if ( !$this->tableExists( $tableName, $fName ) ) {
3950 $sql = "DROP TABLE " . $this->tableName( $tableName );
3951 if ( $this->cascadingDeletes() ) {
3954 return $this->query( $sql, $fName );
3958 * Get search engine class. All subclasses of this need to implement this
3959 * if they wish to use searching.
3963 public function getSearchEngine() {
3964 return 'SearchEngineDummy';
3968 * Find out when 'infinity' is. Most DBMSes support this. This is a special
3969 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
3970 * because "i" sorts after all numbers.
3974 public function getInfinity() {
3979 * Encode an expiry time into the DBMS dependent format
3981 * @param string $expiry timestamp for expiry, or the 'infinity' string
3984 public function encodeExpiry( $expiry ) {
3985 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3986 ?
$this->getInfinity()
3987 : $this->timestamp( $expiry );
3991 * Decode an expiry time into a DBMS independent format
3993 * @param string $expiry DB timestamp field value for expiry
3994 * @param $format integer: TS_* constant, defaults to TS_MW
3997 public function decodeExpiry( $expiry, $format = TS_MW
) {
3998 return ( $expiry == '' ||
$expiry == $this->getInfinity() )
4000 : wfTimestamp( $format, $expiry );
4004 * Allow or deny "big selects" for this session only. This is done by setting
4005 * the sql_big_selects session variable.
4007 * This is a MySQL-specific feature.
4009 * @param $value Mixed: true for allow, false for deny, or "default" to
4010 * restore the initial value
4012 public function setBigSelects( $value = true ) {
4019 public function __toString() {
4020 return (string)$this->mConn
;
4024 * Run a few simple sanity checks
4026 public function __destruct() {
4027 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
4028 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4030 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
4032 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
4033 $callers[] = $callbackInfo[1];
4036 $callers = implode( ', ', $callers );
4037 trigger_error( "DB transaction callbacks still pending (from $callers)." );