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;
304 # ------------------------------------------------------------------------------
306 # ------------------------------------------------------------------------------
307 # These optionally set a variable and return the previous state
310 * A string describing the current software version, and possibly
311 * other details in a user-friendly way. Will be listed on Special:Version, etc.
312 * Use getServerVersion() to get machine-friendly information.
314 * @return string: Version information from the database server
316 public function getServerInfo() {
317 return $this->getServerVersion();
321 * @return string: command delimiter used by this database engine
323 public function getDelimiter() {
324 return $this->delimiter
;
328 * Boolean, controls output of large amounts of debug information.
329 * @param $debug bool|null
330 * - true to enable debugging
331 * - false to disable debugging
332 * - omitted or null to do nothing
334 * @return bool|null previous value of the flag
336 public function debug( $debug = null ) {
337 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
341 * Turns buffering of SQL result sets on (true) or off (false). Default is
344 * Unbuffered queries are very troublesome in MySQL:
346 * - If another query is executed while the first query is being read
347 * out, the first query is killed. This means you can't call normal
348 * MediaWiki functions while you are reading an unbuffered query result
349 * from a normal wfGetDB() connection.
351 * - Unbuffered queries cause the MySQL server to use large amounts of
352 * memory and to hold broad locks which block other queries.
354 * If you want to limit client-side memory, it's almost always better to
355 * split up queries into batches using a LIMIT clause than to switch off
358 * @param $buffer null|bool
360 * @return null|bool The previous value of the flag
362 public function bufferResults( $buffer = null ) {
363 if ( is_null( $buffer ) ) {
364 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
366 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
371 * Turns on (false) or off (true) the automatic generation and sending
372 * of a "we're sorry, but there has been a database error" page on
373 * database errors. Default is on (false). When turned off, the
374 * code should use lastErrno() and lastError() to handle the
375 * situation as appropriate.
377 * Do not use this function outside of the Database classes.
379 * @param $ignoreErrors bool|null
381 * @return bool The previous value of the flag.
383 public function ignoreErrors( $ignoreErrors = null ) {
384 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
388 * Gets or sets the current transaction level.
390 * Historically, transactions were allowed to be "nested". This is no
391 * longer supported, so this function really only returns a boolean.
393 * @param int $level An integer (0 or 1), or omitted to leave it unchanged.
394 * @return int The previous value
396 public function trxLevel( $level = null ) {
397 return wfSetVar( $this->mTrxLevel
, $level );
401 * Get/set the number of errors logged. Only useful when errors are ignored
402 * @param int $count The count to set, or omitted to leave it unchanged.
403 * @return int The error count
405 public function errorCount( $count = null ) {
406 return wfSetVar( $this->mErrorCount
, $count );
410 * Get/set the table prefix.
411 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
412 * @return string The previous table prefix.
414 public function tablePrefix( $prefix = null ) {
415 return wfSetVar( $this->mTablePrefix
, $prefix );
419 * Set the filehandle to copy write statements to.
421 * @param $fh filehandle
423 public function setFileHandle( $fh ) {
424 $this->fileHandle
= $fh;
428 * Get properties passed down from the server info array of the load
431 * @param string $name The entry of the info array to get, or null to get the
434 * @return LoadBalancer|null
436 public function getLBInfo( $name = null ) {
437 if ( is_null( $name ) ) {
438 return $this->mLBInfo
;
440 if ( array_key_exists( $name, $this->mLBInfo
) ) {
441 return $this->mLBInfo
[$name];
449 * Set the LB info array, or a member of it. If called with one parameter,
450 * the LB info array is set to that parameter. If it is called with two
451 * parameters, the member with the given name is set to the given value.
456 public function setLBInfo( $name, $value = null ) {
457 if ( is_null( $value ) ) {
458 $this->mLBInfo
= $name;
460 $this->mLBInfo
[$name] = $value;
465 * Set lag time in seconds for a fake slave
469 public function setFakeSlaveLag( $lag ) {
470 $this->mFakeSlaveLag
= $lag;
474 * Make this connection a fake master
476 * @param $enabled bool
478 public function setFakeMaster( $enabled = true ) {
479 $this->mFakeMaster
= $enabled;
483 * Returns true if this database supports (and uses) cascading deletes
487 public function cascadingDeletes() {
492 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
496 public function cleanupTriggers() {
501 * Returns true if this database is strict about what can be put into an IP field.
502 * Specifically, it uses a NULL value instead of an empty string.
506 public function strictIPs() {
511 * Returns true if this database uses timestamps rather than integers
515 public function realTimestamps() {
520 * Returns true if this database does an implicit sort when doing GROUP BY
524 public function implicitGroupby() {
529 * Returns true if this database does an implicit order by when the column has an index
530 * For example: SELECT page_title FROM page LIMIT 1
534 public function implicitOrderby() {
539 * Returns true if this database can do a native search on IP columns
540 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
544 public function searchableIPs() {
549 * Returns true if this database can use functional indexes
553 public function functionalIndexes() {
558 * Return the last query that went through DatabaseBase::query()
561 public function lastQuery() {
562 return $this->mLastQuery
;
566 * Returns true if the connection may have been used for write queries.
567 * Should return true if unsure.
571 public function doneWrites() {
572 return $this->mDoneWrites
;
576 * Returns true if there is a transaction open with possible write
577 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
581 public function writesOrCallbacksPending() {
582 return $this->mTrxLevel
&& (
583 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
588 * Is a connection to the database open?
591 public function isOpen() {
592 return $this->mOpened
;
596 * Set a flag for this connection
598 * @param $flag Integer: DBO_* constants from Defines.php:
599 * - DBO_DEBUG: output some debug info (same as debug())
600 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
601 * - DBO_TRX: automatically start transactions
602 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
603 * and removes it in command line mode
604 * - DBO_PERSISTENT: use persistant database connection
606 public function setFlag( $flag ) {
607 global $wgDebugDBTransactions;
608 $this->mFlags |
= $flag;
609 if ( ( $flag & DBO_TRX
) & $wgDebugDBTransactions ) {
610 wfDebug( "Implicit transactions are now disabled.\n" );
615 * Clear a flag for this connection
617 * @param $flag: same as setFlag()'s $flag param
619 public function clearFlag( $flag ) {
620 global $wgDebugDBTransactions;
621 $this->mFlags
&= ~
$flag;
622 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
623 wfDebug( "Implicit transactions are now disabled.\n" );
628 * Returns a boolean whether the flag $flag is set for this connection
630 * @param $flag: same as setFlag()'s $flag param
633 public function getFlag( $flag ) {
634 return !!( $this->mFlags
& $flag );
638 * General read-only accessor
640 * @param $name string
644 public function getProperty( $name ) {
651 public function getWikiID() {
652 if ( $this->mTablePrefix
) {
653 return "{$this->mDBname}-{$this->mTablePrefix}";
655 return $this->mDBname
;
660 * Return a path to the DBMS-specific schema file, otherwise default to tables.sql
664 public function getSchemaPath() {
666 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
667 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
669 return "$IP/maintenance/tables.sql";
673 # ------------------------------------------------------------------------------
675 # ------------------------------------------------------------------------------
680 * FIXME: It is possible to construct a Database object with no associated
681 * connection object, by specifying no parameters to __construct(). This
682 * feature is deprecated and should be removed.
684 * FIXME: The long list of formal parameters here is not really appropriate
685 * for MySQL, and not at all appropriate for any other DBMS. It should be
686 * replaced by named parameters as in DatabaseBase::factory().
688 * DatabaseBase subclasses should not be constructed directly in external
689 * code. DatabaseBase::factory() should be used instead.
691 * @param string $server database server host
692 * @param string $user database user name
693 * @param string $password database user password
694 * @param string $dbName database name
696 * @param string $tablePrefix database table prefixes. By default use the prefix gave in LocalSettings.php
697 * @param bool $foreign disable some operations specific to local databases
699 function __construct( $server = false, $user = false, $password = false, $dbName = false,
700 $flags = 0, $tablePrefix = 'get from global', $foreign = false
702 global $wgDBprefix, $wgCommandLineMode, $wgDebugDBTransactions;
704 $this->mTrxAtomicLevels
= new SplStack
;
705 $this->mFlags
= $flags;
707 if ( $this->mFlags
& DBO_DEFAULT
) {
708 if ( $wgCommandLineMode ) {
709 $this->mFlags
&= ~DBO_TRX
;
710 if ( $wgDebugDBTransactions ) {
711 wfDebug( "Implicit transaction open disabled.\n" );
714 $this->mFlags |
= DBO_TRX
;
715 if ( $wgDebugDBTransactions ) {
716 wfDebug( "Implicit transaction open enabled.\n" );
721 /** Get the default table prefix*/
722 if ( $tablePrefix == 'get from global' ) {
723 $this->mTablePrefix
= $wgDBprefix;
725 $this->mTablePrefix
= $tablePrefix;
728 $this->mForeign
= $foreign;
731 $this->open( $server, $user, $password, $dbName );
736 * Called by serialize. Throw an exception when DB connection is serialized.
737 * This causes problems on some database engines because the connection is
738 * not restored on unserialize.
740 public function __sleep() {
741 throw new MWException( 'Database serialization may cause problems, since the connection is not restored on wakeup.' );
745 * Given a DB type, construct the name of the appropriate child class of
746 * DatabaseBase. This is designed to replace all of the manual stuff like:
747 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
748 * as well as validate against the canonical list of DB types we have
750 * This factory function is mostly useful for when you need to connect to a
751 * database other than the MediaWiki default (such as for external auth,
752 * an extension, et cetera). Do not use this to connect to the MediaWiki
753 * database. Example uses in core:
754 * @see LoadBalancer::reallyOpenConnection()
755 * @see ForeignDBRepo::getMasterDB()
756 * @see WebInstaller_DBConnect::execute()
760 * @param string $dbType A possible DB type
761 * @param array $p An array of options to pass to the constructor.
762 * Valid options are: host, user, password, dbname, flags, tablePrefix, driver
763 * @return DatabaseBase subclass or null
765 final public static function factory( $dbType, $p = array() ) {
766 $canonicalDBTypes = array(
767 'mysql' => array( 'mysqli', 'mysql' ),
768 'postgres' => array(),
775 $dbType = strtolower( $dbType );
776 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
777 $possibleDrivers = $canonicalDBTypes[$dbType];
778 if ( !empty( $p['driver'] ) ) {
779 if ( in_array( $p['driver'], $possibleDrivers ) ) {
780 $driver = $p['driver'];
782 throw new MWException( __METHOD__
.
783 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
786 foreach ( $possibleDrivers as $posDriver ) {
787 if ( extension_loaded( $posDriver ) ) {
788 $driver = $posDriver;
796 if ( $driver === false ) {
797 throw new MWException( __METHOD__
.
798 " no viable database extension found for type '$dbType'" );
801 $class = 'Database' . ucfirst( $driver );
802 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
804 isset( $p['host'] ) ?
$p['host'] : false,
805 isset( $p['user'] ) ?
$p['user'] : false,
806 isset( $p['password'] ) ?
$p['password'] : false,
807 isset( $p['dbname'] ) ?
$p['dbname'] : false,
808 isset( $p['flags'] ) ?
$p['flags'] : 0,
809 isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global',
810 isset( $p['foreign'] ) ?
$p['foreign'] : false
817 protected function installErrorHandler() {
818 $this->mPHPError
= false;
819 $this->htmlErrors
= ini_set( 'html_errors', '0' );
820 set_error_handler( array( $this, 'connectionErrorHandler' ) );
824 * @return bool|string
826 protected function restoreErrorHandler() {
827 restore_error_handler();
828 if ( $this->htmlErrors
!== false ) {
829 ini_set( 'html_errors', $this->htmlErrors
);
831 if ( $this->mPHPError
) {
832 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
833 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
845 public function connectionErrorHandler( $errno, $errstr ) {
846 $this->mPHPError
= $errstr;
850 * Closes a database connection.
851 * if it is open : commits any open transactions
853 * @throws MWException
854 * @return Bool operation success. true if already closed.
856 public function close() {
857 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
858 throw new MWException( "Transaction idle callbacks still pending." );
860 $this->mOpened
= false;
861 if ( $this->mConn
) {
862 if ( $this->trxLevel() ) {
863 if ( !$this->mTrxAutomatic
) {
864 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
865 " performing implicit commit before closing connection!" );
868 $this->commit( __METHOD__
, 'flush' );
871 $ret = $this->closeConnection();
872 $this->mConn
= false;
880 * Closes underlying database connection
882 * @return bool: Whether connection was closed successfully
884 abstract protected function closeConnection();
887 * @param string $error fallback error message, used if none is given by DB
888 * @throws DBConnectionError
890 function reportConnectionError( $error = 'Unknown error' ) {
891 $myError = $this->lastError();
897 throw new DBConnectionError( $this, $error );
901 * The DBMS-dependent part of query()
903 * @param $sql String: SQL query.
904 * @return ResultWrapper Result object to feed to fetchObject, fetchRow, ...; or false on failure
906 abstract protected function doQuery( $sql );
909 * Determine whether a query writes to the DB.
910 * Should return true if unsure.
916 public function isWriteQuery( $sql ) {
917 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
921 * Run an SQL query and return the result. Normally throws a DBQueryError
922 * on failure. If errors are ignored, returns false instead.
924 * In new code, the query wrappers select(), insert(), update(), delete(),
925 * etc. should be used where possible, since they give much better DBMS
926 * independence and automatically quote or validate user input in a variety
927 * of contexts. This function is generally only useful for queries which are
928 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
931 * However, the query wrappers themselves should call this function.
933 * @param $sql String: SQL query
934 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
935 * comment (you can use __METHOD__ or add some extra info)
936 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
937 * maybe best to catch the exception instead?
938 * @throws MWException
939 * @return boolean|ResultWrapper. true for a successful write query, ResultWrapper object
940 * for a successful read query, or false on failure if $tempIgnore set
942 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
943 global $wgUser, $wgDebugDBTransactions;
945 $this->mLastQuery
= $sql;
946 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
947 # Set a flag indicating that writes have been done
948 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
949 $this->mDoneWrites
= true;
952 # Add a comment for easy SHOW PROCESSLIST interpretation
953 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
954 $userName = $wgUser->getName();
955 if ( mb_strlen( $userName ) > 15 ) {
956 $userName = mb_substr( $userName, 0, 15 ) . '...';
958 $userName = str_replace( '/', '', $userName );
963 // Add trace comment to the begin of the sql string, right after the operator.
964 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
965 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
967 # If DBO_TRX is set, start a transaction
968 if ( ( $this->mFlags
& DBO_TRX
) && !$this->mTrxLevel
&&
969 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' )
971 # Avoid establishing transactions for SHOW and SET statements too -
972 # that would delay transaction initializations to once connection
973 # is really used by application
974 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
975 if ( strpos( $sqlstart, "SHOW " ) !== 0 && strpos( $sqlstart, "SET " ) !== 0 ) {
976 if ( $wgDebugDBTransactions ) {
977 wfDebug( "Implicit transaction start.\n" );
979 $this->begin( __METHOD__
. " ($fname)" );
980 $this->mTrxAutomatic
= true;
984 # Keep track of whether the transaction has write queries pending
985 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $this->isWriteQuery( $sql ) ) {
986 $this->mTrxDoneWrites
= true;
987 Profiler
::instance()->transactionWritingIn( $this->mServer
, $this->mDBname
);
990 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
991 if ( !Profiler
::instance()->isStub() ) {
992 # generalizeSQL will probably cut down the query to reasonable
993 # logging size most of the time. The substr is really just a sanity check.
995 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
996 $totalProf = 'DatabaseBase::query-master';
998 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
999 $totalProf = 'DatabaseBase::query';
1001 wfProfileIn( $totalProf );
1002 wfProfileIn( $queryProf );
1005 if ( $this->debug() ) {
1009 $sqlx = substr( $commentedSql, 0, 500 );
1010 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1012 $master = $isMaster ?
'master' : 'slave';
1013 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1016 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
1018 # Do the query and handle errors
1019 $ret = $this->doQuery( $commentedSql );
1021 MWDebug
::queryTime( $queryId );
1023 # Try reconnecting if the connection was lost
1024 if ( false === $ret && $this->wasErrorReissuable() ) {
1025 # Transaction is gone, like it or not
1026 $this->mTrxLevel
= 0;
1027 $this->mTrxIdleCallbacks
= array(); // cancel
1028 $this->mTrxPreCommitCallbacks
= array(); // cancel
1029 wfDebug( "Connection lost, reconnecting...\n" );
1031 if ( $this->ping() ) {
1032 wfDebug( "Reconnected\n" );
1033 $sqlx = substr( $commentedSql, 0, 500 );
1034 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1035 global $wgRequestTime;
1036 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
1037 if ( $elapsed < 300 ) {
1038 # Not a database error to lose a transaction after a minute or two
1039 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
1041 $ret = $this->doQuery( $commentedSql );
1043 wfDebug( "Failed\n" );
1047 if ( false === $ret ) {
1048 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1051 if ( !Profiler
::instance()->isStub() ) {
1052 wfProfileOut( $queryProf );
1053 wfProfileOut( $totalProf );
1056 return $this->resultObject( $ret );
1060 * Report a query error. Log the error, and if neither the object ignore
1061 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1063 * @param $error String
1064 * @param $errno Integer
1065 * @param $sql String
1066 * @param $fname String
1067 * @param $tempIgnore Boolean
1068 * @throws DBQueryError
1070 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1071 # Ignore errors during error handling to avoid infinite recursion
1072 $ignore = $this->ignoreErrors( true );
1073 ++
$this->mErrorCount
;
1075 if ( $ignore ||
$tempIgnore ) {
1076 wfDebug( "SQL ERROR (ignored): $error\n" );
1077 $this->ignoreErrors( $ignore );
1079 $sql1line = str_replace( "\n", "\\n", $sql );
1080 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
1081 wfDebug( "SQL ERROR: " . $error . "\n" );
1082 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1087 * Intended to be compatible with the PEAR::DB wrapper functions.
1088 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1090 * ? = scalar value, quoted as necessary
1091 * ! = raw SQL bit (a function for instance)
1092 * & = filename; reads the file and inserts as a blob
1093 * (we don't use this though...)
1095 * @param $sql string
1096 * @param $func string
1100 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1101 /* MySQL doesn't support prepared statements (yet), so just
1102 pack up the query for reference. We'll manually replace
1104 return array( 'query' => $sql, 'func' => $func );
1108 * Free a prepared query, generated by prepare().
1111 protected function freePrepared( $prepared ) {
1112 /* No-op by default */
1116 * Execute a prepared query with the various arguments
1117 * @param string $prepared the prepared sql
1118 * @param $args Mixed: Either an array here, or put scalars as varargs
1120 * @return ResultWrapper
1122 public function execute( $prepared, $args = null ) {
1123 if ( !is_array( $args ) ) {
1125 $args = func_get_args();
1126 array_shift( $args );
1129 $sql = $this->fillPrepared( $prepared['query'], $args );
1131 return $this->query( $sql, $prepared['func'] );
1135 * For faking prepared SQL statements on DBs that don't support it directly.
1137 * @param string $preparedQuery a 'preparable' SQL statement
1138 * @param array $args of arguments to fill it with
1139 * @return string executable SQL
1141 public function fillPrepared( $preparedQuery, $args ) {
1143 $this->preparedArgs
=& $args;
1145 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1146 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1150 * preg_callback func for fillPrepared()
1151 * The arguments should be in $this->preparedArgs and must not be touched
1152 * while we're doing this.
1154 * @param $matches Array
1155 * @throws DBUnexpectedError
1158 protected function fillPreparedArg( $matches ) {
1159 switch ( $matches[1] ) {
1168 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1170 switch ( $matches[1] ) {
1172 return $this->addQuotes( $arg );
1176 # return $this->addQuotes( file_get_contents( $arg ) );
1177 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
1179 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
1184 * Free a result object returned by query() or select(). It's usually not
1185 * necessary to call this, just use unset() or let the variable holding
1186 * the result object go out of scope.
1188 * @param $res Mixed: A SQL result
1190 public function freeResult( $res ) {
1194 * A SELECT wrapper which returns a single field from a single result row.
1196 * Usually throws a DBQueryError on failure. If errors are explicitly
1197 * ignored, returns false on failure.
1199 * If no result rows are returned from the query, false is returned.
1201 * @param string|array $table Table name. See DatabaseBase::select() for details.
1202 * @param string $var The field name to select. This must be a valid SQL
1203 * fragment: do not use unvalidated user input.
1204 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1205 * @param string $fname The function name of the caller.
1206 * @param string|array $options The query options. See DatabaseBase::select() for details.
1208 * @return bool|mixed The value from the field, or false on failure.
1210 public function selectField( $table, $var, $cond = '', $fname = __METHOD__
,
1213 if ( !is_array( $options ) ) {
1214 $options = array( $options );
1217 $options['LIMIT'] = 1;
1219 $res = $this->select( $table, $var, $cond, $fname, $options );
1221 if ( $res === false ||
!$this->numRows( $res ) ) {
1225 $row = $this->fetchRow( $res );
1227 if ( $row !== false ) {
1228 return reset( $row );
1235 * Returns an optional USE INDEX clause to go after the table, and a
1236 * string to go at the end of the query.
1238 * @param array $options associative array of options to be turned into
1239 * an SQL query, valid keys are listed in the function.
1241 * @see DatabaseBase::select()
1243 public function makeSelectOptions( $options ) {
1244 $preLimitTail = $postLimitTail = '';
1247 $noKeyOptions = array();
1249 foreach ( $options as $key => $option ) {
1250 if ( is_numeric( $key ) ) {
1251 $noKeyOptions[$option] = true;
1255 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1257 $preLimitTail .= $this->makeOrderBy( $options );
1259 // if (isset($options['LIMIT'])) {
1260 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1261 // isset($options['OFFSET']) ? $options['OFFSET']
1265 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1266 $postLimitTail .= ' FOR UPDATE';
1269 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1270 $postLimitTail .= ' LOCK IN SHARE MODE';
1273 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1274 $startOpts .= 'DISTINCT';
1277 # Various MySQL extensions
1278 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1279 $startOpts .= ' /*! STRAIGHT_JOIN */';
1282 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1283 $startOpts .= ' HIGH_PRIORITY';
1286 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1287 $startOpts .= ' SQL_BIG_RESULT';
1290 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1291 $startOpts .= ' SQL_BUFFER_RESULT';
1294 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1295 $startOpts .= ' SQL_SMALL_RESULT';
1298 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1299 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1302 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1303 $startOpts .= ' SQL_CACHE';
1306 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1307 $startOpts .= ' SQL_NO_CACHE';
1310 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1311 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1316 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1320 * Returns an optional GROUP BY with an optional HAVING
1322 * @param array $options associative array of options
1324 * @see DatabaseBase::select()
1327 public function makeGroupByWithHaving( $options ) {
1329 if ( isset( $options['GROUP BY'] ) ) {
1330 $gb = is_array( $options['GROUP BY'] )
1331 ?
implode( ',', $options['GROUP BY'] )
1332 : $options['GROUP BY'];
1333 $sql .= ' GROUP BY ' . $gb;
1335 if ( isset( $options['HAVING'] ) ) {
1336 $having = is_array( $options['HAVING'] )
1337 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1338 : $options['HAVING'];
1339 $sql .= ' HAVING ' . $having;
1345 * Returns an optional ORDER BY
1347 * @param array $options associative array of options
1349 * @see DatabaseBase::select()
1352 public function makeOrderBy( $options ) {
1353 if ( isset( $options['ORDER BY'] ) ) {
1354 $ob = is_array( $options['ORDER BY'] )
1355 ?
implode( ',', $options['ORDER BY'] )
1356 : $options['ORDER BY'];
1357 return ' ORDER BY ' . $ob;
1363 * Execute a SELECT query constructed using the various parameters provided.
1364 * See below for full details of the parameters.
1366 * @param string|array $table Table name
1367 * @param string|array $vars Field names
1368 * @param string|array $conds Conditions
1369 * @param string $fname Caller function name
1370 * @param array $options Query options
1371 * @param $join_conds Array Join conditions
1373 * @param $table string|array
1375 * May be either an array of table names, or a single string holding a table
1376 * name. If an array is given, table aliases can be specified, for example:
1378 * array( 'a' => 'user' )
1380 * This includes the user table in the query, with the alias "a" available
1381 * for use in field names (e.g. a.user_name).
1383 * All of the table names given here are automatically run through
1384 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1385 * added, and various other table name mappings to be performed.
1388 * @param $vars string|array
1390 * May be either a field name or an array of field names. The field names
1391 * can be complete fragments of SQL, for direct inclusion into the SELECT
1392 * query. If an array is given, field aliases can be specified, for example:
1394 * array( 'maxrev' => 'MAX(rev_id)' )
1396 * This includes an expression with the alias "maxrev" in the query.
1398 * If an expression is given, care must be taken to ensure that it is
1402 * @param $conds string|array
1404 * May be either a string containing a single condition, or an array of
1405 * conditions. If an array is given, the conditions constructed from each
1406 * element are combined with AND.
1408 * Array elements may take one of two forms:
1410 * - Elements with a numeric key are interpreted as raw SQL fragments.
1411 * - Elements with a string key are interpreted as equality conditions,
1412 * where the key is the field name.
1413 * - If the value of such an array element is a scalar (such as a
1414 * string), it will be treated as data and thus quoted appropriately.
1415 * If it is null, an IS NULL clause will be added.
1416 * - If the value is an array, an IN(...) clause will be constructed,
1417 * such that the field name may match any of the elements in the
1418 * array. The elements of the array will be quoted.
1420 * Note that expressions are often DBMS-dependent in their syntax.
1421 * DBMS-independent wrappers are provided for constructing several types of
1422 * expression commonly used in condition queries. See:
1423 * - DatabaseBase::buildLike()
1424 * - DatabaseBase::conditional()
1427 * @param $options string|array
1429 * Optional: Array of query options. Boolean options are specified by
1430 * including them in the array as a string value with a numeric key, for
1433 * array( 'FOR UPDATE' )
1435 * The supported options are:
1437 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1438 * with LIMIT can theoretically be used for paging through a result set,
1439 * but this is discouraged in MediaWiki for performance reasons.
1441 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1442 * and then the first rows are taken until the limit is reached. LIMIT
1443 * is applied to a result set after OFFSET.
1445 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1446 * changed until the next COMMIT.
1448 * - DISTINCT: Boolean: return only unique result rows.
1450 * - GROUP BY: May be either an SQL fragment string naming a field or
1451 * expression to group by, or an array of such SQL fragments.
1453 * - HAVING: May be either an string containing a HAVING clause or an array of
1454 * conditions building the HAVING clause. If an array is given, the conditions
1455 * constructed from each element are combined with AND.
1457 * - ORDER BY: May be either an SQL fragment giving a field name or
1458 * expression to order by, or an array of such SQL fragments.
1460 * - USE INDEX: This may be either a string giving the index name to use
1461 * for the query, or an array. If it is an associative array, each key
1462 * gives the table name (or alias), each value gives the index name to
1463 * use for that table. All strings are SQL fragments and so should be
1464 * validated by the caller.
1466 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1467 * instead of SELECT.
1469 * And also the following boolean MySQL extensions, see the MySQL manual
1470 * for documentation:
1472 * - LOCK IN SHARE MODE
1476 * - SQL_BUFFER_RESULT
1477 * - SQL_SMALL_RESULT
1478 * - SQL_CALC_FOUND_ROWS
1483 * @param $join_conds string|array
1485 * Optional associative array of table-specific join conditions. In the
1486 * most common case, this is unnecessary, since the join condition can be
1487 * in $conds. However, it is useful for doing a LEFT JOIN.
1489 * The key of the array contains the table name or alias. The value is an
1490 * array with two elements, numbered 0 and 1. The first gives the type of
1491 * join, the second is an SQL fragment giving the join condition for that
1492 * table. For example:
1494 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1496 * @return ResultWrapper. If the query returned no rows, a ResultWrapper
1497 * with no rows in it will be returned. If there was a query error, a
1498 * DBQueryError exception will be thrown, except if the "ignore errors"
1499 * option was set, in which case false will be returned.
1501 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1502 $options = array(), $join_conds = array() ) {
1503 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1505 return $this->query( $sql, $fname );
1509 * The equivalent of DatabaseBase::select() except that the constructed SQL
1510 * is returned, instead of being immediately executed. This can be useful for
1511 * doing UNION queries, where the SQL text of each query is needed. In general,
1512 * however, callers outside of Database classes should just use select().
1514 * @param string|array $table Table name
1515 * @param string|array $vars Field names
1516 * @param string|array $conds Conditions
1517 * @param string $fname Caller function name
1518 * @param string|array $options Query options
1519 * @param $join_conds string|array Join conditions
1521 * @return string SQL query string.
1522 * @see DatabaseBase::select()
1524 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1525 $options = array(), $join_conds = array() )
1527 if ( is_array( $vars ) ) {
1528 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1531 $options = (array)$options;
1532 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1533 ?
$options['USE INDEX']
1536 if ( is_array( $table ) ) {
1538 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1539 } elseif ( $table != '' ) {
1540 if ( $table[0] == ' ' ) {
1541 $from = ' FROM ' . $table;
1544 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1550 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1551 $this->makeSelectOptions( $options );
1553 if ( !empty( $conds ) ) {
1554 if ( is_array( $conds ) ) {
1555 $conds = $this->makeList( $conds, LIST_AND
);
1557 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1559 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1562 if ( isset( $options['LIMIT'] ) ) {
1563 $sql = $this->limitResult( $sql, $options['LIMIT'],
1564 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1566 $sql = "$sql $postLimitTail";
1568 if ( isset( $options['EXPLAIN'] ) ) {
1569 $sql = 'EXPLAIN ' . $sql;
1576 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1577 * that a single row object is returned. If the query returns no rows,
1578 * false is returned.
1580 * @param string|array $table Table name
1581 * @param string|array $vars Field names
1582 * @param array $conds Conditions
1583 * @param string $fname Caller function name
1584 * @param string|array $options Query options
1585 * @param $join_conds array|string Join conditions
1587 * @return object|bool
1589 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1590 $options = array(), $join_conds = array() )
1592 $options = (array)$options;
1593 $options['LIMIT'] = 1;
1594 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1596 if ( $res === false ) {
1600 if ( !$this->numRows( $res ) ) {
1604 $obj = $this->fetchObject( $res );
1610 * Estimate rows in dataset.
1612 * MySQL allows you to estimate the number of rows that would be returned
1613 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1614 * index cardinality statistics, and is notoriously inaccurate, especially
1615 * when large numbers of rows have recently been added or deleted.
1617 * For DBMSs that don't support fast result size estimation, this function
1618 * will actually perform the SELECT COUNT(*).
1620 * Takes the same arguments as DatabaseBase::select().
1622 * @param string $table table name
1623 * @param array|string $vars : unused
1624 * @param array|string $conds : filters on the table
1625 * @param string $fname function name for profiling
1626 * @param array $options options for select
1627 * @return Integer: row count
1629 public function estimateRowCount( $table, $vars = '*', $conds = '',
1630 $fname = __METHOD__
, $options = array() )
1633 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1636 $row = $this->fetchRow( $res );
1637 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1644 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1645 * It's only slightly flawed. Don't use for anything important.
1647 * @param string $sql A SQL Query
1651 static function generalizeSQL( $sql ) {
1652 # This does the same as the regexp below would do, but in such a way
1653 # as to avoid crashing php on some large strings.
1654 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1656 $sql = str_replace( "\\\\", '', $sql );
1657 $sql = str_replace( "\\'", '', $sql );
1658 $sql = str_replace( "\\\"", '', $sql );
1659 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1660 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1662 # All newlines, tabs, etc replaced by single space
1663 $sql = preg_replace( '/\s+/', ' ', $sql );
1666 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1667 $sql = preg_replace( '/-?\d+/s', 'N', $sql );
1673 * Determines whether a field exists in a table
1675 * @param string $table table name
1676 * @param string $field filed to check on that table
1677 * @param string $fname calling function name (optional)
1678 * @return Boolean: whether $table has filed $field
1680 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1681 $info = $this->fieldInfo( $table, $field );
1687 * Determines whether an index exists
1688 * Usually throws a DBQueryError on failure
1689 * If errors are explicitly ignored, returns NULL on failure
1693 * @param $fname string
1697 public function indexExists( $table, $index, $fname = __METHOD__
) {
1698 if ( !$this->tableExists( $table ) ) {
1702 $info = $this->indexInfo( $table, $index, $fname );
1703 if ( is_null( $info ) ) {
1706 return $info !== false;
1711 * Query whether a given table exists
1713 * @param $table string
1714 * @param $fname string
1718 public function tableExists( $table, $fname = __METHOD__
) {
1719 $table = $this->tableName( $table );
1720 $old = $this->ignoreErrors( true );
1721 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1722 $this->ignoreErrors( $old );
1728 * mysql_field_type() wrapper
1733 public function fieldType( $res, $index ) {
1734 if ( $res instanceof ResultWrapper
) {
1735 $res = $res->result
;
1738 return mysql_field_type( $res, $index );
1742 * Determines if a given index is unique
1744 * @param $table string
1745 * @param $index string
1749 public function indexUnique( $table, $index ) {
1750 $indexInfo = $this->indexInfo( $table, $index );
1752 if ( !$indexInfo ) {
1756 return !$indexInfo[0]->Non_unique
;
1760 * Helper for DatabaseBase::insert().
1762 * @param $options array
1765 protected function makeInsertOptions( $options ) {
1766 return implode( ' ', $options );
1770 * INSERT wrapper, inserts an array into a table.
1774 * - A single associative array. The array keys are the field names, and
1775 * the values are the values to insert. The values are treated as data
1776 * and will be quoted appropriately. If NULL is inserted, this will be
1777 * converted to a database NULL.
1778 * - An array with numeric keys, holding a list of associative arrays.
1779 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1780 * each subarray must be identical to each other, and in the same order.
1782 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1785 * $options is an array of options, with boolean options encoded as values
1786 * with numeric keys, in the same style as $options in
1787 * DatabaseBase::select(). Supported options are:
1789 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1790 * any rows which cause duplicate key errors are not inserted. It's
1791 * possible to determine how many rows were successfully inserted using
1792 * DatabaseBase::affectedRows().
1794 * @param $table String Table name. This will be passed through
1795 * DatabaseBase::tableName().
1796 * @param $a Array of rows to insert
1797 * @param $fname String Calling function name (use __METHOD__) for logs/profiling
1798 * @param array $options of options
1802 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
1803 # No rows to insert, easy just return now
1804 if ( !count( $a ) ) {
1808 $table = $this->tableName( $table );
1810 if ( !is_array( $options ) ) {
1811 $options = array( $options );
1815 if ( isset( $options['fileHandle'] ) ) {
1816 $fh = $options['fileHandle'];
1818 $options = $this->makeInsertOptions( $options );
1820 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1822 $keys = array_keys( $a[0] );
1825 $keys = array_keys( $a );
1828 $sql = 'INSERT ' . $options .
1829 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1833 foreach ( $a as $row ) {
1839 $sql .= '(' . $this->makeList( $row ) . ')';
1842 $sql .= '(' . $this->makeList( $a ) . ')';
1845 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1847 } elseif ( $fh !== null ) {
1851 return (bool)$this->query( $sql, $fname );
1855 * Make UPDATE options for the DatabaseBase::update function
1857 * @param array $options The options passed to DatabaseBase::update
1860 protected function makeUpdateOptions( $options ) {
1861 if ( !is_array( $options ) ) {
1862 $options = array( $options );
1867 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1868 $opts[] = $this->lowPriorityOption();
1871 if ( in_array( 'IGNORE', $options ) ) {
1875 return implode( ' ', $opts );
1879 * UPDATE wrapper. Takes a condition array and a SET array.
1881 * @param $table String name of the table to UPDATE. This will be passed through
1882 * DatabaseBase::tableName().
1884 * @param array $values An array of values to SET. For each array element,
1885 * the key gives the field name, and the value gives the data
1886 * to set that field to. The data will be quoted by
1887 * DatabaseBase::addQuotes().
1889 * @param $conds Array: An array of conditions (WHERE). See
1890 * DatabaseBase::select() for the details of the format of
1891 * condition arrays. Use '*' to update all rows.
1893 * @param $fname String: The function name of the caller (from __METHOD__),
1894 * for logging and profiling.
1896 * @param array $options An array of UPDATE options, can be:
1897 * - IGNORE: Ignore unique key conflicts
1898 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1901 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
1902 $table = $this->tableName( $table );
1903 $opts = $this->makeUpdateOptions( $options );
1904 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1906 if ( $conds !== array() && $conds !== '*' ) {
1907 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1910 return $this->query( $sql, $fname );
1914 * Makes an encoded list of strings from an array
1915 * @param array $a containing the data
1916 * @param int $mode Constant
1917 * - LIST_COMMA: comma separated, no field names
1918 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
1919 * the documentation for $conds in DatabaseBase::select().
1920 * - LIST_OR: ORed WHERE clause (without the WHERE)
1921 * - LIST_SET: comma separated with field names, like a SET clause
1922 * - LIST_NAMES: comma separated field names
1924 * @throws MWException|DBUnexpectedError
1927 public function makeList( $a, $mode = LIST_COMMA
) {
1928 if ( !is_array( $a ) ) {
1929 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1935 foreach ( $a as $field => $value ) {
1937 if ( $mode == LIST_AND
) {
1939 } elseif ( $mode == LIST_OR
) {
1948 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1949 $list .= "($value)";
1950 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1952 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1953 if ( count( $value ) == 0 ) {
1954 throw new MWException( __METHOD__
. ": empty input for field $field" );
1955 } elseif ( count( $value ) == 1 ) {
1956 // Special-case single values, as IN isn't terribly efficient
1957 // Don't necessarily assume the single key is 0; we don't
1958 // enforce linear numeric ordering on other arrays here.
1959 $value = array_values( $value );
1960 $list .= $field . " = " . $this->addQuotes( $value[0] );
1962 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1964 } elseif ( $value === null ) {
1965 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1966 $list .= "$field IS ";
1967 } elseif ( $mode == LIST_SET
) {
1968 $list .= "$field = ";
1972 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1973 $list .= "$field = ";
1975 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1983 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1984 * The keys on each level may be either integers or strings.
1986 * @param array $data organized as 2-d
1987 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
1988 * @param string $baseKey field name to match the base-level keys to (eg 'pl_namespace')
1989 * @param string $subKey field name to match the sub-level keys to (eg 'pl_title')
1990 * @return Mixed: string SQL fragment, or false if no items in array.
1992 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1995 foreach ( $data as $base => $sub ) {
1996 if ( count( $sub ) ) {
1997 $conds[] = $this->makeList(
1998 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2004 return $this->makeList( $conds, LIST_OR
);
2006 // Nothing to search for...
2012 * Return aggregated value alias
2015 * @param $valuename string
2019 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2027 public function bitNot( $field ) {
2033 * @param $fieldRight
2036 public function bitAnd( $fieldLeft, $fieldRight ) {
2037 return "($fieldLeft & $fieldRight)";
2042 * @param $fieldRight
2045 public function bitOr( $fieldLeft, $fieldRight ) {
2046 return "($fieldLeft | $fieldRight)";
2050 * Build a concatenation list to feed into a SQL query
2051 * @param array $stringList list of raw SQL expressions; caller is responsible for any quoting
2054 public function buildConcat( $stringList ) {
2055 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2059 * Change the current database
2061 * @todo Explain what exactly will fail if this is not overridden.
2065 * @return bool Success or failure
2067 public function selectDB( $db ) {
2068 # Stub. Shouldn't cause serious problems if it's not overridden, but
2069 # if your database engine supports a concept similar to MySQL's
2070 # databases you may as well.
2071 $this->mDBname
= $db;
2076 * Get the current DB name
2078 public function getDBname() {
2079 return $this->mDBname
;
2083 * Get the server hostname or IP address
2085 public function getServer() {
2086 return $this->mServer
;
2090 * Format a table name ready for use in constructing an SQL query
2092 * This does two important things: it quotes the table names to clean them up,
2093 * and it adds a table prefix if only given a table name with no quotes.
2095 * All functions of this object which require a table name call this function
2096 * themselves. Pass the canonical name to such functions. This is only needed
2097 * when calling query() directly.
2099 * @param string $name database table name
2100 * @param string $format One of:
2101 * quoted - Automatically pass the table name through addIdentifierQuotes()
2102 * so that it can be used in a query.
2103 * raw - Do not add identifier quotes to the table name
2104 * @return String: full database name
2106 public function tableName( $name, $format = 'quoted' ) {
2107 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
2108 # Skip the entire process when we have a string quoted on both ends.
2109 # Note that we check the end so that we will still quote any use of
2110 # use of `database`.table. But won't break things if someone wants
2111 # to query a database table with a dot in the name.
2112 if ( $this->isQuotedIdentifier( $name ) ) {
2116 # Lets test for any bits of text that should never show up in a table
2117 # name. Basically anything like JOIN or ON which are actually part of
2118 # SQL queries, but may end up inside of the table value to combine
2119 # sql. Such as how the API is doing.
2120 # Note that we use a whitespace test rather than a \b test to avoid
2121 # any remote case where a word like on may be inside of a table name
2122 # surrounded by symbols which may be considered word breaks.
2123 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2127 # Split database and table into proper variables.
2128 # We reverse the explode so that database.table and table both output
2129 # the correct table.
2130 $dbDetails = explode( '.', $name, 2 );
2131 if ( count( $dbDetails ) == 2 ) {
2132 list( $database, $table ) = $dbDetails;
2133 # We don't want any prefix added in this case
2136 list( $table ) = $dbDetails;
2137 if ( $wgSharedDB !== null # We have a shared database
2138 && $this->mForeign
== false # We're not working on a foreign database
2139 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
2140 && in_array( $table, $wgSharedTables ) # A shared table is selected
2142 $database = $wgSharedDB;
2143 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
2146 $prefix = $this->mTablePrefix
; # Default prefix
2150 # Quote $table and apply the prefix if not quoted.
2151 $tableName = "{$prefix}{$table}";
2152 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) ) {
2153 $tableName = $this->addIdentifierQuotes( $tableName );
2156 # Quote $database and merge it with the table name if needed
2157 if ( $database !== null ) {
2158 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2159 $database = $this->addIdentifierQuotes( $database );
2161 $tableName = $database . '.' . $tableName;
2168 * Fetch a number of table names into an array
2169 * This is handy when you need to construct SQL for joins
2172 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2173 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2174 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2178 public function tableNames() {
2179 $inArray = func_get_args();
2182 foreach ( $inArray as $name ) {
2183 $retVal[$name] = $this->tableName( $name );
2190 * Fetch a number of table names into an zero-indexed numerical array
2191 * This is handy when you need to construct SQL for joins
2194 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2195 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2196 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2200 public function tableNamesN() {
2201 $inArray = func_get_args();
2204 foreach ( $inArray as $name ) {
2205 $retVal[] = $this->tableName( $name );
2212 * Get an aliased table name
2213 * e.g. tableName AS newTableName
2215 * @param string $name Table name, see tableName()
2216 * @param string|bool $alias Alias (optional)
2217 * @return string SQL name for aliased table. Will not alias a table to its own name
2219 public function tableNameWithAlias( $name, $alias = false ) {
2220 if ( !$alias ||
$alias == $name ) {
2221 return $this->tableName( $name );
2223 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2228 * Gets an array of aliased table names
2230 * @param $tables array( [alias] => table )
2231 * @return array of strings, see tableNameWithAlias()
2233 public function tableNamesWithAlias( $tables ) {
2235 foreach ( $tables as $alias => $table ) {
2236 if ( is_numeric( $alias ) ) {
2239 $retval[] = $this->tableNameWithAlias( $table, $alias );
2245 * Get an aliased field name
2246 * e.g. fieldName AS newFieldName
2248 * @param string $name Field name
2249 * @param string|bool $alias Alias (optional)
2250 * @return string SQL name for aliased field. Will not alias a field to its own name
2252 public function fieldNameWithAlias( $name, $alias = false ) {
2253 if ( !$alias ||
(string)$alias === (string)$name ) {
2256 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2261 * Gets an array of aliased field names
2263 * @param $fields array( [alias] => field )
2264 * @return array of strings, see fieldNameWithAlias()
2266 public function fieldNamesWithAlias( $fields ) {
2268 foreach ( $fields as $alias => $field ) {
2269 if ( is_numeric( $alias ) ) {
2272 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2278 * Get the aliased table name clause for a FROM clause
2279 * which might have a JOIN and/or USE INDEX clause
2281 * @param array $tables ( [alias] => table )
2282 * @param $use_index array Same as for select()
2283 * @param $join_conds array Same as for select()
2286 protected function tableNamesWithUseIndexOrJOIN(
2287 $tables, $use_index = array(), $join_conds = array()
2291 $use_index = (array)$use_index;
2292 $join_conds = (array)$join_conds;
2294 foreach ( $tables as $alias => $table ) {
2295 if ( !is_string( $alias ) ) {
2296 // No alias? Set it equal to the table name
2299 // Is there a JOIN clause for this table?
2300 if ( isset( $join_conds[$alias] ) ) {
2301 list( $joinType, $conds ) = $join_conds[$alias];
2302 $tableClause = $joinType;
2303 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2304 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2305 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2307 $tableClause .= ' ' . $use;
2310 $on = $this->makeList( (array)$conds, LIST_AND
);
2312 $tableClause .= ' ON (' . $on . ')';
2315 $retJOIN[] = $tableClause;
2316 // Is there an INDEX clause for this table?
2317 } elseif ( isset( $use_index[$alias] ) ) {
2318 $tableClause = $this->tableNameWithAlias( $table, $alias );
2319 $tableClause .= ' ' . $this->useIndexClause(
2320 implode( ',', (array)$use_index[$alias] ) );
2322 $ret[] = $tableClause;
2324 $tableClause = $this->tableNameWithAlias( $table, $alias );
2326 $ret[] = $tableClause;
2330 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2331 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2332 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2334 // Compile our final table clause
2335 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2339 * Get the name of an index in a given table
2345 protected function indexName( $index ) {
2346 // Backwards-compatibility hack
2348 'ar_usertext_timestamp' => 'usertext_timestamp',
2349 'un_user_id' => 'user_id',
2350 'un_user_ip' => 'user_ip',
2353 if ( isset( $renamed[$index] ) ) {
2354 return $renamed[$index];
2361 * Adds quotes and backslashes.
2367 public function addQuotes( $s ) {
2368 if ( $s === null ) {
2371 # This will also quote numeric values. This should be harmless,
2372 # and protects against weird problems that occur when they really
2373 # _are_ strings such as article titles and string->number->string
2374 # conversion is not 1:1.
2375 return "'" . $this->strencode( $s ) . "'";
2380 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2381 * MySQL uses `backticks` while basically everything else uses double quotes.
2382 * Since MySQL is the odd one out here the double quotes are our generic
2383 * and we implement backticks in DatabaseMysql.
2389 public function addIdentifierQuotes( $s ) {
2390 return '"' . str_replace( '"', '""', $s ) . '"';
2394 * Returns if the given identifier looks quoted or not according to
2395 * the database convention for quoting identifiers .
2397 * @param $name string
2401 public function isQuotedIdentifier( $name ) {
2402 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2409 protected function escapeLikeInternal( $s ) {
2410 $s = str_replace( '\\', '\\\\', $s );
2411 $s = $this->strencode( $s );
2412 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
2418 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
2419 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
2420 * Alternatively, the function could be provided with an array of aforementioned parameters.
2422 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
2423 * for subpages of 'My page title'.
2424 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
2427 * @return String: fully built LIKE statement
2429 public function buildLike() {
2430 $params = func_get_args();
2432 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2433 $params = $params[0];
2438 foreach ( $params as $value ) {
2439 if ( $value instanceof LikeMatch
) {
2440 $s .= $value->toString();
2442 $s .= $this->escapeLikeInternal( $value );
2446 return " LIKE '" . $s . "' ";
2450 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2454 public function anyChar() {
2455 return new LikeMatch( '_' );
2459 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2463 public function anyString() {
2464 return new LikeMatch( '%' );
2468 * Returns an appropriately quoted sequence value for inserting a new row.
2469 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2470 * subclass will return an integer, and save the value for insertId()
2472 * Any implementation of this function should *not* involve reusing
2473 * sequence numbers created for rolled-back transactions.
2474 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2475 * @param $seqName string
2478 public function nextSequenceValue( $seqName ) {
2483 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2484 * is only needed because a) MySQL must be as efficient as possible due to
2485 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2486 * which index to pick. Anyway, other databases might have different
2487 * indexes on a given table. So don't bother overriding this unless you're
2492 public function useIndexClause( $index ) {
2497 * REPLACE query wrapper.
2499 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2500 * except that when there is a duplicate key error, the old row is deleted
2501 * and the new row is inserted in its place.
2503 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2504 * perform the delete, we need to know what the unique indexes are so that
2505 * we know how to find the conflicting rows.
2507 * It may be more efficient to leave off unique indexes which are unlikely
2508 * to collide. However if you do this, you run the risk of encountering
2509 * errors which wouldn't have occurred in MySQL.
2511 * @param string $table The table to replace the row(s) in.
2512 * @param array $rows Can be either a single row to insert, or multiple rows,
2513 * in the same format as for DatabaseBase::insert()
2514 * @param array $uniqueIndexes is an array of indexes. Each element may be either
2515 * a field name or an array of field names
2516 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2518 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2519 $quotedTable = $this->tableName( $table );
2521 if ( count( $rows ) == 0 ) {
2526 if ( !is_array( reset( $rows ) ) ) {
2527 $rows = array( $rows );
2530 foreach ( $rows as $row ) {
2531 # Delete rows which collide
2532 if ( $uniqueIndexes ) {
2533 $sql = "DELETE FROM $quotedTable WHERE ";
2535 foreach ( $uniqueIndexes as $index ) {
2542 if ( is_array( $index ) ) {
2544 foreach ( $index as $col ) {
2550 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2553 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2557 $this->query( $sql, $fname );
2560 # Now insert the row
2561 $this->insert( $table, $row, $fname );
2566 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2569 * @param string $table Table name
2570 * @param array $rows Rows to insert
2571 * @param string $fname Caller function name
2573 * @return ResultWrapper
2575 protected function nativeReplace( $table, $rows, $fname ) {
2576 $table = $this->tableName( $table );
2579 if ( !is_array( reset( $rows ) ) ) {
2580 $rows = array( $rows );
2583 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2586 foreach ( $rows as $row ) {
2593 $sql .= '(' . $this->makeList( $row ) . ')';
2596 return $this->query( $sql, $fname );
2600 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2602 * This updates any conflicting rows (according to the unique indexes) using
2603 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2605 * $rows may be either:
2606 * - A single associative array. The array keys are the field names, and
2607 * the values are the values to insert. The values are treated as data
2608 * and will be quoted appropriately. If NULL is inserted, this will be
2609 * converted to a database NULL.
2610 * - An array with numeric keys, holding a list of associative arrays.
2611 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2612 * each subarray must be identical to each other, and in the same order.
2614 * It may be more efficient to leave off unique indexes which are unlikely
2615 * to collide. However if you do this, you run the risk of encountering
2616 * errors which wouldn't have occurred in MySQL.
2618 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2621 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2622 * @param array $rows A single row or list of rows to insert
2623 * @param array $uniqueIndexes List of single field names or field name tuples
2624 * @param array $set An array of values to SET. For each array element,
2625 * the key gives the field name, and the value gives the data
2626 * to set that field to. The data will be quoted by
2627 * DatabaseBase::addQuotes().
2628 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2629 * @param array $options of options
2634 public function upsert(
2635 $table, array $rows, array $uniqueIndexes, array $set, $fname = __METHOD__
2637 if ( !count( $rows ) ) {
2638 return true; // nothing to do
2640 $rows = is_array( reset( $rows ) ) ?
$rows : array( $rows );
2642 if ( count( $uniqueIndexes ) ) {
2643 $clauses = array(); // list WHERE clauses that each identify a single row
2644 foreach ( $rows as $row ) {
2645 foreach ( $uniqueIndexes as $index ) {
2646 $index = is_array( $index ) ?
$index : array( $index ); // columns
2647 $rowKey = array(); // unique key to this row
2648 foreach ( $index as $column ) {
2649 $rowKey[$column] = $row[$column];
2651 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2654 $where = array( $this->makeList( $clauses, LIST_OR
) );
2659 $useTrx = !$this->mTrxLevel
;
2661 $this->begin( $fname );
2664 # Update any existing conflicting row(s)
2665 if ( $where !== false ) {
2666 $ok = $this->update( $table, $set, $where, $fname );
2670 # Now insert any non-conflicting row(s)
2671 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2672 } catch ( Exception
$e ) {
2674 $this->rollback( $fname );
2679 $this->commit( $fname );
2686 * DELETE where the condition is a join.
2688 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2689 * we use sub-selects
2691 * For safety, an empty $conds will not delete everything. If you want to
2692 * delete all rows where the join condition matches, set $conds='*'.
2694 * DO NOT put the join condition in $conds.
2696 * @param $delTable String: The table to delete from.
2697 * @param $joinTable String: The other table.
2698 * @param $delVar String: The variable to join on, in the first table.
2699 * @param $joinVar String: The variable to join on, in the second table.
2700 * @param $conds Array: Condition array of field names mapped to variables,
2701 * ANDed together in the WHERE clause
2702 * @param $fname String: Calling function name (use __METHOD__) for
2704 * @throws DBUnexpectedError
2706 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2707 $fname = __METHOD__
)
2710 throw new DBUnexpectedError( $this,
2711 'DatabaseBase::deleteJoin() called with empty $conds' );
2714 $delTable = $this->tableName( $delTable );
2715 $joinTable = $this->tableName( $joinTable );
2716 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2717 if ( $conds != '*' ) {
2718 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2722 $this->query( $sql, $fname );
2726 * Returns the size of a text field, or -1 for "unlimited"
2728 * @param $table string
2729 * @param $field string
2733 public function textFieldSize( $table, $field ) {
2734 $table = $this->tableName( $table );
2735 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2736 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2737 $row = $this->fetchObject( $res );
2741 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2751 * A string to insert into queries to show that they're low-priority, like
2752 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2753 * string and nothing bad should happen.
2755 * @return string Returns the text of the low priority option if it is
2756 * supported, or a blank string otherwise
2758 public function lowPriorityOption() {
2763 * DELETE query wrapper.
2765 * @param array $table Table name
2766 * @param string|array $conds of conditions. See $conds in DatabaseBase::select() for
2767 * the format. Use $conds == "*" to delete all rows
2768 * @param string $fname name of the calling function
2770 * @throws DBUnexpectedError
2771 * @return bool|ResultWrapper
2773 public function delete( $table, $conds, $fname = __METHOD__
) {
2775 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2778 $table = $this->tableName( $table );
2779 $sql = "DELETE FROM $table";
2781 if ( $conds != '*' ) {
2782 if ( is_array( $conds ) ) {
2783 $conds = $this->makeList( $conds, LIST_AND
);
2785 $sql .= ' WHERE ' . $conds;
2788 return $this->query( $sql, $fname );
2792 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2793 * into another table.
2795 * @param string $destTable The table name to insert into
2796 * @param string|array $srcTable May be either a table name, or an array of table names
2797 * to include in a join.
2799 * @param array $varMap must be an associative array of the form
2800 * array( 'dest1' => 'source1', ...). Source items may be literals
2801 * rather than field names, but strings should be quoted with
2802 * DatabaseBase::addQuotes()
2804 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
2805 * the details of the format of condition arrays. May be "*" to copy the
2808 * @param string $fname The function name of the caller, from __METHOD__
2810 * @param array $insertOptions Options for the INSERT part of the query, see
2811 * DatabaseBase::insert() for details.
2812 * @param array $selectOptions Options for the SELECT part of the query, see
2813 * DatabaseBase::select() for details.
2815 * @return ResultWrapper
2817 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2818 $fname = __METHOD__
,
2819 $insertOptions = array(), $selectOptions = array() )
2821 $destTable = $this->tableName( $destTable );
2823 if ( is_array( $insertOptions ) ) {
2824 $insertOptions = implode( ' ', $insertOptions );
2827 if ( !is_array( $selectOptions ) ) {
2828 $selectOptions = array( $selectOptions );
2831 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2833 if ( is_array( $srcTable ) ) {
2834 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2836 $srcTable = $this->tableName( $srcTable );
2839 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2840 " SELECT $startOpts " . implode( ',', $varMap ) .
2841 " FROM $srcTable $useIndex ";
2843 if ( $conds != '*' ) {
2844 if ( is_array( $conds ) ) {
2845 $conds = $this->makeList( $conds, LIST_AND
);
2847 $sql .= " WHERE $conds";
2850 $sql .= " $tailOpts";
2852 return $this->query( $sql, $fname );
2856 * Construct a LIMIT query with optional offset. This is used for query
2857 * pages. The SQL should be adjusted so that only the first $limit rows
2858 * are returned. If $offset is provided as well, then the first $offset
2859 * rows should be discarded, and the next $limit rows should be returned.
2860 * If the result of the query is not ordered, then the rows to be returned
2861 * are theoretically arbitrary.
2863 * $sql is expected to be a SELECT, if that makes a difference.
2865 * The version provided by default works in MySQL and SQLite. It will very
2866 * likely need to be overridden for most other DBMSes.
2868 * @param string $sql SQL query we will append the limit too
2869 * @param $limit Integer the SQL limit
2870 * @param $offset Integer|bool the SQL offset (default false)
2872 * @throws DBUnexpectedError
2875 public function limitResult( $sql, $limit, $offset = false ) {
2876 if ( !is_numeric( $limit ) ) {
2877 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2879 return "$sql LIMIT "
2880 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2885 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2886 * within the UNION construct.
2889 public function unionSupportsOrderAndLimit() {
2890 return true; // True for almost every DB supported
2894 * Construct a UNION query
2895 * This is used for providing overload point for other DB abstractions
2896 * not compatible with the MySQL syntax.
2897 * @param array $sqls SQL statements to combine
2898 * @param $all Boolean: use UNION ALL
2899 * @return String: SQL fragment
2901 public function unionQueries( $sqls, $all ) {
2902 $glue = $all ?
') UNION ALL (' : ') UNION (';
2903 return '(' . implode( $glue, $sqls ) . ')';
2907 * Returns an SQL expression for a simple conditional. This doesn't need
2908 * to be overridden unless CASE isn't supported in your DBMS.
2910 * @param string|array $cond SQL expression which will result in a boolean value
2911 * @param string $trueVal SQL expression to return if true
2912 * @param string $falseVal SQL expression to return if false
2913 * @return String: SQL fragment
2915 public function conditional( $cond, $trueVal, $falseVal ) {
2916 if ( is_array( $cond ) ) {
2917 $cond = $this->makeList( $cond, LIST_AND
);
2919 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2923 * Returns a comand for str_replace function in SQL query.
2924 * Uses REPLACE() in MySQL
2926 * @param string $orig column to modify
2927 * @param string $old column to seek
2928 * @param string $new column to replace with
2932 public function strreplace( $orig, $old, $new ) {
2933 return "REPLACE({$orig}, {$old}, {$new})";
2937 * Determines how long the server has been up
2942 public function getServerUptime() {
2947 * Determines if the last failure was due to a deadlock
2952 public function wasDeadlock() {
2957 * Determines if the last failure was due to a lock timeout
2962 public function wasLockTimeout() {
2967 * Determines if the last query error was something that should be dealt
2968 * with by pinging the connection and reissuing the query.
2973 public function wasErrorReissuable() {
2978 * Determines if the last failure was due to the database being read-only.
2983 public function wasReadOnlyError() {
2988 * Perform a deadlock-prone transaction.
2990 * This function invokes a callback function to perform a set of write
2991 * queries. If a deadlock occurs during the processing, the transaction
2992 * will be rolled back and the callback function will be called again.
2995 * $dbw->deadlockLoop( callback, ... );
2997 * Extra arguments are passed through to the specified callback function.
2999 * Returns whatever the callback function returned on its successful,
3000 * iteration, or false on error, for example if the retry limit was
3005 public function deadlockLoop() {
3006 $this->begin( __METHOD__
);
3007 $args = func_get_args();
3008 $function = array_shift( $args );
3009 $oldIgnore = $this->ignoreErrors( true );
3010 $tries = self
::DEADLOCK_TRIES
;
3012 if ( is_array( $function ) ) {
3013 $fname = $function[0];
3019 $retVal = call_user_func_array( $function, $args );
3020 $error = $this->lastError();
3021 $errno = $this->lastErrno();
3022 $sql = $this->lastQuery();
3025 if ( $this->wasDeadlock() ) {
3027 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3029 $this->reportQueryError( $error, $errno, $sql, $fname );
3032 } while ( $this->wasDeadlock() && --$tries > 0 );
3034 $this->ignoreErrors( $oldIgnore );
3036 if ( $tries <= 0 ) {
3037 $this->rollback( __METHOD__
);
3038 $this->reportQueryError( $error, $errno, $sql, $fname );
3041 $this->commit( __METHOD__
);
3047 * Wait for the slave to catch up to a given master position.
3049 * @param $pos DBMasterPos object
3050 * @param $timeout Integer: the maximum number of seconds to wait for
3053 * @return integer: zero if the slave was past that position already,
3054 * greater than zero if we waited for some period of time, less than
3055 * zero if we timed out.
3057 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3058 wfProfileIn( __METHOD__
);
3060 if ( !is_null( $this->mFakeSlaveLag
) ) {
3061 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
3063 if ( $wait > $timeout * 1e6
) {
3064 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
3065 wfProfileOut( __METHOD__
);
3067 } elseif ( $wait > 0 ) {
3068 wfDebug( "Fake slave waiting $wait us\n" );
3070 wfProfileOut( __METHOD__
);
3073 wfDebug( "Fake slave up to date ($wait us)\n" );
3074 wfProfileOut( __METHOD__
);
3079 wfProfileOut( __METHOD__
);
3081 # Real waits are implemented in the subclass.
3086 * Get the replication position of this slave
3088 * @return DBMasterPos, or false if this is not a slave.
3090 public function getSlavePos() {
3091 if ( !is_null( $this->mFakeSlaveLag
) ) {
3092 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
3093 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
3102 * Get the position of this master
3104 * @return DBMasterPos, or false if this is not a master
3106 public function getMasterPos() {
3107 if ( $this->mFakeMaster
) {
3108 return new MySQLMasterPos( 'fake', microtime( true ) );
3115 * Run an anonymous function as soon as there is no transaction pending.
3116 * If there is a transaction and it is rolled back, then the callback is cancelled.
3117 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3118 * Callbacks must commit any transactions that they begin.
3120 * This is useful for updates to different systems or when separate transactions are needed.
3121 * For example, one might want to enqueue jobs into a system outside the database, but only
3122 * after the database is updated so that the jobs will see the data when they actually run.
3123 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3125 * @param callable $callback
3128 final public function onTransactionIdle( $callback ) {
3129 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
3130 if ( !$this->mTrxLevel
) {
3131 $this->runOnTransactionIdleCallbacks();
3136 * Run an anonymous function before the current transaction commits or now if there is none.
3137 * If there is a transaction and it is rolled back, then the callback is cancelled.
3138 * Callbacks must not start nor commit any transactions.
3140 * This is useful for updates that easily cause deadlocks if locks are held too long
3141 * but where atomicity is strongly desired for these updates and some related updates.
3143 * @param callable $callback
3146 final public function onTransactionPreCommitOrIdle( $callback ) {
3147 if ( $this->mTrxLevel
) {
3148 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
3150 $this->onTransactionIdle( $callback ); // this will trigger immediately
3155 * Actually any "on transaction idle" callbacks.
3159 protected function runOnTransactionIdleCallbacks() {
3160 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
3162 $e = null; // last exception
3163 do { // callbacks may add callbacks :)
3164 $callbacks = $this->mTrxIdleCallbacks
;
3165 $this->mTrxIdleCallbacks
= array(); // recursion guard
3166 foreach ( $callbacks as $callback ) {
3168 list( $phpCallback ) = $callback;
3169 $this->clearFlag( DBO_TRX
); // make each query its own transaction
3170 call_user_func( $phpCallback );
3171 $this->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
3172 } catch ( Exception
$e ) {}
3174 } while ( count( $this->mTrxIdleCallbacks
) );
3176 if ( $e instanceof Exception
) {
3177 throw $e; // re-throw any last exception
3182 * Actually any "on transaction pre-commit" callbacks.
3186 protected function runOnTransactionPreCommitCallbacks() {
3187 $e = null; // last exception
3188 do { // callbacks may add callbacks :)
3189 $callbacks = $this->mTrxPreCommitCallbacks
;
3190 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
3191 foreach ( $callbacks as $callback ) {
3193 list( $phpCallback ) = $callback;
3194 call_user_func( $phpCallback );
3195 } catch ( Exception
$e ) {}
3197 } while ( count( $this->mTrxPreCommitCallbacks
) );
3199 if ( $e instanceof Exception
) {
3200 throw $e; // re-throw any last exception
3205 * Begin an atomic section of statements
3207 * If a transaction has been started already, just keep track of the given
3208 * section name to make sure the transaction is not committed pre-maturely.
3209 * This function can be used in layers (with sub-sections), so use a stack
3210 * to keep track of the different atomic sections. If there is no transaction,
3211 * start one implicitly.
3213 * The goal of this function is to create an atomic section of SQL queries
3214 * without having to start a new transaction if it already exists.
3216 * Atomic sections are more strict than transactions. With transactions,
3217 * attempting to begin a new transaction when one is already running results
3218 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3219 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3220 * and any database transactions cannot be began or committed until all atomic
3221 * levels are closed. There is no such thing as implicitly opening or closing
3222 * an atomic section.
3225 * @param string $fname
3227 final public function startAtomic( $fname = __METHOD__
) {
3228 if ( !$this->mTrxLevel
) {
3229 $this->begin( $fname );
3230 $this->mTrxAutomatic
= true;
3231 $this->mTrxAutomaticAtomic
= true;
3234 $this->mTrxAtomicLevels
->push( $fname );
3238 * Begin a transaction. If a transaction is already in progress, that transaction will be committed before the
3239 * new transaction is started.
3241 * Note that when the DBO_TRX flag is set (which is usually the case for web requests, but not for maintenance scripts),
3242 * any previous database query will have started a transaction automatically.
3244 * Nesting of transactions is not supported. Attempts to nest transactions will cause a warning, unless the current
3245 * transaction was started automatically because of the DBO_TRX flag.
3247 * @param $fname string
3249 final public function begin( $fname = __METHOD__
) {
3250 global $wgDebugDBTransactions;
3252 if ( $this->mTrxLevel
) { // implicit commit
3253 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3254 // If the current transaction was an automatic atomic one, then we definitely have
3255 // a problem. Same if there is any unclosed atomic level.
3256 throw new DBUnexpectedError( $this,
3257 "Attempted to start explicit transaction when atomic levels are still open."
3259 } elseif ( !$this->mTrxAutomatic
) {
3260 // We want to warn about inadvertently nested begin/commit pairs, but not about
3261 // auto-committing implicit transactions that were started by query() via DBO_TRX
3262 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3263 " performing implicit commit!";
3265 wfLogDBError( $msg );
3267 // if the transaction was automatic and has done write operations,
3268 // log it if $wgDebugDBTransactions is enabled.
3269 if ( $this->mTrxDoneWrites
&& $wgDebugDBTransactions ) {
3270 wfDebug( "$fname: Automatic transaction with writes in progress" .
3271 " (from {$this->mTrxFname}), performing implicit commit!\n"
3276 $this->runOnTransactionPreCommitCallbacks();
3277 $this->doCommit( $fname );
3278 if ( $this->mTrxDoneWrites
) {
3279 Profiler
::instance()->transactionWritingOut( $this->mServer
, $this->mDBname
);
3281 $this->runOnTransactionIdleCallbacks();
3284 $this->doBegin( $fname );
3285 $this->mTrxFname
= $fname;
3286 $this->mTrxDoneWrites
= false;
3287 $this->mTrxAutomatic
= false;
3288 $this->mTrxAutomaticAtomic
= false;
3289 $this->mTrxAtomicLevels
= new SplStack
;
3293 * Issues the BEGIN command to the database server.
3295 * @see DatabaseBase::begin()
3296 * @param type $fname
3298 protected function doBegin( $fname ) {
3299 $this->query( 'BEGIN', $fname );
3300 $this->mTrxLevel
= 1;
3304 * Ends an atomic section of SQL statements
3306 * Ends the next section of atomic SQL statements and commits the transaction
3310 * @see DatabaseBase::startAtomic
3311 * @param string $fname
3313 final public function endAtomic( $fname = __METHOD__
) {
3314 if ( $this->mTrxAtomicLevels
->isEmpty() ||
3315 $this->mTrxAtomicLevels
->pop() !== $fname
3317 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3320 if ( $this->mTrxAtomicLevels
->isEmpty() && $this->mTrxAutomaticAtomic
) {
3321 $this->commit( $fname, 'flush' );
3326 * Commits a transaction previously started using begin().
3327 * If no transaction is in progress, a warning is issued.
3329 * Nesting of transactions is not supported.
3331 * @param $fname string
3332 * @param string $flush Flush flag, set to 'flush' to disable warnings about explicitly committing implicit
3333 * transactions, or calling commit when no transaction is in progress.
3334 * This will silently break any ongoing explicit transaction. Only set the flush flag if you are sure
3335 * that it is safe to ignore these warnings in your context.
3337 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3338 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3339 // There are still atomic sections open. This cannot be ignored
3340 throw new DBUnexpectedError( $this, "Attempted to commit transaction while atomic sections are still open" );
3343 if ( $flush != 'flush' ) {
3344 if ( !$this->mTrxLevel
) {
3345 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3346 } elseif ( $this->mTrxAutomatic
) {
3347 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3350 if ( !$this->mTrxLevel
) {
3351 return; // nothing to do
3352 } elseif ( !$this->mTrxAutomatic
) {
3353 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3357 $this->runOnTransactionPreCommitCallbacks();
3358 $this->doCommit( $fname );
3359 if ( $this->mTrxDoneWrites
) {
3360 Profiler
::instance()->transactionWritingOut( $this->mServer
, $this->mDBname
);
3362 $this->mTrxDoneWrites
= false;
3363 $this->runOnTransactionIdleCallbacks();
3367 * Issues the COMMIT command to the database server.
3369 * @see DatabaseBase::commit()
3370 * @param type $fname
3372 protected function doCommit( $fname ) {
3373 if ( $this->mTrxLevel
) {
3374 $this->query( 'COMMIT', $fname );
3375 $this->mTrxLevel
= 0;
3380 * Rollback a transaction previously started using begin().
3381 * If no transaction is in progress, a warning is issued.
3383 * No-op on non-transactional databases.
3385 * @param $fname string
3387 final public function rollback( $fname = __METHOD__
) {
3388 if ( !$this->mTrxLevel
) {
3389 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3391 $this->doRollback( $fname );
3392 $this->mTrxIdleCallbacks
= array(); // cancel
3393 $this->mTrxPreCommitCallbacks
= array(); // cancel
3394 $this->mTrxAtomicLevels
= new SplStack
;
3395 if ( $this->mTrxDoneWrites
) {
3396 Profiler
::instance()->transactionWritingOut( $this->mServer
, $this->mDBname
);
3398 $this->mTrxDoneWrites
= false;
3402 * Issues the ROLLBACK command to the database server.
3404 * @see DatabaseBase::rollback()
3405 * @param type $fname
3407 protected function doRollback( $fname ) {
3408 if ( $this->mTrxLevel
) {
3409 $this->query( 'ROLLBACK', $fname, true );
3410 $this->mTrxLevel
= 0;
3415 * Creates a new table with structure copied from existing table
3416 * Note that unlike most database abstraction functions, this function does not
3417 * automatically append database prefix, because it works at a lower
3418 * abstraction level.
3419 * The table names passed to this function shall not be quoted (this
3420 * function calls addIdentifierQuotes when needed).
3422 * @param string $oldName name of table whose structure should be copied
3423 * @param string $newName name of table to be created
3424 * @param $temporary Boolean: whether the new table should be temporary
3425 * @param string $fname calling function name
3426 * @throws MWException
3427 * @return Boolean: true if operation was successful
3429 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3432 throw new MWException(
3433 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3437 * List all tables on the database
3439 * @param string $prefix Only show tables with this prefix, e.g. mw_
3440 * @param string $fname calling function name
3441 * @throws MWException
3443 function listTables( $prefix = null, $fname = __METHOD__
) {
3444 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3448 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3449 * to the format used for inserting into timestamp fields in this DBMS.
3451 * The result is unquoted, and needs to be passed through addQuotes()
3452 * before it can be included in raw SQL.
3454 * @param $ts string|int
3458 public function timestamp( $ts = 0 ) {
3459 return wfTimestamp( TS_MW
, $ts );
3463 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3464 * to the format used for inserting into timestamp fields in this DBMS. If
3465 * NULL is input, it is passed through, allowing NULL values to be inserted
3466 * into timestamp fields.
3468 * The result is unquoted, and needs to be passed through addQuotes()
3469 * before it can be included in raw SQL.
3471 * @param $ts string|int
3475 public function timestampOrNull( $ts = null ) {
3476 if ( is_null( $ts ) ) {
3479 return $this->timestamp( $ts );
3484 * Take the result from a query, and wrap it in a ResultWrapper if
3485 * necessary. Boolean values are passed through as is, to indicate success
3486 * of write queries or failure.
3488 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3489 * resource, and it was necessary to call this function to convert it to
3490 * a wrapper. Nowadays, raw database objects are never exposed to external
3491 * callers, so this is unnecessary in external code. For compatibility with
3492 * old code, ResultWrapper objects are passed through unaltered.
3494 * @param $result bool|ResultWrapper
3496 * @return bool|ResultWrapper
3498 public function resultObject( $result ) {
3499 if ( empty( $result ) ) {
3501 } elseif ( $result instanceof ResultWrapper
) {
3503 } elseif ( $result === true ) {
3504 // Successful write query
3507 return new ResultWrapper( $this, $result );
3512 * Ping the server and try to reconnect if it there is no connection
3514 * @return bool Success or failure
3516 public function ping() {
3517 # Stub. Not essential to override.
3522 * Get slave lag. Currently supported only by MySQL.
3524 * Note that this function will generate a fatal error on many
3525 * installations. Most callers should use LoadBalancer::safeGetLag()
3528 * @return int Database replication lag in seconds
3530 public function getLag() {
3531 return intval( $this->mFakeSlaveLag
);
3535 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3539 function maxListLen() {
3544 * Some DBMSs have a special format for inserting into blob fields, they
3545 * don't allow simple quoted strings to be inserted. To insert into such
3546 * a field, pass the data through this function before passing it to
3547 * DatabaseBase::insert().
3551 public function encodeBlob( $b ) {
3556 * Some DBMSs return a special placeholder object representing blob fields
3557 * in result objects. Pass the object through this function to return the
3562 public function decodeBlob( $b ) {
3567 * Override database's default behavior. $options include:
3568 * 'connTimeout' : Set the connection timeout value in seconds.
3569 * May be useful for very long batch queries such as
3570 * full-wiki dumps, where a single query reads out over
3573 * @param $options Array
3576 public function setSessionOptions( array $options ) {
3580 * Read and execute SQL commands from a file.
3582 * Returns true on success, error string or exception on failure (depending
3583 * on object's error ignore settings).
3585 * @param string $filename File name to open
3586 * @param bool|callable $lineCallback Optional function called before reading each line
3587 * @param bool|callable $resultCallback Optional function called for each MySQL result
3588 * @param bool|string $fname Calling function name or false if name should be
3589 * generated dynamically using $filename
3590 * @param bool|callable $inputCallback Callback: Optional function called for each complete line sent
3591 * @throws MWException
3592 * @throws Exception|MWException
3593 * @return bool|string
3595 public function sourceFile(
3596 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3598 wfSuppressWarnings();
3599 $fp = fopen( $filename, 'r' );
3600 wfRestoreWarnings();
3602 if ( false === $fp ) {
3603 throw new MWException( "Could not open \"{$filename}\".\n" );
3607 $fname = __METHOD__
. "( $filename )";
3611 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3613 catch ( MWException
$e ) {
3624 * Get the full path of a patch file. Originally based on archive()
3625 * from updaters.inc. Keep in mind this always returns a patch, as
3626 * it fails back to MySQL if no DB-specific patch can be found
3628 * @param string $patch The name of the patch, like patch-something.sql
3629 * @return String Full path to patch file
3631 public function patchPath( $patch ) {
3634 $dbType = $this->getType();
3635 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3636 return "$IP/maintenance/$dbType/archives/$patch";
3638 return "$IP/maintenance/archives/$patch";
3643 * Set variables to be used in sourceFile/sourceStream, in preference to the
3644 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3645 * all. If it's set to false, $GLOBALS will be used.
3647 * @param bool|array $vars mapping variable name to value.
3649 public function setSchemaVars( $vars ) {
3650 $this->mSchemaVars
= $vars;
3654 * Read and execute commands from an open file handle.
3656 * Returns true on success, error string or exception on failure (depending
3657 * on object's error ignore settings).
3659 * @param $fp Resource: File handle
3660 * @param $lineCallback Callback: Optional function called before reading each query
3661 * @param $resultCallback Callback: Optional function called for each MySQL result
3662 * @param string $fname Calling function name
3663 * @param $inputCallback Callback: Optional function called for each complete query sent
3664 * @return bool|string
3666 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3667 $fname = __METHOD__
, $inputCallback = false )
3671 while ( !feof( $fp ) ) {
3672 if ( $lineCallback ) {
3673 call_user_func( $lineCallback );
3676 $line = trim( fgets( $fp ) );
3678 if ( $line == '' ) {
3682 if ( '-' == $line[0] && '-' == $line[1] ) {
3690 $done = $this->streamStatementEnd( $cmd, $line );
3694 if ( $done ||
feof( $fp ) ) {
3695 $cmd = $this->replaceVars( $cmd );
3697 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3698 $res = $this->query( $cmd, $fname );
3700 if ( $resultCallback ) {
3701 call_user_func( $resultCallback, $res, $this );
3704 if ( false === $res ) {
3705 $err = $this->lastError();
3706 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3717 * Called by sourceStream() to check if we've reached a statement end
3719 * @param string $sql SQL assembled so far
3720 * @param string $newLine New line about to be added to $sql
3721 * @return Bool Whether $newLine contains end of the statement
3723 public function streamStatementEnd( &$sql, &$newLine ) {
3724 if ( $this->delimiter
) {
3726 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3727 if ( $newLine != $prev ) {
3735 * Database independent variable replacement. Replaces a set of variables
3736 * in an SQL statement with their contents as given by $this->getSchemaVars().
3738 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3740 * - '{$var}' should be used for text and is passed through the database's
3742 * - `{$var}` should be used for identifiers (eg: table and database names),
3743 * it is passed through the database's addIdentifierQuotes method which
3744 * can be overridden if the database uses something other than backticks.
3745 * - / *$var* / is just encoded, besides traditional table prefix and
3746 * table options its use should be avoided.
3748 * @param string $ins SQL statement to replace variables in
3749 * @return String The new SQL statement with variables replaced
3751 protected function replaceSchemaVars( $ins ) {
3752 $vars = $this->getSchemaVars();
3753 foreach ( $vars as $var => $value ) {
3755 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
3757 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
3759 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ), $ins );
3765 * Replace variables in sourced SQL
3767 * @param $ins string
3771 protected function replaceVars( $ins ) {
3772 $ins = $this->replaceSchemaVars( $ins );
3775 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3776 array( $this, 'tableNameCallback' ), $ins );
3779 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
3780 array( $this, 'indexNameCallback' ), $ins );
3786 * Get schema variables. If none have been set via setSchemaVars(), then
3787 * use some defaults from the current object.
3791 protected function getSchemaVars() {
3792 if ( $this->mSchemaVars
) {
3793 return $this->mSchemaVars
;
3795 return $this->getDefaultSchemaVars();
3800 * Get schema variables to use if none have been set via setSchemaVars().
3802 * Override this in derived classes to provide variables for tables.sql
3803 * and SQL patch files.
3807 protected function getDefaultSchemaVars() {
3812 * Table name callback
3814 * @param $matches array
3818 protected function tableNameCallback( $matches ) {
3819 return $this->tableName( $matches[1] );
3823 * Index name callback
3825 * @param $matches array
3829 protected function indexNameCallback( $matches ) {
3830 return $this->indexName( $matches[1] );
3834 * Check to see if a named lock is available. This is non-blocking.
3836 * @param string $lockName name of lock to poll
3837 * @param string $method name of method calling us
3841 public function lockIsFree( $lockName, $method ) {
3846 * Acquire a named lock
3848 * Abstracted from Filestore::lock() so child classes can implement for
3851 * @param string $lockName name of lock to aquire
3852 * @param string $method name of method calling us
3853 * @param $timeout Integer: timeout
3856 public function lock( $lockName, $method, $timeout = 5 ) {
3863 * @param string $lockName Name of lock to release
3864 * @param string $method Name of method calling us
3866 * @return int Returns 1 if the lock was released, 0 if the lock was not established
3867 * by this thread (in which case the lock is not released), and NULL if the named
3868 * lock did not exist
3870 public function unlock( $lockName, $method ) {
3875 * Lock specific tables
3877 * @param array $read of tables to lock for read access
3878 * @param array $write of tables to lock for write access
3879 * @param string $method name of caller
3880 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3884 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3889 * Unlock specific tables
3891 * @param string $method the caller
3895 public function unlockTables( $method ) {
3901 * @param $tableName string
3902 * @param $fName string
3903 * @return bool|ResultWrapper
3906 public function dropTable( $tableName, $fName = __METHOD__
) {
3907 if ( !$this->tableExists( $tableName, $fName ) ) {
3910 $sql = "DROP TABLE " . $this->tableName( $tableName );
3911 if ( $this->cascadingDeletes() ) {
3914 return $this->query( $sql, $fName );
3918 * Get search engine class. All subclasses of this need to implement this
3919 * if they wish to use searching.
3923 public function getSearchEngine() {
3924 return 'SearchEngineDummy';
3928 * Find out when 'infinity' is. Most DBMSes support this. This is a special
3929 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
3930 * because "i" sorts after all numbers.
3934 public function getInfinity() {
3939 * Encode an expiry time into the DBMS dependent format
3941 * @param string $expiry timestamp for expiry, or the 'infinity' string
3944 public function encodeExpiry( $expiry ) {
3945 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3946 ?
$this->getInfinity()
3947 : $this->timestamp( $expiry );
3951 * Decode an expiry time into a DBMS independent format
3953 * @param string $expiry DB timestamp field value for expiry
3954 * @param $format integer: TS_* constant, defaults to TS_MW
3957 public function decodeExpiry( $expiry, $format = TS_MW
) {
3958 return ( $expiry == '' ||
$expiry == $this->getInfinity() )
3960 : wfTimestamp( $format, $expiry );
3964 * Allow or deny "big selects" for this session only. This is done by setting
3965 * the sql_big_selects session variable.
3967 * This is a MySQL-specific feature.
3969 * @param $value Mixed: true for allow, false for deny, or "default" to
3970 * restore the initial value
3972 public function setBigSelects( $value = true ) {
3979 public function __toString() {
3980 return (string)$this->mConn
;
3984 * Run a few simple sanity checks
3986 public function __destruct() {
3987 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3988 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3990 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
3992 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
3993 $callers[] = $callbackInfo[1];
3996 $callers = implode( ', ', $callers );
3997 trigger_error( "DB transaction callbacks still pending (from $callers)." );