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 $mErrorCount = 0;
247 protected $mLBInfo = array();
248 protected $mFakeSlaveLag = null, $mFakeMaster = false;
249 protected $mDefaultBigSelects = null;
250 protected $mSchemaVars = false;
252 protected $preparedArgs;
254 protected $htmlErrors;
256 protected $delimiter = ';';
259 * Either 1 if a transaction is active or 0 otherwise.
260 * The other Trx fields may not be meaningfull if this is 0.
264 protected $mTrxLevel = 0;
267 * Remembers the function name given for starting the most recent transaction via begin().
268 * Used to provide additional context for error reporting.
271 * @see DatabaseBase::mTrxLevel
273 private $mTrxFname = null;
276 * Record if possible write queries were done in the last transaction started
279 * @see DatabaseBase::mTrxLevel
281 private $mTrxDoneWrites = false;
284 * Record if the current transaction was started implicitly due to DBO_TRX being set.
287 * @see DatabaseBase::mTrxLevel
289 private $mTrxAutomatic = false;
292 * Array of levels of atomicity within transactions
296 private $mTrxAtomicLevels;
299 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
303 private $mTrxAutomaticAtomic = false;
307 * @var file handle for upgrade
309 protected $fileHandle = null;
313 * @var Process cache of VIEWs names in the database
315 protected $allViews = null;
317 # ------------------------------------------------------------------------------
319 # ------------------------------------------------------------------------------
320 # These optionally set a variable and return the previous state
323 * A string describing the current software version, and possibly
324 * other details in a user-friendly way. Will be listed on Special:Version, etc.
325 * Use getServerVersion() to get machine-friendly information.
327 * @return string: Version information from the database server
329 public function getServerInfo() {
330 return $this->getServerVersion();
334 * @return string: command delimiter used by this database engine
336 public function getDelimiter() {
337 return $this->delimiter
;
341 * Boolean, controls output of large amounts of debug information.
342 * @param $debug bool|null
343 * - true to enable debugging
344 * - false to disable debugging
345 * - omitted or null to do nothing
347 * @return bool|null previous value of the flag
349 public function debug( $debug = null ) {
350 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
354 * Turns buffering of SQL result sets on (true) or off (false). Default is
357 * Unbuffered queries are very troublesome in MySQL:
359 * - If another query is executed while the first query is being read
360 * out, the first query is killed. This means you can't call normal
361 * MediaWiki functions while you are reading an unbuffered query result
362 * from a normal wfGetDB() connection.
364 * - Unbuffered queries cause the MySQL server to use large amounts of
365 * memory and to hold broad locks which block other queries.
367 * If you want to limit client-side memory, it's almost always better to
368 * split up queries into batches using a LIMIT clause than to switch off
371 * @param $buffer null|bool
373 * @return null|bool The previous value of the flag
375 public function bufferResults( $buffer = null ) {
376 if ( is_null( $buffer ) ) {
377 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
379 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
384 * Turns on (false) or off (true) the automatic generation and sending
385 * of a "we're sorry, but there has been a database error" page on
386 * database errors. Default is on (false). When turned off, the
387 * code should use lastErrno() and lastError() to handle the
388 * situation as appropriate.
390 * Do not use this function outside of the Database classes.
392 * @param $ignoreErrors bool|null
394 * @return bool The previous value of the flag.
396 public function ignoreErrors( $ignoreErrors = null ) {
397 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
401 * Gets the current transaction level.
403 * Historically, transactions were allowed to be "nested". This is no
404 * longer supported, so this function really only returns a boolean.
406 * @return int The previous value
408 public function trxLevel() {
409 return $this->mTrxLevel
;
413 * Get/set the number of errors logged. Only useful when errors are ignored
414 * @param int $count The count to set, or omitted to leave it unchanged.
415 * @return int The error count
417 public function errorCount( $count = null ) {
418 return wfSetVar( $this->mErrorCount
, $count );
422 * Get/set the table prefix.
423 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
424 * @return string The previous table prefix.
426 public function tablePrefix( $prefix = null ) {
427 return wfSetVar( $this->mTablePrefix
, $prefix );
431 * Set the filehandle to copy write statements to.
433 * @param $fh filehandle
435 public function setFileHandle( $fh ) {
436 $this->fileHandle
= $fh;
440 * Get properties passed down from the server info array of the load
443 * @param string $name The entry of the info array to get, or null to get the
446 * @return LoadBalancer|null
448 public function getLBInfo( $name = null ) {
449 if ( is_null( $name ) ) {
450 return $this->mLBInfo
;
452 if ( array_key_exists( $name, $this->mLBInfo
) ) {
453 return $this->mLBInfo
[$name];
461 * Set the LB info array, or a member of it. If called with one parameter,
462 * the LB info array is set to that parameter. If it is called with two
463 * parameters, the member with the given name is set to the given value.
468 public function setLBInfo( $name, $value = null ) {
469 if ( is_null( $value ) ) {
470 $this->mLBInfo
= $name;
472 $this->mLBInfo
[$name] = $value;
477 * Set lag time in seconds for a fake slave
481 public function setFakeSlaveLag( $lag ) {
482 $this->mFakeSlaveLag
= $lag;
486 * Make this connection a fake master
488 * @param $enabled bool
490 public function setFakeMaster( $enabled = true ) {
491 $this->mFakeMaster
= $enabled;
495 * Returns true if this database supports (and uses) cascading deletes
499 public function cascadingDeletes() {
504 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
508 public function cleanupTriggers() {
513 * Returns true if this database is strict about what can be put into an IP field.
514 * Specifically, it uses a NULL value instead of an empty string.
518 public function strictIPs() {
523 * Returns true if this database uses timestamps rather than integers
527 public function realTimestamps() {
532 * Returns true if this database does an implicit sort when doing GROUP BY
536 public function implicitGroupby() {
541 * Returns true if this database does an implicit order by when the column has an index
542 * For example: SELECT page_title FROM page LIMIT 1
546 public function implicitOrderby() {
551 * Returns true if this database can do a native search on IP columns
552 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
556 public function searchableIPs() {
561 * Returns true if this database can use functional indexes
565 public function functionalIndexes() {
570 * Return the last query that went through DatabaseBase::query()
573 public function lastQuery() {
574 return $this->mLastQuery
;
578 * Returns true if the connection may have been used for write queries.
579 * Should return true if unsure.
583 public function doneWrites() {
584 return $this->mDoneWrites
;
588 * Returns true if there is a transaction open with possible write
589 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
593 public function writesOrCallbacksPending() {
594 return $this->mTrxLevel
&& (
595 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
600 * Is a connection to the database open?
603 public function isOpen() {
604 return $this->mOpened
;
608 * Set a flag for this connection
610 * @param $flag Integer: DBO_* constants from Defines.php:
611 * - DBO_DEBUG: output some debug info (same as debug())
612 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
613 * - DBO_TRX: automatically start transactions
614 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
615 * and removes it in command line mode
616 * - DBO_PERSISTENT: use persistant database connection
618 public function setFlag( $flag ) {
619 global $wgDebugDBTransactions;
620 $this->mFlags |
= $flag;
621 if ( ( $flag & DBO_TRX
) & $wgDebugDBTransactions ) {
622 wfDebug( "Implicit transactions are now disabled.\n" );
627 * Clear a flag for this connection
629 * @param $flag: same as setFlag()'s $flag param
631 public function clearFlag( $flag ) {
632 global $wgDebugDBTransactions;
633 $this->mFlags
&= ~
$flag;
634 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
635 wfDebug( "Implicit transactions are now disabled.\n" );
640 * Returns a boolean whether the flag $flag is set for this connection
642 * @param $flag: same as setFlag()'s $flag param
645 public function getFlag( $flag ) {
646 return !!( $this->mFlags
& $flag );
650 * General read-only accessor
652 * @param $name string
656 public function getProperty( $name ) {
663 public function getWikiID() {
664 if ( $this->mTablePrefix
) {
665 return "{$this->mDBname}-{$this->mTablePrefix}";
667 return $this->mDBname
;
672 * Return a path to the DBMS-specific schema file, otherwise default to tables.sql
676 public function getSchemaPath() {
678 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
679 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
681 return "$IP/maintenance/tables.sql";
685 # ------------------------------------------------------------------------------
687 # ------------------------------------------------------------------------------
692 * FIXME: It is possible to construct a Database object with no associated
693 * connection object, by specifying no parameters to __construct(). This
694 * feature is deprecated and should be removed.
696 * DatabaseBase subclasses should not be constructed directly in external
697 * code. DatabaseBase::factory() should be used instead.
699 * @param array Parameters passed from DatabaseBase::factory()
701 function __construct( $params = null ) {
702 global $wgDBprefix, $wgCommandLineMode, $wgDebugDBTransactions;
704 $this->mTrxAtomicLevels
= new SplStack
;
706 if ( is_array( $params ) ) { // MW 1.22
707 $server = $params['host'];
708 $user = $params['user'];
709 $password = $params['password'];
710 $dbName = $params['dbname'];
711 $flags = $params['flags'];
712 $tablePrefix = $params['tablePrefix'];
713 $foreign = $params['foreign'];
714 } else { // legacy calling pattern
715 wfDeprecated( __METHOD__
. " method called without parameter array.", "1.23" );
716 $args = func_get_args();
717 $server = isset( $args[0] ) ?
$args[0] : false;
718 $user = isset( $args[1] ) ?
$args[1] : false;
719 $password = isset( $args[2] ) ?
$args[2] : false;
720 $dbName = isset( $args[3] ) ?
$args[3] : false;
721 $flags = isset( $args[4] ) ?
$args[4] : 0;
722 $tablePrefix = isset( $args[5] ) ?
$args[5] : 'get from global';
723 $foreign = isset( $args[6] ) ?
$args[6] : false;
726 $this->mFlags
= $flags;
727 if ( $this->mFlags
& DBO_DEFAULT
) {
728 if ( $wgCommandLineMode ) {
729 $this->mFlags
&= ~DBO_TRX
;
730 if ( $wgDebugDBTransactions ) {
731 wfDebug( "Implicit transaction open disabled.\n" );
734 $this->mFlags |
= DBO_TRX
;
735 if ( $wgDebugDBTransactions ) {
736 wfDebug( "Implicit transaction open enabled.\n" );
741 /** Get the default table prefix*/
742 if ( $tablePrefix == 'get from global' ) {
743 $this->mTablePrefix
= $wgDBprefix;
745 $this->mTablePrefix
= $tablePrefix;
748 $this->mForeign
= $foreign;
751 $this->open( $server, $user, $password, $dbName );
756 * Called by serialize. Throw an exception when DB connection is serialized.
757 * This causes problems on some database engines because the connection is
758 * not restored on unserialize.
760 public function __sleep() {
761 throw new MWException( 'Database serialization may cause problems, since the connection is not restored on wakeup.' );
765 * Given a DB type, construct the name of the appropriate child class of
766 * DatabaseBase. This is designed to replace all of the manual stuff like:
767 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
768 * as well as validate against the canonical list of DB types we have
770 * This factory function is mostly useful for when you need to connect to a
771 * database other than the MediaWiki default (such as for external auth,
772 * an extension, et cetera). Do not use this to connect to the MediaWiki
773 * database. Example uses in core:
774 * @see LoadBalancer::reallyOpenConnection()
775 * @see ForeignDBRepo::getMasterDB()
776 * @see WebInstaller_DBConnect::execute()
780 * @param string $dbType A possible DB type
781 * @param array $p An array of options to pass to the constructor.
782 * Valid options are: host, user, password, dbname, flags, tablePrefix, driver
783 * @return DatabaseBase subclass or null
785 final public static function factory( $dbType, $p = array() ) {
786 $canonicalDBTypes = array(
787 'mysql' => array( 'mysqli', 'mysql' ),
788 'postgres' => array(),
795 $dbType = strtolower( $dbType );
796 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
797 $possibleDrivers = $canonicalDBTypes[$dbType];
798 if ( !empty( $p['driver'] ) ) {
799 if ( in_array( $p['driver'], $possibleDrivers ) ) {
800 $driver = $p['driver'];
802 throw new MWException( __METHOD__
.
803 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
806 foreach ( $possibleDrivers as $posDriver ) {
807 if ( extension_loaded( $posDriver ) ) {
808 $driver = $posDriver;
816 if ( $driver === false ) {
817 throw new MWException( __METHOD__
.
818 " no viable database extension found for type '$dbType'" );
821 $class = 'Database' . ucfirst( $driver );
822 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
824 'host' => isset( $p['host'] ) ?
$p['host'] : false,
825 'user' => isset( $p['user'] ) ?
$p['user'] : false,
826 'password' => isset( $p['password'] ) ?
$p['password'] : false,
827 'dbname' => isset( $p['dbname'] ) ?
$p['dbname'] : false,
828 'flags' => isset( $p['flags'] ) ?
$p['flags'] : 0,
829 'tablePrefix' => isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global',
830 'foreign' => isset( $p['foreign'] ) ?
$p['foreign'] : false
832 return new $class( $params );
838 protected function installErrorHandler() {
839 $this->mPHPError
= false;
840 $this->htmlErrors
= ini_set( 'html_errors', '0' );
841 set_error_handler( array( $this, 'connectionErrorHandler' ) );
845 * @return bool|string
847 protected function restoreErrorHandler() {
848 restore_error_handler();
849 if ( $this->htmlErrors
!== false ) {
850 ini_set( 'html_errors', $this->htmlErrors
);
852 if ( $this->mPHPError
) {
853 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
854 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
866 public function connectionErrorHandler( $errno, $errstr ) {
867 $this->mPHPError
= $errstr;
871 * Closes a database connection.
872 * if it is open : commits any open transactions
874 * @throws MWException
875 * @return Bool operation success. true if already closed.
877 public function close() {
878 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
879 throw new MWException( "Transaction idle callbacks still pending." );
881 $this->mOpened
= false;
882 if ( $this->mConn
) {
883 if ( $this->trxLevel() ) {
884 if ( !$this->mTrxAutomatic
) {
885 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
886 " performing implicit commit before closing connection!" );
889 $this->commit( __METHOD__
, 'flush' );
892 $ret = $this->closeConnection();
893 $this->mConn
= false;
901 * Closes underlying database connection
903 * @return bool: Whether connection was closed successfully
905 abstract protected function closeConnection();
908 * @param string $error fallback error message, used if none is given by DB
909 * @throws DBConnectionError
911 function reportConnectionError( $error = 'Unknown error' ) {
912 $myError = $this->lastError();
918 throw new DBConnectionError( $this, $error );
922 * The DBMS-dependent part of query()
924 * @param $sql String: SQL query.
925 * @return ResultWrapper Result object to feed to fetchObject, fetchRow, ...; or false on failure
927 abstract protected function doQuery( $sql );
930 * Determine whether a query writes to the DB.
931 * Should return true if unsure.
937 public function isWriteQuery( $sql ) {
938 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
942 * Run an SQL query and return the result. Normally throws a DBQueryError
943 * on failure. If errors are ignored, returns false instead.
945 * In new code, the query wrappers select(), insert(), update(), delete(),
946 * etc. should be used where possible, since they give much better DBMS
947 * independence and automatically quote or validate user input in a variety
948 * of contexts. This function is generally only useful for queries which are
949 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
952 * However, the query wrappers themselves should call this function.
954 * @param $sql String: SQL query
955 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
956 * comment (you can use __METHOD__ or add some extra info)
957 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
958 * maybe best to catch the exception instead?
959 * @throws MWException
960 * @return boolean|ResultWrapper. true for a successful write query, ResultWrapper object
961 * for a successful read query, or false on failure if $tempIgnore set
963 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
964 global $wgUser, $wgDebugDBTransactions;
966 $this->mLastQuery
= $sql;
967 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
968 # Set a flag indicating that writes have been done
969 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
970 $this->mDoneWrites
= true;
973 # Add a comment for easy SHOW PROCESSLIST interpretation
974 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
975 $userName = $wgUser->getName();
976 if ( mb_strlen( $userName ) > 15 ) {
977 $userName = mb_substr( $userName, 0, 15 ) . '...';
979 $userName = str_replace( '/', '', $userName );
984 // Add trace comment to the begin of the sql string, right after the operator.
985 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
986 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
988 # If DBO_TRX is set, start a transaction
989 if ( ( $this->mFlags
& DBO_TRX
) && !$this->mTrxLevel
&&
990 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' )
992 # Avoid establishing transactions for SHOW and SET statements too -
993 # that would delay transaction initializations to once connection
994 # is really used by application
995 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
996 if ( strpos( $sqlstart, "SHOW " ) !== 0 && strpos( $sqlstart, "SET " ) !== 0 ) {
997 if ( $wgDebugDBTransactions ) {
998 wfDebug( "Implicit transaction start.\n" );
1000 $this->begin( __METHOD__
. " ($fname)" );
1001 $this->mTrxAutomatic
= true;
1005 # Keep track of whether the transaction has write queries pending
1006 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $this->isWriteQuery( $sql ) ) {
1007 $this->mTrxDoneWrites
= true;
1008 Profiler
::instance()->transactionWritingIn( $this->mServer
, $this->mDBname
);
1011 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1012 if ( !Profiler
::instance()->isStub() ) {
1013 # generalizeSQL will probably cut down the query to reasonable
1014 # logging size most of the time. The substr is really just a sanity check.
1016 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1017 $totalProf = 'DatabaseBase::query-master';
1019 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1020 $totalProf = 'DatabaseBase::query';
1022 wfProfileIn( $totalProf );
1023 wfProfileIn( $queryProf );
1026 if ( $this->debug() ) {
1030 $sqlx = substr( $commentedSql, 0, 500 );
1031 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1033 $master = $isMaster ?
'master' : 'slave';
1034 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1037 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
1039 # Do the query and handle errors
1040 $ret = $this->doQuery( $commentedSql );
1042 MWDebug
::queryTime( $queryId );
1044 # Try reconnecting if the connection was lost
1045 if ( false === $ret && $this->wasErrorReissuable() ) {
1046 # Transaction is gone, like it or not
1047 $hadTrx = $this->mTrxLevel
; // possible lost transaction
1048 wfDebug( "Connection lost, reconnecting...\n" );
1049 $this->mTrxLevel
= 0;
1050 wfDebug( "Connection lost, reconnecting...\n" );
1052 if ( $this->ping() ) {
1053 wfDebug( "Reconnected\n" );
1054 $sqlx = substr( $commentedSql, 0, 500 );
1055 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1056 global $wgRequestTime;
1057 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
1058 if ( $elapsed < 300 ) {
1059 # Not a database error to lose a transaction after a minute or two
1060 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
1063 # Should be safe to silently retry
1064 $ret = $this->doQuery( $commentedSql );
1067 wfDebug( "Failed\n" );
1071 if ( false === $ret ) {
1072 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1075 if ( !Profiler
::instance()->isStub() ) {
1076 wfProfileOut( $queryProf );
1077 wfProfileOut( $totalProf );
1080 return $this->resultObject( $ret );
1084 * Report a query error. Log the error, and if neither the object ignore
1085 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1087 * @param $error String
1088 * @param $errno Integer
1089 * @param $sql String
1090 * @param $fname String
1091 * @param $tempIgnore Boolean
1092 * @throws DBQueryError
1094 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1095 # Ignore errors during error handling to avoid infinite recursion
1096 $ignore = $this->ignoreErrors( true );
1097 ++
$this->mErrorCount
;
1099 if ( $ignore ||
$tempIgnore ) {
1100 wfDebug( "SQL ERROR (ignored): $error\n" );
1101 $this->ignoreErrors( $ignore );
1103 $sql1line = str_replace( "\n", "\\n", $sql );
1104 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
1105 wfDebug( "SQL ERROR: " . $error . "\n" );
1106 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1111 * Intended to be compatible with the PEAR::DB wrapper functions.
1112 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1114 * ? = scalar value, quoted as necessary
1115 * ! = raw SQL bit (a function for instance)
1116 * & = filename; reads the file and inserts as a blob
1117 * (we don't use this though...)
1119 * @param $sql string
1120 * @param $func string
1124 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1125 /* MySQL doesn't support prepared statements (yet), so just
1126 pack up the query for reference. We'll manually replace
1128 return array( 'query' => $sql, 'func' => $func );
1132 * Free a prepared query, generated by prepare().
1135 protected function freePrepared( $prepared ) {
1136 /* No-op by default */
1140 * Execute a prepared query with the various arguments
1141 * @param string $prepared the prepared sql
1142 * @param $args Mixed: Either an array here, or put scalars as varargs
1144 * @return ResultWrapper
1146 public function execute( $prepared, $args = null ) {
1147 if ( !is_array( $args ) ) {
1149 $args = func_get_args();
1150 array_shift( $args );
1153 $sql = $this->fillPrepared( $prepared['query'], $args );
1155 return $this->query( $sql, $prepared['func'] );
1159 * For faking prepared SQL statements on DBs that don't support it directly.
1161 * @param string $preparedQuery a 'preparable' SQL statement
1162 * @param array $args of arguments to fill it with
1163 * @return string executable SQL
1165 public function fillPrepared( $preparedQuery, $args ) {
1167 $this->preparedArgs
=& $args;
1169 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1170 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1174 * preg_callback func for fillPrepared()
1175 * The arguments should be in $this->preparedArgs and must not be touched
1176 * while we're doing this.
1178 * @param $matches Array
1179 * @throws DBUnexpectedError
1182 protected function fillPreparedArg( $matches ) {
1183 switch ( $matches[1] ) {
1192 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1194 switch ( $matches[1] ) {
1196 return $this->addQuotes( $arg );
1200 # return $this->addQuotes( file_get_contents( $arg ) );
1201 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
1203 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
1208 * Free a result object returned by query() or select(). It's usually not
1209 * necessary to call this, just use unset() or let the variable holding
1210 * the result object go out of scope.
1212 * @param $res Mixed: A SQL result
1214 public function freeResult( $res ) {
1218 * A SELECT wrapper which returns a single field from a single result row.
1220 * Usually throws a DBQueryError on failure. If errors are explicitly
1221 * ignored, returns false on failure.
1223 * If no result rows are returned from the query, false is returned.
1225 * @param string|array $table Table name. See DatabaseBase::select() for details.
1226 * @param string $var The field name to select. This must be a valid SQL
1227 * fragment: do not use unvalidated user input.
1228 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1229 * @param string $fname The function name of the caller.
1230 * @param string|array $options The query options. See DatabaseBase::select() for details.
1232 * @return bool|mixed The value from the field, or false on failure.
1234 public function selectField( $table, $var, $cond = '', $fname = __METHOD__
,
1237 if ( !is_array( $options ) ) {
1238 $options = array( $options );
1241 $options['LIMIT'] = 1;
1243 $res = $this->select( $table, $var, $cond, $fname, $options );
1245 if ( $res === false ||
!$this->numRows( $res ) ) {
1249 $row = $this->fetchRow( $res );
1251 if ( $row !== false ) {
1252 return reset( $row );
1259 * Returns an optional USE INDEX clause to go after the table, and a
1260 * string to go at the end of the query.
1262 * @param array $options associative array of options to be turned into
1263 * an SQL query, valid keys are listed in the function.
1265 * @see DatabaseBase::select()
1267 public function makeSelectOptions( $options ) {
1268 $preLimitTail = $postLimitTail = '';
1271 $noKeyOptions = array();
1273 foreach ( $options as $key => $option ) {
1274 if ( is_numeric( $key ) ) {
1275 $noKeyOptions[$option] = true;
1279 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1281 $preLimitTail .= $this->makeOrderBy( $options );
1283 // if (isset($options['LIMIT'])) {
1284 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1285 // isset($options['OFFSET']) ? $options['OFFSET']
1289 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1290 $postLimitTail .= ' FOR UPDATE';
1293 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1294 $postLimitTail .= ' LOCK IN SHARE MODE';
1297 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1298 $startOpts .= 'DISTINCT';
1301 # Various MySQL extensions
1302 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1303 $startOpts .= ' /*! STRAIGHT_JOIN */';
1306 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1307 $startOpts .= ' HIGH_PRIORITY';
1310 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1311 $startOpts .= ' SQL_BIG_RESULT';
1314 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1315 $startOpts .= ' SQL_BUFFER_RESULT';
1318 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1319 $startOpts .= ' SQL_SMALL_RESULT';
1322 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1323 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1326 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1327 $startOpts .= ' SQL_CACHE';
1330 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1331 $startOpts .= ' SQL_NO_CACHE';
1334 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1335 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1340 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1344 * Returns an optional GROUP BY with an optional HAVING
1346 * @param array $options associative array of options
1348 * @see DatabaseBase::select()
1351 public function makeGroupByWithHaving( $options ) {
1353 if ( isset( $options['GROUP BY'] ) ) {
1354 $gb = is_array( $options['GROUP BY'] )
1355 ?
implode( ',', $options['GROUP BY'] )
1356 : $options['GROUP BY'];
1357 $sql .= ' GROUP BY ' . $gb;
1359 if ( isset( $options['HAVING'] ) ) {
1360 $having = is_array( $options['HAVING'] )
1361 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1362 : $options['HAVING'];
1363 $sql .= ' HAVING ' . $having;
1369 * Returns an optional ORDER BY
1371 * @param array $options associative array of options
1373 * @see DatabaseBase::select()
1376 public function makeOrderBy( $options ) {
1377 if ( isset( $options['ORDER BY'] ) ) {
1378 $ob = is_array( $options['ORDER BY'] )
1379 ?
implode( ',', $options['ORDER BY'] )
1380 : $options['ORDER BY'];
1381 return ' ORDER BY ' . $ob;
1387 * Execute a SELECT query constructed using the various parameters provided.
1388 * See below for full details of the parameters.
1390 * @param string|array $table Table name
1391 * @param string|array $vars Field names
1392 * @param string|array $conds Conditions
1393 * @param string $fname Caller function name
1394 * @param array $options Query options
1395 * @param $join_conds Array Join conditions
1397 * @param $table string|array
1399 * May be either an array of table names, or a single string holding a table
1400 * name. If an array is given, table aliases can be specified, for example:
1402 * array( 'a' => 'user' )
1404 * This includes the user table in the query, with the alias "a" available
1405 * for use in field names (e.g. a.user_name).
1407 * All of the table names given here are automatically run through
1408 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1409 * added, and various other table name mappings to be performed.
1412 * @param $vars string|array
1414 * May be either a field name or an array of field names. The field names
1415 * can be complete fragments of SQL, for direct inclusion into the SELECT
1416 * query. If an array is given, field aliases can be specified, for example:
1418 * array( 'maxrev' => 'MAX(rev_id)' )
1420 * This includes an expression with the alias "maxrev" in the query.
1422 * If an expression is given, care must be taken to ensure that it is
1426 * @param $conds string|array
1428 * May be either a string containing a single condition, or an array of
1429 * conditions. If an array is given, the conditions constructed from each
1430 * element are combined with AND.
1432 * Array elements may take one of two forms:
1434 * - Elements with a numeric key are interpreted as raw SQL fragments.
1435 * - Elements with a string key are interpreted as equality conditions,
1436 * where the key is the field name.
1437 * - If the value of such an array element is a scalar (such as a
1438 * string), it will be treated as data and thus quoted appropriately.
1439 * If it is null, an IS NULL clause will be added.
1440 * - If the value is an array, an IN(...) clause will be constructed,
1441 * such that the field name may match any of the elements in the
1442 * array. The elements of the array will be quoted.
1444 * Note that expressions are often DBMS-dependent in their syntax.
1445 * DBMS-independent wrappers are provided for constructing several types of
1446 * expression commonly used in condition queries. See:
1447 * - DatabaseBase::buildLike()
1448 * - DatabaseBase::conditional()
1451 * @param $options string|array
1453 * Optional: Array of query options. Boolean options are specified by
1454 * including them in the array as a string value with a numeric key, for
1457 * array( 'FOR UPDATE' )
1459 * The supported options are:
1461 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1462 * with LIMIT can theoretically be used for paging through a result set,
1463 * but this is discouraged in MediaWiki for performance reasons.
1465 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1466 * and then the first rows are taken until the limit is reached. LIMIT
1467 * is applied to a result set after OFFSET.
1469 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1470 * changed until the next COMMIT.
1472 * - DISTINCT: Boolean: return only unique result rows.
1474 * - GROUP BY: May be either an SQL fragment string naming a field or
1475 * expression to group by, or an array of such SQL fragments.
1477 * - HAVING: May be either an string containing a HAVING clause or an array of
1478 * conditions building the HAVING clause. If an array is given, the conditions
1479 * constructed from each element are combined with AND.
1481 * - ORDER BY: May be either an SQL fragment giving a field name or
1482 * expression to order by, or an array of such SQL fragments.
1484 * - USE INDEX: This may be either a string giving the index name to use
1485 * for the query, or an array. If it is an associative array, each key
1486 * gives the table name (or alias), each value gives the index name to
1487 * use for that table. All strings are SQL fragments and so should be
1488 * validated by the caller.
1490 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1491 * instead of SELECT.
1493 * And also the following boolean MySQL extensions, see the MySQL manual
1494 * for documentation:
1496 * - LOCK IN SHARE MODE
1500 * - SQL_BUFFER_RESULT
1501 * - SQL_SMALL_RESULT
1502 * - SQL_CALC_FOUND_ROWS
1507 * @param $join_conds string|array
1509 * Optional associative array of table-specific join conditions. In the
1510 * most common case, this is unnecessary, since the join condition can be
1511 * in $conds. However, it is useful for doing a LEFT JOIN.
1513 * The key of the array contains the table name or alias. The value is an
1514 * array with two elements, numbered 0 and 1. The first gives the type of
1515 * join, the second is an SQL fragment giving the join condition for that
1516 * table. For example:
1518 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1520 * @return ResultWrapper. If the query returned no rows, a ResultWrapper
1521 * with no rows in it will be returned. If there was a query error, a
1522 * DBQueryError exception will be thrown, except if the "ignore errors"
1523 * option was set, in which case false will be returned.
1525 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1526 $options = array(), $join_conds = array() ) {
1527 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1529 return $this->query( $sql, $fname );
1533 * The equivalent of DatabaseBase::select() except that the constructed SQL
1534 * is returned, instead of being immediately executed. This can be useful for
1535 * doing UNION queries, where the SQL text of each query is needed. In general,
1536 * however, callers outside of Database classes should just use select().
1538 * @param string|array $table Table name
1539 * @param string|array $vars Field names
1540 * @param string|array $conds Conditions
1541 * @param string $fname Caller function name
1542 * @param string|array $options Query options
1543 * @param $join_conds string|array Join conditions
1545 * @return string SQL query string.
1546 * @see DatabaseBase::select()
1548 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1549 $options = array(), $join_conds = array() )
1551 if ( is_array( $vars ) ) {
1552 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1555 $options = (array)$options;
1556 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1557 ?
$options['USE INDEX']
1560 if ( is_array( $table ) ) {
1562 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1563 } elseif ( $table != '' ) {
1564 if ( $table[0] == ' ' ) {
1565 $from = ' FROM ' . $table;
1568 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1574 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1575 $this->makeSelectOptions( $options );
1577 if ( !empty( $conds ) ) {
1578 if ( is_array( $conds ) ) {
1579 $conds = $this->makeList( $conds, LIST_AND
);
1581 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1583 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1586 if ( isset( $options['LIMIT'] ) ) {
1587 $sql = $this->limitResult( $sql, $options['LIMIT'],
1588 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1590 $sql = "$sql $postLimitTail";
1592 if ( isset( $options['EXPLAIN'] ) ) {
1593 $sql = 'EXPLAIN ' . $sql;
1600 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1601 * that a single row object is returned. If the query returns no rows,
1602 * false is returned.
1604 * @param string|array $table Table name
1605 * @param string|array $vars Field names
1606 * @param array $conds Conditions
1607 * @param string $fname Caller function name
1608 * @param string|array $options Query options
1609 * @param $join_conds array|string Join conditions
1611 * @return object|bool
1613 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1614 $options = array(), $join_conds = array() )
1616 $options = (array)$options;
1617 $options['LIMIT'] = 1;
1618 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1620 if ( $res === false ) {
1624 if ( !$this->numRows( $res ) ) {
1628 $obj = $this->fetchObject( $res );
1634 * Estimate rows in dataset.
1636 * MySQL allows you to estimate the number of rows that would be returned
1637 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1638 * index cardinality statistics, and is notoriously inaccurate, especially
1639 * when large numbers of rows have recently been added or deleted.
1641 * For DBMSs that don't support fast result size estimation, this function
1642 * will actually perform the SELECT COUNT(*).
1644 * Takes the same arguments as DatabaseBase::select().
1646 * @param string $table table name
1647 * @param array|string $vars : unused
1648 * @param array|string $conds : filters on the table
1649 * @param string $fname function name for profiling
1650 * @param array $options options for select
1651 * @return Integer: row count
1653 public function estimateRowCount( $table, $vars = '*', $conds = '',
1654 $fname = __METHOD__
, $options = array() )
1657 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1660 $row = $this->fetchRow( $res );
1661 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1668 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1669 * It's only slightly flawed. Don't use for anything important.
1671 * @param string $sql A SQL Query
1675 static function generalizeSQL( $sql ) {
1676 # This does the same as the regexp below would do, but in such a way
1677 # as to avoid crashing php on some large strings.
1678 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1680 $sql = str_replace( "\\\\", '', $sql );
1681 $sql = str_replace( "\\'", '', $sql );
1682 $sql = str_replace( "\\\"", '', $sql );
1683 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1684 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1686 # All newlines, tabs, etc replaced by single space
1687 $sql = preg_replace( '/\s+/', ' ', $sql );
1690 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1691 $sql = preg_replace( '/-?\d+/s', 'N', $sql );
1697 * Determines whether a field exists in a table
1699 * @param string $table table name
1700 * @param string $field filed to check on that table
1701 * @param string $fname calling function name (optional)
1702 * @return Boolean: whether $table has filed $field
1704 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1705 $info = $this->fieldInfo( $table, $field );
1711 * Determines whether an index exists
1712 * Usually throws a DBQueryError on failure
1713 * If errors are explicitly ignored, returns NULL on failure
1717 * @param $fname string
1721 public function indexExists( $table, $index, $fname = __METHOD__
) {
1722 if ( !$this->tableExists( $table ) ) {
1726 $info = $this->indexInfo( $table, $index, $fname );
1727 if ( is_null( $info ) ) {
1730 return $info !== false;
1735 * Query whether a given table exists
1737 * @param $table string
1738 * @param $fname string
1742 public function tableExists( $table, $fname = __METHOD__
) {
1743 $table = $this->tableName( $table );
1744 $old = $this->ignoreErrors( true );
1745 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1746 $this->ignoreErrors( $old );
1752 * mysql_field_type() wrapper
1757 public function fieldType( $res, $index ) {
1758 if ( $res instanceof ResultWrapper
) {
1759 $res = $res->result
;
1762 return mysql_field_type( $res, $index );
1766 * Determines if a given index is unique
1768 * @param $table string
1769 * @param $index string
1773 public function indexUnique( $table, $index ) {
1774 $indexInfo = $this->indexInfo( $table, $index );
1776 if ( !$indexInfo ) {
1780 return !$indexInfo[0]->Non_unique
;
1784 * Helper for DatabaseBase::insert().
1786 * @param $options array
1789 protected function makeInsertOptions( $options ) {
1790 return implode( ' ', $options );
1794 * INSERT wrapper, inserts an array into a table.
1798 * - A single associative array. The array keys are the field names, and
1799 * the values are the values to insert. The values are treated as data
1800 * and will be quoted appropriately. If NULL is inserted, this will be
1801 * converted to a database NULL.
1802 * - An array with numeric keys, holding a list of associative arrays.
1803 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1804 * each subarray must be identical to each other, and in the same order.
1806 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1809 * $options is an array of options, with boolean options encoded as values
1810 * with numeric keys, in the same style as $options in
1811 * DatabaseBase::select(). Supported options are:
1813 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1814 * any rows which cause duplicate key errors are not inserted. It's
1815 * possible to determine how many rows were successfully inserted using
1816 * DatabaseBase::affectedRows().
1818 * @param $table String Table name. This will be passed through
1819 * DatabaseBase::tableName().
1820 * @param $a Array of rows to insert
1821 * @param $fname String Calling function name (use __METHOD__) for logs/profiling
1822 * @param array $options of options
1826 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
1827 # No rows to insert, easy just return now
1828 if ( !count( $a ) ) {
1832 $table = $this->tableName( $table );
1834 if ( !is_array( $options ) ) {
1835 $options = array( $options );
1839 if ( isset( $options['fileHandle'] ) ) {
1840 $fh = $options['fileHandle'];
1842 $options = $this->makeInsertOptions( $options );
1844 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1846 $keys = array_keys( $a[0] );
1849 $keys = array_keys( $a );
1852 $sql = 'INSERT ' . $options .
1853 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1857 foreach ( $a as $row ) {
1863 $sql .= '(' . $this->makeList( $row ) . ')';
1866 $sql .= '(' . $this->makeList( $a ) . ')';
1869 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1871 } elseif ( $fh !== null ) {
1875 return (bool)$this->query( $sql, $fname );
1879 * Make UPDATE options for the DatabaseBase::update function
1881 * @param array $options The options passed to DatabaseBase::update
1884 protected function makeUpdateOptions( $options ) {
1885 if ( !is_array( $options ) ) {
1886 $options = array( $options );
1891 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1892 $opts[] = $this->lowPriorityOption();
1895 if ( in_array( 'IGNORE', $options ) ) {
1899 return implode( ' ', $opts );
1903 * UPDATE wrapper. Takes a condition array and a SET array.
1905 * @param $table String name of the table to UPDATE. This will be passed through
1906 * DatabaseBase::tableName().
1908 * @param array $values An array of values to SET. For each array element,
1909 * the key gives the field name, and the value gives the data
1910 * to set that field to. The data will be quoted by
1911 * DatabaseBase::addQuotes().
1913 * @param $conds Array: An array of conditions (WHERE). See
1914 * DatabaseBase::select() for the details of the format of
1915 * condition arrays. Use '*' to update all rows.
1917 * @param $fname String: The function name of the caller (from __METHOD__),
1918 * for logging and profiling.
1920 * @param array $options An array of UPDATE options, can be:
1921 * - IGNORE: Ignore unique key conflicts
1922 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1925 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
1926 $table = $this->tableName( $table );
1927 $opts = $this->makeUpdateOptions( $options );
1928 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1930 if ( $conds !== array() && $conds !== '*' ) {
1931 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1934 return $this->query( $sql, $fname );
1938 * Makes an encoded list of strings from an array
1939 * @param array $a containing the data
1940 * @param int $mode Constant
1941 * - LIST_COMMA: comma separated, no field names
1942 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
1943 * the documentation for $conds in DatabaseBase::select().
1944 * - LIST_OR: ORed WHERE clause (without the WHERE)
1945 * - LIST_SET: comma separated with field names, like a SET clause
1946 * - LIST_NAMES: comma separated field names
1948 * @throws MWException|DBUnexpectedError
1951 public function makeList( $a, $mode = LIST_COMMA
) {
1952 if ( !is_array( $a ) ) {
1953 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1959 foreach ( $a as $field => $value ) {
1961 if ( $mode == LIST_AND
) {
1963 } elseif ( $mode == LIST_OR
) {
1972 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1973 $list .= "($value)";
1974 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1976 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1977 if ( count( $value ) == 0 ) {
1978 throw new MWException( __METHOD__
. ": empty input for field $field" );
1979 } elseif ( count( $value ) == 1 ) {
1980 // Special-case single values, as IN isn't terribly efficient
1981 // Don't necessarily assume the single key is 0; we don't
1982 // enforce linear numeric ordering on other arrays here.
1983 $value = array_values( $value );
1984 $list .= $field . " = " . $this->addQuotes( $value[0] );
1986 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1988 } elseif ( $value === null ) {
1989 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1990 $list .= "$field IS ";
1991 } elseif ( $mode == LIST_SET
) {
1992 $list .= "$field = ";
1996 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1997 $list .= "$field = ";
1999 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
2007 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2008 * The keys on each level may be either integers or strings.
2010 * @param array $data organized as 2-d
2011 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2012 * @param string $baseKey field name to match the base-level keys to (eg 'pl_namespace')
2013 * @param string $subKey field name to match the sub-level keys to (eg 'pl_title')
2014 * @return Mixed: string SQL fragment, or false if no items in array.
2016 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2019 foreach ( $data as $base => $sub ) {
2020 if ( count( $sub ) ) {
2021 $conds[] = $this->makeList(
2022 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2028 return $this->makeList( $conds, LIST_OR
);
2030 // Nothing to search for...
2036 * Return aggregated value alias
2039 * @param $valuename string
2043 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2051 public function bitNot( $field ) {
2057 * @param $fieldRight
2060 public function bitAnd( $fieldLeft, $fieldRight ) {
2061 return "($fieldLeft & $fieldRight)";
2066 * @param $fieldRight
2069 public function bitOr( $fieldLeft, $fieldRight ) {
2070 return "($fieldLeft | $fieldRight)";
2074 * Build a concatenation list to feed into a SQL query
2075 * @param array $stringList list of raw SQL expressions; caller is responsible for any quoting
2078 public function buildConcat( $stringList ) {
2079 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2083 * Change the current database
2085 * @todo Explain what exactly will fail if this is not overridden.
2089 * @return bool Success or failure
2091 public function selectDB( $db ) {
2092 # Stub. Shouldn't cause serious problems if it's not overridden, but
2093 # if your database engine supports a concept similar to MySQL's
2094 # databases you may as well.
2095 $this->mDBname
= $db;
2100 * Get the current DB name
2102 public function getDBname() {
2103 return $this->mDBname
;
2107 * Get the server hostname or IP address
2109 public function getServer() {
2110 return $this->mServer
;
2114 * Format a table name ready for use in constructing an SQL query
2116 * This does two important things: it quotes the table names to clean them up,
2117 * and it adds a table prefix if only given a table name with no quotes.
2119 * All functions of this object which require a table name call this function
2120 * themselves. Pass the canonical name to such functions. This is only needed
2121 * when calling query() directly.
2123 * @param string $name database table name
2124 * @param string $format One of:
2125 * quoted - Automatically pass the table name through addIdentifierQuotes()
2126 * so that it can be used in a query.
2127 * raw - Do not add identifier quotes to the table name
2128 * @return String: full database name
2130 public function tableName( $name, $format = 'quoted' ) {
2131 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
2132 # Skip the entire process when we have a string quoted on both ends.
2133 # Note that we check the end so that we will still quote any use of
2134 # use of `database`.table. But won't break things if someone wants
2135 # to query a database table with a dot in the name.
2136 if ( $this->isQuotedIdentifier( $name ) ) {
2140 # Lets test for any bits of text that should never show up in a table
2141 # name. Basically anything like JOIN or ON which are actually part of
2142 # SQL queries, but may end up inside of the table value to combine
2143 # sql. Such as how the API is doing.
2144 # Note that we use a whitespace test rather than a \b test to avoid
2145 # any remote case where a word like on may be inside of a table name
2146 # surrounded by symbols which may be considered word breaks.
2147 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2151 # Split database and table into proper variables.
2152 # We reverse the explode so that database.table and table both output
2153 # the correct table.
2154 $dbDetails = explode( '.', $name, 2 );
2155 if ( count( $dbDetails ) == 2 ) {
2156 list( $database, $table ) = $dbDetails;
2157 # We don't want any prefix added in this case
2160 list( $table ) = $dbDetails;
2161 if ( $wgSharedDB !== null # We have a shared database
2162 && $this->mForeign
== false # We're not working on a foreign database
2163 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
2164 && in_array( $table, $wgSharedTables ) # A shared table is selected
2166 $database = $wgSharedDB;
2167 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
2170 $prefix = $this->mTablePrefix
; # Default prefix
2174 # Quote $table and apply the prefix if not quoted.
2175 $tableName = "{$prefix}{$table}";
2176 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) ) {
2177 $tableName = $this->addIdentifierQuotes( $tableName );
2180 # Quote $database and merge it with the table name if needed
2181 if ( $database !== null ) {
2182 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2183 $database = $this->addIdentifierQuotes( $database );
2185 $tableName = $database . '.' . $tableName;
2192 * Fetch a number of table names into an array
2193 * This is handy when you need to construct SQL for joins
2196 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2197 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2198 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2202 public function tableNames() {
2203 $inArray = func_get_args();
2206 foreach ( $inArray as $name ) {
2207 $retVal[$name] = $this->tableName( $name );
2214 * Fetch a number of table names into an zero-indexed numerical array
2215 * This is handy when you need to construct SQL for joins
2218 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2219 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2220 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2224 public function tableNamesN() {
2225 $inArray = func_get_args();
2228 foreach ( $inArray as $name ) {
2229 $retVal[] = $this->tableName( $name );
2236 * Get an aliased table name
2237 * e.g. tableName AS newTableName
2239 * @param string $name Table name, see tableName()
2240 * @param string|bool $alias Alias (optional)
2241 * @return string SQL name for aliased table. Will not alias a table to its own name
2243 public function tableNameWithAlias( $name, $alias = false ) {
2244 if ( !$alias ||
$alias == $name ) {
2245 return $this->tableName( $name );
2247 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2252 * Gets an array of aliased table names
2254 * @param $tables array( [alias] => table )
2255 * @return array of strings, see tableNameWithAlias()
2257 public function tableNamesWithAlias( $tables ) {
2259 foreach ( $tables as $alias => $table ) {
2260 if ( is_numeric( $alias ) ) {
2263 $retval[] = $this->tableNameWithAlias( $table, $alias );
2269 * Get an aliased field name
2270 * e.g. fieldName AS newFieldName
2272 * @param string $name Field name
2273 * @param string|bool $alias Alias (optional)
2274 * @return string SQL name for aliased field. Will not alias a field to its own name
2276 public function fieldNameWithAlias( $name, $alias = false ) {
2277 if ( !$alias ||
(string)$alias === (string)$name ) {
2280 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2285 * Gets an array of aliased field names
2287 * @param $fields array( [alias] => field )
2288 * @return array of strings, see fieldNameWithAlias()
2290 public function fieldNamesWithAlias( $fields ) {
2292 foreach ( $fields as $alias => $field ) {
2293 if ( is_numeric( $alias ) ) {
2296 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2302 * Get the aliased table name clause for a FROM clause
2303 * which might have a JOIN and/or USE INDEX clause
2305 * @param array $tables ( [alias] => table )
2306 * @param $use_index array Same as for select()
2307 * @param $join_conds array Same as for select()
2310 protected function tableNamesWithUseIndexOrJOIN(
2311 $tables, $use_index = array(), $join_conds = array()
2315 $use_index = (array)$use_index;
2316 $join_conds = (array)$join_conds;
2318 foreach ( $tables as $alias => $table ) {
2319 if ( !is_string( $alias ) ) {
2320 // No alias? Set it equal to the table name
2323 // Is there a JOIN clause for this table?
2324 if ( isset( $join_conds[$alias] ) ) {
2325 list( $joinType, $conds ) = $join_conds[$alias];
2326 $tableClause = $joinType;
2327 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2328 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2329 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2331 $tableClause .= ' ' . $use;
2334 $on = $this->makeList( (array)$conds, LIST_AND
);
2336 $tableClause .= ' ON (' . $on . ')';
2339 $retJOIN[] = $tableClause;
2340 // Is there an INDEX clause for this table?
2341 } elseif ( isset( $use_index[$alias] ) ) {
2342 $tableClause = $this->tableNameWithAlias( $table, $alias );
2343 $tableClause .= ' ' . $this->useIndexClause(
2344 implode( ',', (array)$use_index[$alias] ) );
2346 $ret[] = $tableClause;
2348 $tableClause = $this->tableNameWithAlias( $table, $alias );
2350 $ret[] = $tableClause;
2354 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2355 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2356 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2358 // Compile our final table clause
2359 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2363 * Get the name of an index in a given table
2369 protected function indexName( $index ) {
2370 // Backwards-compatibility hack
2372 'ar_usertext_timestamp' => 'usertext_timestamp',
2373 'un_user_id' => 'user_id',
2374 'un_user_ip' => 'user_ip',
2377 if ( isset( $renamed[$index] ) ) {
2378 return $renamed[$index];
2385 * Adds quotes and backslashes.
2391 public function addQuotes( $s ) {
2392 if ( $s === null ) {
2395 # This will also quote numeric values. This should be harmless,
2396 # and protects against weird problems that occur when they really
2397 # _are_ strings such as article titles and string->number->string
2398 # conversion is not 1:1.
2399 return "'" . $this->strencode( $s ) . "'";
2404 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2405 * MySQL uses `backticks` while basically everything else uses double quotes.
2406 * Since MySQL is the odd one out here the double quotes are our generic
2407 * and we implement backticks in DatabaseMysql.
2413 public function addIdentifierQuotes( $s ) {
2414 return '"' . str_replace( '"', '""', $s ) . '"';
2418 * Returns if the given identifier looks quoted or not according to
2419 * the database convention for quoting identifiers .
2421 * @param $name string
2425 public function isQuotedIdentifier( $name ) {
2426 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2433 protected function escapeLikeInternal( $s ) {
2434 $s = str_replace( '\\', '\\\\', $s );
2435 $s = $this->strencode( $s );
2436 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
2442 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
2443 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
2444 * Alternatively, the function could be provided with an array of aforementioned parameters.
2446 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
2447 * for subpages of 'My page title'.
2448 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
2451 * @return String: fully built LIKE statement
2453 public function buildLike() {
2454 $params = func_get_args();
2456 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2457 $params = $params[0];
2462 foreach ( $params as $value ) {
2463 if ( $value instanceof LikeMatch
) {
2464 $s .= $value->toString();
2466 $s .= $this->escapeLikeInternal( $value );
2470 return " LIKE '" . $s . "' ";
2474 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2478 public function anyChar() {
2479 return new LikeMatch( '_' );
2483 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2487 public function anyString() {
2488 return new LikeMatch( '%' );
2492 * Returns an appropriately quoted sequence value for inserting a new row.
2493 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2494 * subclass will return an integer, and save the value for insertId()
2496 * Any implementation of this function should *not* involve reusing
2497 * sequence numbers created for rolled-back transactions.
2498 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2499 * @param $seqName string
2502 public function nextSequenceValue( $seqName ) {
2507 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2508 * is only needed because a) MySQL must be as efficient as possible due to
2509 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2510 * which index to pick. Anyway, other databases might have different
2511 * indexes on a given table. So don't bother overriding this unless you're
2516 public function useIndexClause( $index ) {
2521 * REPLACE query wrapper.
2523 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2524 * except that when there is a duplicate key error, the old row is deleted
2525 * and the new row is inserted in its place.
2527 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2528 * perform the delete, we need to know what the unique indexes are so that
2529 * we know how to find the conflicting rows.
2531 * It may be more efficient to leave off unique indexes which are unlikely
2532 * to collide. However if you do this, you run the risk of encountering
2533 * errors which wouldn't have occurred in MySQL.
2535 * @param string $table The table to replace the row(s) in.
2536 * @param array $rows Can be either a single row to insert, or multiple rows,
2537 * in the same format as for DatabaseBase::insert()
2538 * @param array $uniqueIndexes is an array of indexes. Each element may be either
2539 * a field name or an array of field names
2540 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2542 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2543 $quotedTable = $this->tableName( $table );
2545 if ( count( $rows ) == 0 ) {
2550 if ( !is_array( reset( $rows ) ) ) {
2551 $rows = array( $rows );
2554 foreach ( $rows as $row ) {
2555 # Delete rows which collide
2556 if ( $uniqueIndexes ) {
2557 $sql = "DELETE FROM $quotedTable WHERE ";
2559 foreach ( $uniqueIndexes as $index ) {
2566 if ( is_array( $index ) ) {
2568 foreach ( $index as $col ) {
2574 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2577 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2581 $this->query( $sql, $fname );
2584 # Now insert the row
2585 $this->insert( $table, $row, $fname );
2590 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2593 * @param string $table Table name
2594 * @param array $rows Rows to insert
2595 * @param string $fname Caller function name
2597 * @return ResultWrapper
2599 protected function nativeReplace( $table, $rows, $fname ) {
2600 $table = $this->tableName( $table );
2603 if ( !is_array( reset( $rows ) ) ) {
2604 $rows = array( $rows );
2607 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2610 foreach ( $rows as $row ) {
2617 $sql .= '(' . $this->makeList( $row ) . ')';
2620 return $this->query( $sql, $fname );
2624 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2626 * This updates any conflicting rows (according to the unique indexes) using
2627 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2629 * $rows may be either:
2630 * - A single associative array. The array keys are the field names, and
2631 * the values are the values to insert. The values are treated as data
2632 * and will be quoted appropriately. If NULL is inserted, this will be
2633 * converted to a database NULL.
2634 * - An array with numeric keys, holding a list of associative arrays.
2635 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2636 * each subarray must be identical to each other, and in the same order.
2638 * It may be more efficient to leave off unique indexes which are unlikely
2639 * to collide. However if you do this, you run the risk of encountering
2640 * errors which wouldn't have occurred in MySQL.
2642 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2645 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2646 * @param array $rows A single row or list of rows to insert
2647 * @param array $uniqueIndexes List of single field names or field name tuples
2648 * @param array $set An array of values to SET. For each array element,
2649 * the key gives the field name, and the value gives the data
2650 * to set that field to. The data will be quoted by
2651 * DatabaseBase::addQuotes().
2652 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2653 * @param array $options of options
2658 public function upsert(
2659 $table, array $rows, array $uniqueIndexes, array $set, $fname = __METHOD__
2661 if ( !count( $rows ) ) {
2662 return true; // nothing to do
2664 $rows = is_array( reset( $rows ) ) ?
$rows : array( $rows );
2666 if ( count( $uniqueIndexes ) ) {
2667 $clauses = array(); // list WHERE clauses that each identify a single row
2668 foreach ( $rows as $row ) {
2669 foreach ( $uniqueIndexes as $index ) {
2670 $index = is_array( $index ) ?
$index : array( $index ); // columns
2671 $rowKey = array(); // unique key to this row
2672 foreach ( $index as $column ) {
2673 $rowKey[$column] = $row[$column];
2675 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2678 $where = array( $this->makeList( $clauses, LIST_OR
) );
2683 $useTrx = !$this->mTrxLevel
;
2685 $this->begin( $fname );
2688 # Update any existing conflicting row(s)
2689 if ( $where !== false ) {
2690 $ok = $this->update( $table, $set, $where, $fname );
2694 # Now insert any non-conflicting row(s)
2695 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2696 } catch ( Exception
$e ) {
2698 $this->rollback( $fname );
2703 $this->commit( $fname );
2710 * DELETE where the condition is a join.
2712 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2713 * we use sub-selects
2715 * For safety, an empty $conds will not delete everything. If you want to
2716 * delete all rows where the join condition matches, set $conds='*'.
2718 * DO NOT put the join condition in $conds.
2720 * @param $delTable String: The table to delete from.
2721 * @param $joinTable String: The other table.
2722 * @param $delVar String: The variable to join on, in the first table.
2723 * @param $joinVar String: The variable to join on, in the second table.
2724 * @param $conds Array: Condition array of field names mapped to variables,
2725 * ANDed together in the WHERE clause
2726 * @param $fname String: Calling function name (use __METHOD__) for
2728 * @throws DBUnexpectedError
2730 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2731 $fname = __METHOD__
)
2734 throw new DBUnexpectedError( $this,
2735 'DatabaseBase::deleteJoin() called with empty $conds' );
2738 $delTable = $this->tableName( $delTable );
2739 $joinTable = $this->tableName( $joinTable );
2740 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2741 if ( $conds != '*' ) {
2742 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2746 $this->query( $sql, $fname );
2750 * Returns the size of a text field, or -1 for "unlimited"
2752 * @param $table string
2753 * @param $field string
2757 public function textFieldSize( $table, $field ) {
2758 $table = $this->tableName( $table );
2759 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2760 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2761 $row = $this->fetchObject( $res );
2765 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2775 * A string to insert into queries to show that they're low-priority, like
2776 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2777 * string and nothing bad should happen.
2779 * @return string Returns the text of the low priority option if it is
2780 * supported, or a blank string otherwise
2782 public function lowPriorityOption() {
2787 * DELETE query wrapper.
2789 * @param array $table Table name
2790 * @param string|array $conds of conditions. See $conds in DatabaseBase::select() for
2791 * the format. Use $conds == "*" to delete all rows
2792 * @param string $fname name of the calling function
2794 * @throws DBUnexpectedError
2795 * @return bool|ResultWrapper
2797 public function delete( $table, $conds, $fname = __METHOD__
) {
2799 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2802 $table = $this->tableName( $table );
2803 $sql = "DELETE FROM $table";
2805 if ( $conds != '*' ) {
2806 if ( is_array( $conds ) ) {
2807 $conds = $this->makeList( $conds, LIST_AND
);
2809 $sql .= ' WHERE ' . $conds;
2812 return $this->query( $sql, $fname );
2816 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2817 * into another table.
2819 * @param string $destTable The table name to insert into
2820 * @param string|array $srcTable May be either a table name, or an array of table names
2821 * to include in a join.
2823 * @param array $varMap must be an associative array of the form
2824 * array( 'dest1' => 'source1', ...). Source items may be literals
2825 * rather than field names, but strings should be quoted with
2826 * DatabaseBase::addQuotes()
2828 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
2829 * the details of the format of condition arrays. May be "*" to copy the
2832 * @param string $fname The function name of the caller, from __METHOD__
2834 * @param array $insertOptions Options for the INSERT part of the query, see
2835 * DatabaseBase::insert() for details.
2836 * @param array $selectOptions Options for the SELECT part of the query, see
2837 * DatabaseBase::select() for details.
2839 * @return ResultWrapper
2841 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2842 $fname = __METHOD__
,
2843 $insertOptions = array(), $selectOptions = array() )
2845 $destTable = $this->tableName( $destTable );
2847 if ( is_array( $insertOptions ) ) {
2848 $insertOptions = implode( ' ', $insertOptions );
2851 if ( !is_array( $selectOptions ) ) {
2852 $selectOptions = array( $selectOptions );
2855 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2857 if ( is_array( $srcTable ) ) {
2858 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2860 $srcTable = $this->tableName( $srcTable );
2863 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2864 " SELECT $startOpts " . implode( ',', $varMap ) .
2865 " FROM $srcTable $useIndex ";
2867 if ( $conds != '*' ) {
2868 if ( is_array( $conds ) ) {
2869 $conds = $this->makeList( $conds, LIST_AND
);
2871 $sql .= " WHERE $conds";
2874 $sql .= " $tailOpts";
2876 return $this->query( $sql, $fname );
2880 * Construct a LIMIT query with optional offset. This is used for query
2881 * pages. The SQL should be adjusted so that only the first $limit rows
2882 * are returned. If $offset is provided as well, then the first $offset
2883 * rows should be discarded, and the next $limit rows should be returned.
2884 * If the result of the query is not ordered, then the rows to be returned
2885 * are theoretically arbitrary.
2887 * $sql is expected to be a SELECT, if that makes a difference.
2889 * The version provided by default works in MySQL and SQLite. It will very
2890 * likely need to be overridden for most other DBMSes.
2892 * @param string $sql SQL query we will append the limit too
2893 * @param $limit Integer the SQL limit
2894 * @param $offset Integer|bool the SQL offset (default false)
2896 * @throws DBUnexpectedError
2899 public function limitResult( $sql, $limit, $offset = false ) {
2900 if ( !is_numeric( $limit ) ) {
2901 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2903 return "$sql LIMIT "
2904 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2909 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2910 * within the UNION construct.
2913 public function unionSupportsOrderAndLimit() {
2914 return true; // True for almost every DB supported
2918 * Construct a UNION query
2919 * This is used for providing overload point for other DB abstractions
2920 * not compatible with the MySQL syntax.
2921 * @param array $sqls SQL statements to combine
2922 * @param $all Boolean: use UNION ALL
2923 * @return String: SQL fragment
2925 public function unionQueries( $sqls, $all ) {
2926 $glue = $all ?
') UNION ALL (' : ') UNION (';
2927 return '(' . implode( $glue, $sqls ) . ')';
2931 * Returns an SQL expression for a simple conditional. This doesn't need
2932 * to be overridden unless CASE isn't supported in your DBMS.
2934 * @param string|array $cond SQL expression which will result in a boolean value
2935 * @param string $trueVal SQL expression to return if true
2936 * @param string $falseVal SQL expression to return if false
2937 * @return String: SQL fragment
2939 public function conditional( $cond, $trueVal, $falseVal ) {
2940 if ( is_array( $cond ) ) {
2941 $cond = $this->makeList( $cond, LIST_AND
);
2943 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2947 * Returns a comand for str_replace function in SQL query.
2948 * Uses REPLACE() in MySQL
2950 * @param string $orig column to modify
2951 * @param string $old column to seek
2952 * @param string $new column to replace with
2956 public function strreplace( $orig, $old, $new ) {
2957 return "REPLACE({$orig}, {$old}, {$new})";
2961 * Determines how long the server has been up
2966 public function getServerUptime() {
2971 * Determines if the last failure was due to a deadlock
2976 public function wasDeadlock() {
2981 * Determines if the last failure was due to a lock timeout
2986 public function wasLockTimeout() {
2991 * Determines if the last query error was something that should be dealt
2992 * with by pinging the connection and reissuing the query.
2997 public function wasErrorReissuable() {
3002 * Determines if the last failure was due to the database being read-only.
3007 public function wasReadOnlyError() {
3012 * Perform a deadlock-prone transaction.
3014 * This function invokes a callback function to perform a set of write
3015 * queries. If a deadlock occurs during the processing, the transaction
3016 * will be rolled back and the callback function will be called again.
3019 * $dbw->deadlockLoop( callback, ... );
3021 * Extra arguments are passed through to the specified callback function.
3023 * Returns whatever the callback function returned on its successful,
3024 * iteration, or false on error, for example if the retry limit was
3029 public function deadlockLoop() {
3030 $this->begin( __METHOD__
);
3031 $args = func_get_args();
3032 $function = array_shift( $args );
3033 $oldIgnore = $this->ignoreErrors( true );
3034 $tries = self
::DEADLOCK_TRIES
;
3036 if ( is_array( $function ) ) {
3037 $fname = $function[0];
3043 $retVal = call_user_func_array( $function, $args );
3044 $error = $this->lastError();
3045 $errno = $this->lastErrno();
3046 $sql = $this->lastQuery();
3049 if ( $this->wasDeadlock() ) {
3051 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3053 $this->reportQueryError( $error, $errno, $sql, $fname );
3056 } while ( $this->wasDeadlock() && --$tries > 0 );
3058 $this->ignoreErrors( $oldIgnore );
3060 if ( $tries <= 0 ) {
3061 $this->rollback( __METHOD__
);
3062 $this->reportQueryError( $error, $errno, $sql, $fname );
3065 $this->commit( __METHOD__
);
3071 * Wait for the slave to catch up to a given master position.
3073 * @param $pos DBMasterPos object
3074 * @param $timeout Integer: the maximum number of seconds to wait for
3077 * @return integer: zero if the slave was past that position already,
3078 * greater than zero if we waited for some period of time, less than
3079 * zero if we timed out.
3081 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3082 wfProfileIn( __METHOD__
);
3084 if ( !is_null( $this->mFakeSlaveLag
) ) {
3085 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
3087 if ( $wait > $timeout * 1e6
) {
3088 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
3089 wfProfileOut( __METHOD__
);
3091 } elseif ( $wait > 0 ) {
3092 wfDebug( "Fake slave waiting $wait us\n" );
3094 wfProfileOut( __METHOD__
);
3097 wfDebug( "Fake slave up to date ($wait us)\n" );
3098 wfProfileOut( __METHOD__
);
3103 wfProfileOut( __METHOD__
);
3105 # Real waits are implemented in the subclass.
3110 * Get the replication position of this slave
3112 * @return DBMasterPos, or false if this is not a slave.
3114 public function getSlavePos() {
3115 if ( !is_null( $this->mFakeSlaveLag
) ) {
3116 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
3117 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
3126 * Get the position of this master
3128 * @return DBMasterPos, or false if this is not a master
3130 public function getMasterPos() {
3131 if ( $this->mFakeMaster
) {
3132 return new MySQLMasterPos( 'fake', microtime( true ) );
3139 * Run an anonymous function as soon as there is no transaction pending.
3140 * If there is a transaction and it is rolled back, then the callback is cancelled.
3141 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3142 * Callbacks must commit any transactions that they begin.
3144 * This is useful for updates to different systems or when separate transactions are needed.
3145 * For example, one might want to enqueue jobs into a system outside the database, but only
3146 * after the database is updated so that the jobs will see the data when they actually run.
3147 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3149 * @param callable $callback
3152 final public function onTransactionIdle( $callback ) {
3153 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
3154 if ( !$this->mTrxLevel
) {
3155 $this->runOnTransactionIdleCallbacks();
3160 * Run an anonymous function before the current transaction commits or now if there is none.
3161 * If there is a transaction and it is rolled back, then the callback is cancelled.
3162 * Callbacks must not start nor commit any transactions.
3164 * This is useful for updates that easily cause deadlocks if locks are held too long
3165 * but where atomicity is strongly desired for these updates and some related updates.
3167 * @param callable $callback
3170 final public function onTransactionPreCommitOrIdle( $callback ) {
3171 if ( $this->mTrxLevel
) {
3172 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
3174 $this->onTransactionIdle( $callback ); // this will trigger immediately
3179 * Actually any "on transaction idle" callbacks.
3183 protected function runOnTransactionIdleCallbacks() {
3184 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
3186 $e = null; // last exception
3187 do { // callbacks may add callbacks :)
3188 $callbacks = $this->mTrxIdleCallbacks
;
3189 $this->mTrxIdleCallbacks
= array(); // recursion guard
3190 foreach ( $callbacks as $callback ) {
3192 list( $phpCallback ) = $callback;
3193 $this->clearFlag( DBO_TRX
); // make each query its own transaction
3194 call_user_func( $phpCallback );
3195 $this->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
3196 } catch ( Exception
$e ) {}
3198 } while ( count( $this->mTrxIdleCallbacks
) );
3200 if ( $e instanceof Exception
) {
3201 throw $e; // re-throw any last exception
3206 * Actually any "on transaction pre-commit" callbacks.
3210 protected function runOnTransactionPreCommitCallbacks() {
3211 $e = null; // last exception
3212 do { // callbacks may add callbacks :)
3213 $callbacks = $this->mTrxPreCommitCallbacks
;
3214 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
3215 foreach ( $callbacks as $callback ) {
3217 list( $phpCallback ) = $callback;
3218 call_user_func( $phpCallback );
3219 } catch ( Exception
$e ) {}
3221 } while ( count( $this->mTrxPreCommitCallbacks
) );
3223 if ( $e instanceof Exception
) {
3224 throw $e; // re-throw any last exception
3229 * Begin an atomic section of statements
3231 * If a transaction has been started already, just keep track of the given
3232 * section name to make sure the transaction is not committed pre-maturely.
3233 * This function can be used in layers (with sub-sections), so use a stack
3234 * to keep track of the different atomic sections. If there is no transaction,
3235 * start one implicitly.
3237 * The goal of this function is to create an atomic section of SQL queries
3238 * without having to start a new transaction if it already exists.
3240 * Atomic sections are more strict than transactions. With transactions,
3241 * attempting to begin a new transaction when one is already running results
3242 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3243 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3244 * and any database transactions cannot be began or committed until all atomic
3245 * levels are closed. There is no such thing as implicitly opening or closing
3246 * an atomic section.
3249 * @param string $fname
3252 final public function startAtomic( $fname = __METHOD__
) {
3253 if ( !$this->mTrxLevel
) {
3254 $this->begin( $fname );
3255 $this->mTrxAutomatic
= true;
3256 $this->mTrxAutomaticAtomic
= true;
3259 $this->mTrxAtomicLevels
->push( $fname );
3263 * Ends an atomic section of SQL statements
3265 * Ends the next section of atomic SQL statements and commits the transaction
3269 * @see DatabaseBase::startAtomic
3270 * @param string $fname
3273 final public function endAtomic( $fname = __METHOD__
) {
3274 if ( !$this->mTrxLevel
) {
3275 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3277 if ( $this->mTrxAtomicLevels
->isEmpty() ||
3278 $this->mTrxAtomicLevels
->pop() !== $fname
3280 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3283 if ( $this->mTrxAtomicLevels
->isEmpty() && $this->mTrxAutomaticAtomic
) {
3284 $this->commit( $fname, 'flush' );
3289 * Begin a transaction. If a transaction is already in progress, that transaction will be committed before the
3290 * new transaction is started.
3292 * Note that when the DBO_TRX flag is set (which is usually the case for web requests, but not for maintenance scripts),
3293 * any previous database query will have started a transaction automatically.
3295 * Nesting of transactions is not supported. Attempts to nest transactions will cause a warning, unless the current
3296 * transaction was started automatically because of the DBO_TRX flag.
3298 * @param $fname string
3301 final public function begin( $fname = __METHOD__
) {
3302 global $wgDebugDBTransactions;
3304 if ( $this->mTrxLevel
) { // implicit commit
3305 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3306 // If the current transaction was an automatic atomic one, then we definitely have
3307 // a problem. Same if there is any unclosed atomic level.
3308 throw new DBUnexpectedError( $this,
3309 "Attempted to start explicit transaction when atomic levels are still open."
3311 } elseif ( !$this->mTrxAutomatic
) {
3312 // We want to warn about inadvertently nested begin/commit pairs, but not about
3313 // auto-committing implicit transactions that were started by query() via DBO_TRX
3314 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3315 " performing implicit commit!";
3317 wfLogDBError( $msg );
3319 // if the transaction was automatic and has done write operations,
3320 // log it if $wgDebugDBTransactions is enabled.
3321 if ( $this->mTrxDoneWrites
&& $wgDebugDBTransactions ) {
3322 wfDebug( "$fname: Automatic transaction with writes in progress" .
3323 " (from {$this->mTrxFname}), performing implicit commit!\n"
3328 $this->runOnTransactionPreCommitCallbacks();
3329 $this->doCommit( $fname );
3330 if ( $this->mTrxDoneWrites
) {
3331 Profiler
::instance()->transactionWritingOut( $this->mServer
, $this->mDBname
);
3333 $this->runOnTransactionIdleCallbacks();
3336 $this->doBegin( $fname );
3337 $this->mTrxFname
= $fname;
3338 $this->mTrxDoneWrites
= false;
3339 $this->mTrxAutomatic
= false;
3340 $this->mTrxAutomaticAtomic
= false;
3341 $this->mTrxAtomicLevels
= new SplStack
;
3342 $this->mTrxIdleCallbacks
= array();
3343 $this->mTrxPreCommitCallbacks
= array();
3347 * Issues the BEGIN command to the database server.
3349 * @see DatabaseBase::begin()
3350 * @param type $fname
3352 protected function doBegin( $fname ) {
3353 $this->query( 'BEGIN', $fname );
3354 $this->mTrxLevel
= 1;
3358 * Commits a transaction previously started using begin().
3359 * If no transaction is in progress, a warning is issued.
3361 * Nesting of transactions is not supported.
3363 * @param $fname string
3364 * @param string $flush Flush flag, set to 'flush' to disable warnings about explicitly committing implicit
3365 * transactions, or calling commit when no transaction is in progress.
3366 * This will silently break any ongoing explicit transaction. Only set the flush flag if you are sure
3367 * that it is safe to ignore these warnings in your context.
3369 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3370 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3371 // There are still atomic sections open. This cannot be ignored
3372 throw new DBUnexpectedError( $this, "Attempted to commit transaction while atomic sections are still open" );
3375 if ( $flush != 'flush' ) {
3376 if ( !$this->mTrxLevel
) {
3377 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3378 } elseif ( $this->mTrxAutomatic
) {
3379 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3382 if ( !$this->mTrxLevel
) {
3383 return; // nothing to do
3384 } elseif ( !$this->mTrxAutomatic
) {
3385 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3389 $this->runOnTransactionPreCommitCallbacks();
3390 $this->doCommit( $fname );
3391 if ( $this->mTrxDoneWrites
) {
3392 Profiler
::instance()->transactionWritingOut( $this->mServer
, $this->mDBname
);
3394 $this->runOnTransactionIdleCallbacks();
3398 * Issues the COMMIT command to the database server.
3400 * @see DatabaseBase::commit()
3401 * @param type $fname
3403 protected function doCommit( $fname ) {
3404 if ( $this->mTrxLevel
) {
3405 $this->query( 'COMMIT', $fname );
3406 $this->mTrxLevel
= 0;
3411 * Rollback a transaction previously started using begin().
3412 * If no transaction is in progress, a warning is issued.
3414 * No-op on non-transactional databases.
3416 * @param $fname string
3418 final public function rollback( $fname = __METHOD__
) {
3419 if ( !$this->mTrxLevel
) {
3420 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3422 $this->doRollback( $fname );
3423 $this->mTrxIdleCallbacks
= array(); // cancel
3424 $this->mTrxPreCommitCallbacks
= array(); // cancel
3425 $this->mTrxAtomicLevels
= new SplStack
;
3426 if ( $this->mTrxDoneWrites
) {
3427 Profiler
::instance()->transactionWritingOut( $this->mServer
, $this->mDBname
);
3432 * Issues the ROLLBACK command to the database server.
3434 * @see DatabaseBase::rollback()
3435 * @param type $fname
3437 protected function doRollback( $fname ) {
3438 if ( $this->mTrxLevel
) {
3439 $this->query( 'ROLLBACK', $fname, true );
3440 $this->mTrxLevel
= 0;
3445 * Creates a new table with structure copied from existing table
3446 * Note that unlike most database abstraction functions, this function does not
3447 * automatically append database prefix, because it works at a lower
3448 * abstraction level.
3449 * The table names passed to this function shall not be quoted (this
3450 * function calls addIdentifierQuotes when needed).
3452 * @param string $oldName name of table whose structure should be copied
3453 * @param string $newName name of table to be created
3454 * @param $temporary Boolean: whether the new table should be temporary
3455 * @param string $fname calling function name
3456 * @throws MWException
3457 * @return Boolean: true if operation was successful
3459 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3462 throw new MWException(
3463 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3467 * List all tables on the database
3469 * @param string $prefix Only show tables with this prefix, e.g. mw_
3470 * @param string $fname calling function name
3471 * @throws MWException
3473 function listTables( $prefix = null, $fname = __METHOD__
) {
3474 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3478 * Reset the views process cache set by listViews()
3481 final public function clearViewsCache() {
3482 $this->allViews
= null;
3486 * Lists all the VIEWs in the database
3488 * For caching purposes the list of all views should be stored in
3489 * $this->allViews. The process cache can be cleared with clearViewsCache()
3491 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3492 * @param string $fname Name of calling function
3493 * @throws MWException
3496 public function listViews( $prefix = null, $fname = __METHOD__
) {
3497 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3501 * Differentiates between a TABLE and a VIEW
3503 * @param $name string: Name of the database-structure to test.
3504 * @throws MWException
3507 public function isView( $name ) {
3508 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3512 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3513 * to the format used for inserting into timestamp fields in this DBMS.
3515 * The result is unquoted, and needs to be passed through addQuotes()
3516 * before it can be included in raw SQL.
3518 * @param $ts string|int
3522 public function timestamp( $ts = 0 ) {
3523 return wfTimestamp( TS_MW
, $ts );
3527 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3528 * to the format used for inserting into timestamp fields in this DBMS. If
3529 * NULL is input, it is passed through, allowing NULL values to be inserted
3530 * into timestamp fields.
3532 * The result is unquoted, and needs to be passed through addQuotes()
3533 * before it can be included in raw SQL.
3535 * @param $ts string|int
3539 public function timestampOrNull( $ts = null ) {
3540 if ( is_null( $ts ) ) {
3543 return $this->timestamp( $ts );
3548 * Take the result from a query, and wrap it in a ResultWrapper if
3549 * necessary. Boolean values are passed through as is, to indicate success
3550 * of write queries or failure.
3552 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3553 * resource, and it was necessary to call this function to convert it to
3554 * a wrapper. Nowadays, raw database objects are never exposed to external
3555 * callers, so this is unnecessary in external code. For compatibility with
3556 * old code, ResultWrapper objects are passed through unaltered.
3558 * @param $result bool|ResultWrapper
3560 * @return bool|ResultWrapper
3562 public function resultObject( $result ) {
3563 if ( empty( $result ) ) {
3565 } elseif ( $result instanceof ResultWrapper
) {
3567 } elseif ( $result === true ) {
3568 // Successful write query
3571 return new ResultWrapper( $this, $result );
3576 * Ping the server and try to reconnect if it there is no connection
3578 * @return bool Success or failure
3580 public function ping() {
3581 # Stub. Not essential to override.
3586 * Get slave lag. Currently supported only by MySQL.
3588 * Note that this function will generate a fatal error on many
3589 * installations. Most callers should use LoadBalancer::safeGetLag()
3592 * @return int Database replication lag in seconds
3594 public function getLag() {
3595 return intval( $this->mFakeSlaveLag
);
3599 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3603 function maxListLen() {
3608 * Some DBMSs have a special format for inserting into blob fields, they
3609 * don't allow simple quoted strings to be inserted. To insert into such
3610 * a field, pass the data through this function before passing it to
3611 * DatabaseBase::insert().
3615 public function encodeBlob( $b ) {
3620 * Some DBMSs return a special placeholder object representing blob fields
3621 * in result objects. Pass the object through this function to return the
3626 public function decodeBlob( $b ) {
3631 * Override database's default behavior. $options include:
3632 * 'connTimeout' : Set the connection timeout value in seconds.
3633 * May be useful for very long batch queries such as
3634 * full-wiki dumps, where a single query reads out over
3637 * @param $options Array
3640 public function setSessionOptions( array $options ) {
3644 * Read and execute SQL commands from a file.
3646 * Returns true on success, error string or exception on failure (depending
3647 * on object's error ignore settings).
3649 * @param string $filename File name to open
3650 * @param bool|callable $lineCallback Optional function called before reading each line
3651 * @param bool|callable $resultCallback Optional function called for each MySQL result
3652 * @param bool|string $fname Calling function name or false if name should be
3653 * generated dynamically using $filename
3654 * @param bool|callable $inputCallback Callback: Optional function called for each complete line sent
3655 * @throws MWException
3656 * @throws Exception|MWException
3657 * @return bool|string
3659 public function sourceFile(
3660 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3662 wfSuppressWarnings();
3663 $fp = fopen( $filename, 'r' );
3664 wfRestoreWarnings();
3666 if ( false === $fp ) {
3667 throw new MWException( "Could not open \"{$filename}\".\n" );
3671 $fname = __METHOD__
. "( $filename )";
3675 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3677 catch ( MWException
$e ) {
3688 * Get the full path of a patch file. Originally based on archive()
3689 * from updaters.inc. Keep in mind this always returns a patch, as
3690 * it fails back to MySQL if no DB-specific patch can be found
3692 * @param string $patch The name of the patch, like patch-something.sql
3693 * @return String Full path to patch file
3695 public function patchPath( $patch ) {
3698 $dbType = $this->getType();
3699 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3700 return "$IP/maintenance/$dbType/archives/$patch";
3702 return "$IP/maintenance/archives/$patch";
3707 * Set variables to be used in sourceFile/sourceStream, in preference to the
3708 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3709 * all. If it's set to false, $GLOBALS will be used.
3711 * @param bool|array $vars mapping variable name to value.
3713 public function setSchemaVars( $vars ) {
3714 $this->mSchemaVars
= $vars;
3718 * Read and execute commands from an open file handle.
3720 * Returns true on success, error string or exception on failure (depending
3721 * on object's error ignore settings).
3723 * @param $fp Resource: File handle
3724 * @param $lineCallback Callback: Optional function called before reading each query
3725 * @param $resultCallback Callback: Optional function called for each MySQL result
3726 * @param string $fname Calling function name
3727 * @param $inputCallback Callback: Optional function called for each complete query sent
3728 * @return bool|string
3730 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3731 $fname = __METHOD__
, $inputCallback = false )
3735 while ( !feof( $fp ) ) {
3736 if ( $lineCallback ) {
3737 call_user_func( $lineCallback );
3740 $line = trim( fgets( $fp ) );
3742 if ( $line == '' ) {
3746 if ( '-' == $line[0] && '-' == $line[1] ) {
3754 $done = $this->streamStatementEnd( $cmd, $line );
3758 if ( $done ||
feof( $fp ) ) {
3759 $cmd = $this->replaceVars( $cmd );
3761 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3762 $res = $this->query( $cmd, $fname );
3764 if ( $resultCallback ) {
3765 call_user_func( $resultCallback, $res, $this );
3768 if ( false === $res ) {
3769 $err = $this->lastError();
3770 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3781 * Called by sourceStream() to check if we've reached a statement end
3783 * @param string $sql SQL assembled so far
3784 * @param string $newLine New line about to be added to $sql
3785 * @return Bool Whether $newLine contains end of the statement
3787 public function streamStatementEnd( &$sql, &$newLine ) {
3788 if ( $this->delimiter
) {
3790 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3791 if ( $newLine != $prev ) {
3799 * Database independent variable replacement. Replaces a set of variables
3800 * in an SQL statement with their contents as given by $this->getSchemaVars().
3802 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3804 * - '{$var}' should be used for text and is passed through the database's
3806 * - `{$var}` should be used for identifiers (eg: table and database names),
3807 * it is passed through the database's addIdentifierQuotes method which
3808 * can be overridden if the database uses something other than backticks.
3809 * - / *$var* / is just encoded, besides traditional table prefix and
3810 * table options its use should be avoided.
3812 * @param string $ins SQL statement to replace variables in
3813 * @return String The new SQL statement with variables replaced
3815 protected function replaceSchemaVars( $ins ) {
3816 $vars = $this->getSchemaVars();
3817 foreach ( $vars as $var => $value ) {
3819 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
3821 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
3823 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ), $ins );
3829 * Replace variables in sourced SQL
3831 * @param $ins string
3835 protected function replaceVars( $ins ) {
3836 $ins = $this->replaceSchemaVars( $ins );
3839 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3840 array( $this, 'tableNameCallback' ), $ins );
3843 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
3844 array( $this, 'indexNameCallback' ), $ins );
3850 * Get schema variables. If none have been set via setSchemaVars(), then
3851 * use some defaults from the current object.
3855 protected function getSchemaVars() {
3856 if ( $this->mSchemaVars
) {
3857 return $this->mSchemaVars
;
3859 return $this->getDefaultSchemaVars();
3864 * Get schema variables to use if none have been set via setSchemaVars().
3866 * Override this in derived classes to provide variables for tables.sql
3867 * and SQL patch files.
3871 protected function getDefaultSchemaVars() {
3876 * Table name callback
3878 * @param $matches array
3882 protected function tableNameCallback( $matches ) {
3883 return $this->tableName( $matches[1] );
3887 * Index name callback
3889 * @param $matches array
3893 protected function indexNameCallback( $matches ) {
3894 return $this->indexName( $matches[1] );
3898 * Check to see if a named lock is available. This is non-blocking.
3900 * @param string $lockName name of lock to poll
3901 * @param string $method name of method calling us
3905 public function lockIsFree( $lockName, $method ) {
3910 * Acquire a named lock
3912 * Abstracted from Filestore::lock() so child classes can implement for
3915 * @param string $lockName name of lock to aquire
3916 * @param string $method name of method calling us
3917 * @param $timeout Integer: timeout
3920 public function lock( $lockName, $method, $timeout = 5 ) {
3927 * @param string $lockName Name of lock to release
3928 * @param string $method Name of method calling us
3930 * @return int Returns 1 if the lock was released, 0 if the lock was not established
3931 * by this thread (in which case the lock is not released), and NULL if the named
3932 * lock did not exist
3934 public function unlock( $lockName, $method ) {
3939 * Lock specific tables
3941 * @param array $read of tables to lock for read access
3942 * @param array $write of tables to lock for write access
3943 * @param string $method name of caller
3944 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3948 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3953 * Unlock specific tables
3955 * @param string $method the caller
3959 public function unlockTables( $method ) {
3965 * @param $tableName string
3966 * @param $fName string
3967 * @return bool|ResultWrapper
3970 public function dropTable( $tableName, $fName = __METHOD__
) {
3971 if ( !$this->tableExists( $tableName, $fName ) ) {
3974 $sql = "DROP TABLE " . $this->tableName( $tableName );
3975 if ( $this->cascadingDeletes() ) {
3978 return $this->query( $sql, $fName );
3982 * Get search engine class. All subclasses of this need to implement this
3983 * if they wish to use searching.
3987 public function getSearchEngine() {
3988 return 'SearchEngineDummy';
3992 * Find out when 'infinity' is. Most DBMSes support this. This is a special
3993 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
3994 * because "i" sorts after all numbers.
3998 public function getInfinity() {
4003 * Encode an expiry time into the DBMS dependent format
4005 * @param string $expiry timestamp for expiry, or the 'infinity' string
4008 public function encodeExpiry( $expiry ) {
4009 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4010 ?
$this->getInfinity()
4011 : $this->timestamp( $expiry );
4015 * Decode an expiry time into a DBMS independent format
4017 * @param string $expiry DB timestamp field value for expiry
4018 * @param $format integer: TS_* constant, defaults to TS_MW
4021 public function decodeExpiry( $expiry, $format = TS_MW
) {
4022 return ( $expiry == '' ||
$expiry == $this->getInfinity() )
4024 : wfTimestamp( $format, $expiry );
4028 * Allow or deny "big selects" for this session only. This is done by setting
4029 * the sql_big_selects session variable.
4031 * This is a MySQL-specific feature.
4033 * @param $value Mixed: true for allow, false for deny, or "default" to
4034 * restore the initial value
4036 public function setBigSelects( $value = true ) {
4043 public function __toString() {
4044 return (string)$this->mConn
;
4048 * Run a few simple sanity checks
4050 public function __destruct() {
4051 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
4052 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4054 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
4056 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
4057 $callers[] = $callbackInfo[1];
4060 $callers = implode( ', ', $callers );
4061 trigger_error( "DB transaction callbacks still pending (from $callers)." );