c54c309bf4f414aaf7aa645ebe6bf227cac06bc8
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(),
794 $dbType = strtolower( $dbType );
795 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
796 $possibleDrivers = $canonicalDBTypes[$dbType];
797 if ( !empty( $p['driver'] ) ) {
798 if ( in_array( $p['driver'], $possibleDrivers ) ) {
799 $driver = $p['driver'];
801 throw new MWException( __METHOD__
.
802 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
805 foreach ( $possibleDrivers as $posDriver ) {
806 if ( extension_loaded( $posDriver ) ) {
807 $driver = $posDriver;
815 if ( $driver === false ) {
816 throw new MWException( __METHOD__
.
817 " no viable database extension found for type '$dbType'" );
820 $class = 'Database' . ucfirst( $driver );
821 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
823 'host' => isset( $p['host'] ) ?
$p['host'] : false,
824 'user' => isset( $p['user'] ) ?
$p['user'] : false,
825 'password' => isset( $p['password'] ) ?
$p['password'] : false,
826 'dbname' => isset( $p['dbname'] ) ?
$p['dbname'] : false,
827 'flags' => isset( $p['flags'] ) ?
$p['flags'] : 0,
828 'tablePrefix' => isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global',
829 'foreign' => isset( $p['foreign'] ) ?
$p['foreign'] : false
831 return new $class( $params );
837 protected function installErrorHandler() {
838 $this->mPHPError
= false;
839 $this->htmlErrors
= ini_set( 'html_errors', '0' );
840 set_error_handler( array( $this, 'connectionErrorHandler' ) );
844 * @return bool|string
846 protected function restoreErrorHandler() {
847 restore_error_handler();
848 if ( $this->htmlErrors
!== false ) {
849 ini_set( 'html_errors', $this->htmlErrors
);
851 if ( $this->mPHPError
) {
852 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
853 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
865 public function connectionErrorHandler( $errno, $errstr ) {
866 $this->mPHPError
= $errstr;
870 * Closes a database connection.
871 * if it is open : commits any open transactions
873 * @throws MWException
874 * @return Bool operation success. true if already closed.
876 public function close() {
877 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
878 throw new MWException( "Transaction idle callbacks still pending." );
880 $this->mOpened
= false;
881 if ( $this->mConn
) {
882 if ( $this->trxLevel() ) {
883 if ( !$this->mTrxAutomatic
) {
884 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
885 " performing implicit commit before closing connection!" );
888 $this->commit( __METHOD__
, 'flush' );
891 $ret = $this->closeConnection();
892 $this->mConn
= false;
900 * Closes underlying database connection
902 * @return bool: Whether connection was closed successfully
904 abstract protected function closeConnection();
907 * @param string $error fallback error message, used if none is given by DB
908 * @throws DBConnectionError
910 function reportConnectionError( $error = 'Unknown error' ) {
911 $myError = $this->lastError();
917 throw new DBConnectionError( $this, $error );
921 * The DBMS-dependent part of query()
923 * @param $sql String: SQL query.
924 * @return ResultWrapper Result object to feed to fetchObject, fetchRow, ...; or false on failure
926 abstract protected function doQuery( $sql );
929 * Determine whether a query writes to the DB.
930 * Should return true if unsure.
936 public function isWriteQuery( $sql ) {
937 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
941 * Run an SQL query and return the result. Normally throws a DBQueryError
942 * on failure. If errors are ignored, returns false instead.
944 * In new code, the query wrappers select(), insert(), update(), delete(),
945 * etc. should be used where possible, since they give much better DBMS
946 * independence and automatically quote or validate user input in a variety
947 * of contexts. This function is generally only useful for queries which are
948 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
951 * However, the query wrappers themselves should call this function.
953 * @param $sql String: SQL query
954 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
955 * comment (you can use __METHOD__ or add some extra info)
956 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
957 * maybe best to catch the exception instead?
958 * @throws MWException
959 * @return boolean|ResultWrapper. true for a successful write query, ResultWrapper object
960 * for a successful read query, or false on failure if $tempIgnore set
962 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
963 global $wgUser, $wgDebugDBTransactions;
965 $this->mLastQuery
= $sql;
966 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
967 # Set a flag indicating that writes have been done
968 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
969 $this->mDoneWrites
= true;
972 # Add a comment for easy SHOW PROCESSLIST interpretation
973 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
974 $userName = $wgUser->getName();
975 if ( mb_strlen( $userName ) > 15 ) {
976 $userName = mb_substr( $userName, 0, 15 ) . '...';
978 $userName = str_replace( '/', '', $userName );
983 // Add trace comment to the begin of the sql string, right after the operator.
984 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
985 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
987 # If DBO_TRX is set, start a transaction
988 if ( ( $this->mFlags
& DBO_TRX
) && !$this->mTrxLevel
&&
989 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' )
991 # Avoid establishing transactions for SHOW and SET statements too -
992 # that would delay transaction initializations to once connection
993 # is really used by application
994 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
995 if ( strpos( $sqlstart, "SHOW " ) !== 0 && strpos( $sqlstart, "SET " ) !== 0 ) {
996 if ( $wgDebugDBTransactions ) {
997 wfDebug( "Implicit transaction start.\n" );
999 $this->begin( __METHOD__
. " ($fname)" );
1000 $this->mTrxAutomatic
= true;
1004 # Keep track of whether the transaction has write queries pending
1005 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $this->isWriteQuery( $sql ) ) {
1006 $this->mTrxDoneWrites
= true;
1007 Profiler
::instance()->transactionWritingIn( $this->mServer
, $this->mDBname
);
1010 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1011 if ( !Profiler
::instance()->isStub() ) {
1012 # generalizeSQL will probably cut down the query to reasonable
1013 # logging size most of the time. The substr is really just a sanity check.
1015 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1016 $totalProf = 'DatabaseBase::query-master';
1018 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1019 $totalProf = 'DatabaseBase::query';
1021 wfProfileIn( $totalProf );
1022 wfProfileIn( $queryProf );
1025 if ( $this->debug() ) {
1029 $sqlx = substr( $commentedSql, 0, 500 );
1030 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1032 $master = $isMaster ?
'master' : 'slave';
1033 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1036 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
1038 # Do the query and handle errors
1039 $ret = $this->doQuery( $commentedSql );
1041 MWDebug
::queryTime( $queryId );
1043 # Try reconnecting if the connection was lost
1044 if ( false === $ret && $this->wasErrorReissuable() ) {
1045 # Transaction is gone, like it or not
1046 $hadTrx = $this->mTrxLevel
; // possible lost transaction
1047 wfDebug( "Connection lost, reconnecting...\n" );
1048 $this->mTrxLevel
= 0;
1049 wfDebug( "Connection lost, reconnecting...\n" );
1051 if ( $this->ping() ) {
1052 wfDebug( "Reconnected\n" );
1053 $sqlx = substr( $commentedSql, 0, 500 );
1054 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1055 global $wgRequestTime;
1056 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
1057 if ( $elapsed < 300 ) {
1058 # Not a database error to lose a transaction after a minute or two
1059 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
1062 # Should be safe to silently retry
1063 $ret = $this->doQuery( $commentedSql );
1066 wfDebug( "Failed\n" );
1070 if ( false === $ret ) {
1071 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1074 if ( !Profiler
::instance()->isStub() ) {
1075 wfProfileOut( $queryProf );
1076 wfProfileOut( $totalProf );
1079 return $this->resultObject( $ret );
1083 * Report a query error. Log the error, and if neither the object ignore
1084 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1086 * @param $error String
1087 * @param $errno Integer
1088 * @param $sql String
1089 * @param $fname String
1090 * @param $tempIgnore Boolean
1091 * @throws DBQueryError
1093 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1094 # Ignore errors during error handling to avoid infinite recursion
1095 $ignore = $this->ignoreErrors( true );
1096 ++
$this->mErrorCount
;
1098 if ( $ignore ||
$tempIgnore ) {
1099 wfDebug( "SQL ERROR (ignored): $error\n" );
1100 $this->ignoreErrors( $ignore );
1102 $sql1line = str_replace( "\n", "\\n", $sql );
1103 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
1104 wfDebug( "SQL ERROR: " . $error . "\n" );
1105 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1110 * Intended to be compatible with the PEAR::DB wrapper functions.
1111 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1113 * ? = scalar value, quoted as necessary
1114 * ! = raw SQL bit (a function for instance)
1115 * & = filename; reads the file and inserts as a blob
1116 * (we don't use this though...)
1118 * @param $sql string
1119 * @param $func string
1123 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1124 /* MySQL doesn't support prepared statements (yet), so just
1125 pack up the query for reference. We'll manually replace
1127 return array( 'query' => $sql, 'func' => $func );
1131 * Free a prepared query, generated by prepare().
1134 protected function freePrepared( $prepared ) {
1135 /* No-op by default */
1139 * Execute a prepared query with the various arguments
1140 * @param string $prepared the prepared sql
1141 * @param $args Mixed: Either an array here, or put scalars as varargs
1143 * @return ResultWrapper
1145 public function execute( $prepared, $args = null ) {
1146 if ( !is_array( $args ) ) {
1148 $args = func_get_args();
1149 array_shift( $args );
1152 $sql = $this->fillPrepared( $prepared['query'], $args );
1154 return $this->query( $sql, $prepared['func'] );
1158 * For faking prepared SQL statements on DBs that don't support it directly.
1160 * @param string $preparedQuery a 'preparable' SQL statement
1161 * @param array $args of arguments to fill it with
1162 * @return string executable SQL
1164 public function fillPrepared( $preparedQuery, $args ) {
1166 $this->preparedArgs
=& $args;
1168 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1169 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1173 * preg_callback func for fillPrepared()
1174 * The arguments should be in $this->preparedArgs and must not be touched
1175 * while we're doing this.
1177 * @param $matches Array
1178 * @throws DBUnexpectedError
1181 protected function fillPreparedArg( $matches ) {
1182 switch ( $matches[1] ) {
1191 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1193 switch ( $matches[1] ) {
1195 return $this->addQuotes( $arg );
1199 # return $this->addQuotes( file_get_contents( $arg ) );
1200 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
1202 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
1207 * Free a result object returned by query() or select(). It's usually not
1208 * necessary to call this, just use unset() or let the variable holding
1209 * the result object go out of scope.
1211 * @param $res Mixed: A SQL result
1213 public function freeResult( $res ) {
1217 * A SELECT wrapper which returns a single field from a single result row.
1219 * Usually throws a DBQueryError on failure. If errors are explicitly
1220 * ignored, returns false on failure.
1222 * If no result rows are returned from the query, false is returned.
1224 * @param string|array $table Table name. See DatabaseBase::select() for details.
1225 * @param string $var The field name to select. This must be a valid SQL
1226 * fragment: do not use unvalidated user input.
1227 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1228 * @param string $fname The function name of the caller.
1229 * @param string|array $options The query options. See DatabaseBase::select() for details.
1231 * @return bool|mixed The value from the field, or false on failure.
1233 public function selectField( $table, $var, $cond = '', $fname = __METHOD__
,
1236 if ( !is_array( $options ) ) {
1237 $options = array( $options );
1240 $options['LIMIT'] = 1;
1242 $res = $this->select( $table, $var, $cond, $fname, $options );
1244 if ( $res === false ||
!$this->numRows( $res ) ) {
1248 $row = $this->fetchRow( $res );
1250 if ( $row !== false ) {
1251 return reset( $row );
1258 * Returns an optional USE INDEX clause to go after the table, and a
1259 * string to go at the end of the query.
1261 * @param array $options associative array of options to be turned into
1262 * an SQL query, valid keys are listed in the function.
1264 * @see DatabaseBase::select()
1266 public function makeSelectOptions( $options ) {
1267 $preLimitTail = $postLimitTail = '';
1270 $noKeyOptions = array();
1272 foreach ( $options as $key => $option ) {
1273 if ( is_numeric( $key ) ) {
1274 $noKeyOptions[$option] = true;
1278 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1280 $preLimitTail .= $this->makeOrderBy( $options );
1282 // if (isset($options['LIMIT'])) {
1283 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1284 // isset($options['OFFSET']) ? $options['OFFSET']
1288 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1289 $postLimitTail .= ' FOR UPDATE';
1292 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1293 $postLimitTail .= ' LOCK IN SHARE MODE';
1296 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1297 $startOpts .= 'DISTINCT';
1300 # Various MySQL extensions
1301 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1302 $startOpts .= ' /*! STRAIGHT_JOIN */';
1305 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1306 $startOpts .= ' HIGH_PRIORITY';
1309 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1310 $startOpts .= ' SQL_BIG_RESULT';
1313 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1314 $startOpts .= ' SQL_BUFFER_RESULT';
1317 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1318 $startOpts .= ' SQL_SMALL_RESULT';
1321 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1322 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1325 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1326 $startOpts .= ' SQL_CACHE';
1329 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1330 $startOpts .= ' SQL_NO_CACHE';
1333 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1334 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1339 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1343 * Returns an optional GROUP BY with an optional HAVING
1345 * @param array $options associative array of options
1347 * @see DatabaseBase::select()
1350 public function makeGroupByWithHaving( $options ) {
1352 if ( isset( $options['GROUP BY'] ) ) {
1353 $gb = is_array( $options['GROUP BY'] )
1354 ?
implode( ',', $options['GROUP BY'] )
1355 : $options['GROUP BY'];
1356 $sql .= ' GROUP BY ' . $gb;
1358 if ( isset( $options['HAVING'] ) ) {
1359 $having = is_array( $options['HAVING'] )
1360 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1361 : $options['HAVING'];
1362 $sql .= ' HAVING ' . $having;
1368 * Returns an optional ORDER BY
1370 * @param array $options associative array of options
1372 * @see DatabaseBase::select()
1375 public function makeOrderBy( $options ) {
1376 if ( isset( $options['ORDER BY'] ) ) {
1377 $ob = is_array( $options['ORDER BY'] )
1378 ?
implode( ',', $options['ORDER BY'] )
1379 : $options['ORDER BY'];
1380 return ' ORDER BY ' . $ob;
1386 * Execute a SELECT query constructed using the various parameters provided.
1387 * See below for full details of the parameters.
1389 * @param string|array $table Table name
1390 * @param string|array $vars Field names
1391 * @param string|array $conds Conditions
1392 * @param string $fname Caller function name
1393 * @param array $options Query options
1394 * @param $join_conds Array Join conditions
1396 * @param $table string|array
1398 * May be either an array of table names, or a single string holding a table
1399 * name. If an array is given, table aliases can be specified, for example:
1401 * array( 'a' => 'user' )
1403 * This includes the user table in the query, with the alias "a" available
1404 * for use in field names (e.g. a.user_name).
1406 * All of the table names given here are automatically run through
1407 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1408 * added, and various other table name mappings to be performed.
1411 * @param $vars string|array
1413 * May be either a field name or an array of field names. The field names
1414 * can be complete fragments of SQL, for direct inclusion into the SELECT
1415 * query. If an array is given, field aliases can be specified, for example:
1417 * array( 'maxrev' => 'MAX(rev_id)' )
1419 * This includes an expression with the alias "maxrev" in the query.
1421 * If an expression is given, care must be taken to ensure that it is
1425 * @param $conds string|array
1427 * May be either a string containing a single condition, or an array of
1428 * conditions. If an array is given, the conditions constructed from each
1429 * element are combined with AND.
1431 * Array elements may take one of two forms:
1433 * - Elements with a numeric key are interpreted as raw SQL fragments.
1434 * - Elements with a string key are interpreted as equality conditions,
1435 * where the key is the field name.
1436 * - If the value of such an array element is a scalar (such as a
1437 * string), it will be treated as data and thus quoted appropriately.
1438 * If it is null, an IS NULL clause will be added.
1439 * - If the value is an array, an IN(...) clause will be constructed,
1440 * such that the field name may match any of the elements in the
1441 * array. The elements of the array will be quoted.
1443 * Note that expressions are often DBMS-dependent in their syntax.
1444 * DBMS-independent wrappers are provided for constructing several types of
1445 * expression commonly used in condition queries. See:
1446 * - DatabaseBase::buildLike()
1447 * - DatabaseBase::conditional()
1450 * @param $options string|array
1452 * Optional: Array of query options. Boolean options are specified by
1453 * including them in the array as a string value with a numeric key, for
1456 * array( 'FOR UPDATE' )
1458 * The supported options are:
1460 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1461 * with LIMIT can theoretically be used for paging through a result set,
1462 * but this is discouraged in MediaWiki for performance reasons.
1464 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1465 * and then the first rows are taken until the limit is reached. LIMIT
1466 * is applied to a result set after OFFSET.
1468 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1469 * changed until the next COMMIT.
1471 * - DISTINCT: Boolean: return only unique result rows.
1473 * - GROUP BY: May be either an SQL fragment string naming a field or
1474 * expression to group by, or an array of such SQL fragments.
1476 * - HAVING: May be either an string containing a HAVING clause or an array of
1477 * conditions building the HAVING clause. If an array is given, the conditions
1478 * constructed from each element are combined with AND.
1480 * - ORDER BY: May be either an SQL fragment giving a field name or
1481 * expression to order by, or an array of such SQL fragments.
1483 * - USE INDEX: This may be either a string giving the index name to use
1484 * for the query, or an array. If it is an associative array, each key
1485 * gives the table name (or alias), each value gives the index name to
1486 * use for that table. All strings are SQL fragments and so should be
1487 * validated by the caller.
1489 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1490 * instead of SELECT.
1492 * And also the following boolean MySQL extensions, see the MySQL manual
1493 * for documentation:
1495 * - LOCK IN SHARE MODE
1499 * - SQL_BUFFER_RESULT
1500 * - SQL_SMALL_RESULT
1501 * - SQL_CALC_FOUND_ROWS
1506 * @param $join_conds string|array
1508 * Optional associative array of table-specific join conditions. In the
1509 * most common case, this is unnecessary, since the join condition can be
1510 * in $conds. However, it is useful for doing a LEFT JOIN.
1512 * The key of the array contains the table name or alias. The value is an
1513 * array with two elements, numbered 0 and 1. The first gives the type of
1514 * join, the second is an SQL fragment giving the join condition for that
1515 * table. For example:
1517 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1519 * @return ResultWrapper. If the query returned no rows, a ResultWrapper
1520 * with no rows in it will be returned. If there was a query error, a
1521 * DBQueryError exception will be thrown, except if the "ignore errors"
1522 * option was set, in which case false will be returned.
1524 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1525 $options = array(), $join_conds = array() ) {
1526 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1528 return $this->query( $sql, $fname );
1532 * The equivalent of DatabaseBase::select() except that the constructed SQL
1533 * is returned, instead of being immediately executed. This can be useful for
1534 * doing UNION queries, where the SQL text of each query is needed. In general,
1535 * however, callers outside of Database classes should just use select().
1537 * @param string|array $table Table name
1538 * @param string|array $vars Field names
1539 * @param string|array $conds Conditions
1540 * @param string $fname Caller function name
1541 * @param string|array $options Query options
1542 * @param $join_conds string|array Join conditions
1544 * @return string SQL query string.
1545 * @see DatabaseBase::select()
1547 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1548 $options = array(), $join_conds = array() )
1550 if ( is_array( $vars ) ) {
1551 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1554 $options = (array)$options;
1555 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1556 ?
$options['USE INDEX']
1559 if ( is_array( $table ) ) {
1561 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1562 } elseif ( $table != '' ) {
1563 if ( $table[0] == ' ' ) {
1564 $from = ' FROM ' . $table;
1567 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1573 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1574 $this->makeSelectOptions( $options );
1576 if ( !empty( $conds ) ) {
1577 if ( is_array( $conds ) ) {
1578 $conds = $this->makeList( $conds, LIST_AND
);
1580 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1582 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1585 if ( isset( $options['LIMIT'] ) ) {
1586 $sql = $this->limitResult( $sql, $options['LIMIT'],
1587 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1589 $sql = "$sql $postLimitTail";
1591 if ( isset( $options['EXPLAIN'] ) ) {
1592 $sql = 'EXPLAIN ' . $sql;
1599 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1600 * that a single row object is returned. If the query returns no rows,
1601 * false is returned.
1603 * @param string|array $table Table name
1604 * @param string|array $vars Field names
1605 * @param array $conds Conditions
1606 * @param string $fname Caller function name
1607 * @param string|array $options Query options
1608 * @param $join_conds array|string Join conditions
1610 * @return object|bool
1612 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1613 $options = array(), $join_conds = array() )
1615 $options = (array)$options;
1616 $options['LIMIT'] = 1;
1617 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1619 if ( $res === false ) {
1623 if ( !$this->numRows( $res ) ) {
1627 $obj = $this->fetchObject( $res );
1633 * Estimate rows in dataset.
1635 * MySQL allows you to estimate the number of rows that would be returned
1636 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1637 * index cardinality statistics, and is notoriously inaccurate, especially
1638 * when large numbers of rows have recently been added or deleted.
1640 * For DBMSs that don't support fast result size estimation, this function
1641 * will actually perform the SELECT COUNT(*).
1643 * Takes the same arguments as DatabaseBase::select().
1645 * @param string $table table name
1646 * @param array|string $vars : unused
1647 * @param array|string $conds : filters on the table
1648 * @param string $fname function name for profiling
1649 * @param array $options options for select
1650 * @return Integer: row count
1652 public function estimateRowCount( $table, $vars = '*', $conds = '',
1653 $fname = __METHOD__
, $options = array() )
1656 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1659 $row = $this->fetchRow( $res );
1660 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1667 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1668 * It's only slightly flawed. Don't use for anything important.
1670 * @param string $sql A SQL Query
1674 static function generalizeSQL( $sql ) {
1675 # This does the same as the regexp below would do, but in such a way
1676 # as to avoid crashing php on some large strings.
1677 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1679 $sql = str_replace( "\\\\", '', $sql );
1680 $sql = str_replace( "\\'", '', $sql );
1681 $sql = str_replace( "\\\"", '', $sql );
1682 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1683 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1685 # All newlines, tabs, etc replaced by single space
1686 $sql = preg_replace( '/\s+/', ' ', $sql );
1689 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1690 $sql = preg_replace( '/-?\d+/s', 'N', $sql );
1696 * Determines whether a field exists in a table
1698 * @param string $table table name
1699 * @param string $field filed to check on that table
1700 * @param string $fname calling function name (optional)
1701 * @return Boolean: whether $table has filed $field
1703 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1704 $info = $this->fieldInfo( $table, $field );
1710 * Determines whether an index exists
1711 * Usually throws a DBQueryError on failure
1712 * If errors are explicitly ignored, returns NULL on failure
1716 * @param $fname string
1720 public function indexExists( $table, $index, $fname = __METHOD__
) {
1721 if ( !$this->tableExists( $table ) ) {
1725 $info = $this->indexInfo( $table, $index, $fname );
1726 if ( is_null( $info ) ) {
1729 return $info !== false;
1734 * Query whether a given table exists
1736 * @param $table string
1737 * @param $fname string
1741 public function tableExists( $table, $fname = __METHOD__
) {
1742 $table = $this->tableName( $table );
1743 $old = $this->ignoreErrors( true );
1744 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1745 $this->ignoreErrors( $old );
1751 * mysql_field_type() wrapper
1756 public function fieldType( $res, $index ) {
1757 if ( $res instanceof ResultWrapper
) {
1758 $res = $res->result
;
1761 return mysql_field_type( $res, $index );
1765 * Determines if a given index is unique
1767 * @param $table string
1768 * @param $index string
1772 public function indexUnique( $table, $index ) {
1773 $indexInfo = $this->indexInfo( $table, $index );
1775 if ( !$indexInfo ) {
1779 return !$indexInfo[0]->Non_unique
;
1783 * Helper for DatabaseBase::insert().
1785 * @param $options array
1788 protected function makeInsertOptions( $options ) {
1789 return implode( ' ', $options );
1793 * INSERT wrapper, inserts an array into a table.
1797 * - A single associative array. The array keys are the field names, and
1798 * the values are the values to insert. The values are treated as data
1799 * and will be quoted appropriately. If NULL is inserted, this will be
1800 * converted to a database NULL.
1801 * - An array with numeric keys, holding a list of associative arrays.
1802 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1803 * each subarray must be identical to each other, and in the same order.
1805 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1808 * $options is an array of options, with boolean options encoded as values
1809 * with numeric keys, in the same style as $options in
1810 * DatabaseBase::select(). Supported options are:
1812 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1813 * any rows which cause duplicate key errors are not inserted. It's
1814 * possible to determine how many rows were successfully inserted using
1815 * DatabaseBase::affectedRows().
1817 * @param $table String Table name. This will be passed through
1818 * DatabaseBase::tableName().
1819 * @param $a Array of rows to insert
1820 * @param $fname String Calling function name (use __METHOD__) for logs/profiling
1821 * @param array $options of options
1825 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
1826 # No rows to insert, easy just return now
1827 if ( !count( $a ) ) {
1831 $table = $this->tableName( $table );
1833 if ( !is_array( $options ) ) {
1834 $options = array( $options );
1838 if ( isset( $options['fileHandle'] ) ) {
1839 $fh = $options['fileHandle'];
1841 $options = $this->makeInsertOptions( $options );
1843 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1845 $keys = array_keys( $a[0] );
1848 $keys = array_keys( $a );
1851 $sql = 'INSERT ' . $options .
1852 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1856 foreach ( $a as $row ) {
1862 $sql .= '(' . $this->makeList( $row ) . ')';
1865 $sql .= '(' . $this->makeList( $a ) . ')';
1868 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1870 } elseif ( $fh !== null ) {
1874 return (bool)$this->query( $sql, $fname );
1878 * Make UPDATE options for the DatabaseBase::update function
1880 * @param array $options The options passed to DatabaseBase::update
1883 protected function makeUpdateOptions( $options ) {
1884 if ( !is_array( $options ) ) {
1885 $options = array( $options );
1890 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1891 $opts[] = $this->lowPriorityOption();
1894 if ( in_array( 'IGNORE', $options ) ) {
1898 return implode( ' ', $opts );
1902 * UPDATE wrapper. Takes a condition array and a SET array.
1904 * @param $table String name of the table to UPDATE. This will be passed through
1905 * DatabaseBase::tableName().
1907 * @param array $values An array of values to SET. For each array element,
1908 * the key gives the field name, and the value gives the data
1909 * to set that field to. The data will be quoted by
1910 * DatabaseBase::addQuotes().
1912 * @param $conds Array: An array of conditions (WHERE). See
1913 * DatabaseBase::select() for the details of the format of
1914 * condition arrays. Use '*' to update all rows.
1916 * @param $fname String: The function name of the caller (from __METHOD__),
1917 * for logging and profiling.
1919 * @param array $options An array of UPDATE options, can be:
1920 * - IGNORE: Ignore unique key conflicts
1921 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1924 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
1925 $table = $this->tableName( $table );
1926 $opts = $this->makeUpdateOptions( $options );
1927 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1929 if ( $conds !== array() && $conds !== '*' ) {
1930 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1933 return $this->query( $sql, $fname );
1937 * Makes an encoded list of strings from an array
1938 * @param array $a containing the data
1939 * @param int $mode Constant
1940 * - LIST_COMMA: comma separated, no field names
1941 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
1942 * the documentation for $conds in DatabaseBase::select().
1943 * - LIST_OR: ORed WHERE clause (without the WHERE)
1944 * - LIST_SET: comma separated with field names, like a SET clause
1945 * - LIST_NAMES: comma separated field names
1947 * @throws MWException|DBUnexpectedError
1950 public function makeList( $a, $mode = LIST_COMMA
) {
1951 if ( !is_array( $a ) ) {
1952 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1958 foreach ( $a as $field => $value ) {
1960 if ( $mode == LIST_AND
) {
1962 } elseif ( $mode == LIST_OR
) {
1971 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1972 $list .= "($value)";
1973 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1975 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1976 if ( count( $value ) == 0 ) {
1977 throw new MWException( __METHOD__
. ": empty input for field $field" );
1978 } elseif ( count( $value ) == 1 ) {
1979 // Special-case single values, as IN isn't terribly efficient
1980 // Don't necessarily assume the single key is 0; we don't
1981 // enforce linear numeric ordering on other arrays here.
1982 $value = array_values( $value );
1983 $list .= $field . " = " . $this->addQuotes( $value[0] );
1985 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1987 } elseif ( $value === null ) {
1988 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1989 $list .= "$field IS ";
1990 } elseif ( $mode == LIST_SET
) {
1991 $list .= "$field = ";
1995 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1996 $list .= "$field = ";
1998 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
2006 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2007 * The keys on each level may be either integers or strings.
2009 * @param array $data organized as 2-d
2010 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2011 * @param string $baseKey field name to match the base-level keys to (eg 'pl_namespace')
2012 * @param string $subKey field name to match the sub-level keys to (eg 'pl_title')
2013 * @return Mixed: string SQL fragment, or false if no items in array.
2015 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2018 foreach ( $data as $base => $sub ) {
2019 if ( count( $sub ) ) {
2020 $conds[] = $this->makeList(
2021 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2027 return $this->makeList( $conds, LIST_OR
);
2029 // Nothing to search for...
2035 * Return aggregated value alias
2038 * @param $valuename string
2042 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2050 public function bitNot( $field ) {
2056 * @param $fieldRight
2059 public function bitAnd( $fieldLeft, $fieldRight ) {
2060 return "($fieldLeft & $fieldRight)";
2065 * @param $fieldRight
2068 public function bitOr( $fieldLeft, $fieldRight ) {
2069 return "($fieldLeft | $fieldRight)";
2073 * Build a concatenation list to feed into a SQL query
2074 * @param array $stringList list of raw SQL expressions; caller is responsible for any quoting
2077 public function buildConcat( $stringList ) {
2078 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2082 * Change the current database
2084 * @todo Explain what exactly will fail if this is not overridden.
2088 * @return bool Success or failure
2090 public function selectDB( $db ) {
2091 # Stub. Shouldn't cause serious problems if it's not overridden, but
2092 # if your database engine supports a concept similar to MySQL's
2093 # databases you may as well.
2094 $this->mDBname
= $db;
2099 * Get the current DB name
2101 public function getDBname() {
2102 return $this->mDBname
;
2106 * Get the server hostname or IP address
2108 public function getServer() {
2109 return $this->mServer
;
2113 * Format a table name ready for use in constructing an SQL query
2115 * This does two important things: it quotes the table names to clean them up,
2116 * and it adds a table prefix if only given a table name with no quotes.
2118 * All functions of this object which require a table name call this function
2119 * themselves. Pass the canonical name to such functions. This is only needed
2120 * when calling query() directly.
2122 * @param string $name database table name
2123 * @param string $format One of:
2124 * quoted - Automatically pass the table name through addIdentifierQuotes()
2125 * so that it can be used in a query.
2126 * raw - Do not add identifier quotes to the table name
2127 * @return String: full database name
2129 public function tableName( $name, $format = 'quoted' ) {
2130 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
2131 # Skip the entire process when we have a string quoted on both ends.
2132 # Note that we check the end so that we will still quote any use of
2133 # use of `database`.table. But won't break things if someone wants
2134 # to query a database table with a dot in the name.
2135 if ( $this->isQuotedIdentifier( $name ) ) {
2139 # Lets test for any bits of text that should never show up in a table
2140 # name. Basically anything like JOIN or ON which are actually part of
2141 # SQL queries, but may end up inside of the table value to combine
2142 # sql. Such as how the API is doing.
2143 # Note that we use a whitespace test rather than a \b test to avoid
2144 # any remote case where a word like on may be inside of a table name
2145 # surrounded by symbols which may be considered word breaks.
2146 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2150 # Split database and table into proper variables.
2151 # We reverse the explode so that database.table and table both output
2152 # the correct table.
2153 $dbDetails = explode( '.', $name, 2 );
2154 if ( count( $dbDetails ) == 2 ) {
2155 list( $database, $table ) = $dbDetails;
2156 # We don't want any prefix added in this case
2159 list( $table ) = $dbDetails;
2160 if ( $wgSharedDB !== null # We have a shared database
2161 && $this->mForeign
== false # We're not working on a foreign database
2162 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
2163 && in_array( $table, $wgSharedTables ) # A shared table is selected
2165 $database = $wgSharedDB;
2166 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
2169 $prefix = $this->mTablePrefix
; # Default prefix
2173 # Quote $table and apply the prefix if not quoted.
2174 $tableName = "{$prefix}{$table}";
2175 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) ) {
2176 $tableName = $this->addIdentifierQuotes( $tableName );
2179 # Quote $database and merge it with the table name if needed
2180 if ( $database !== null ) {
2181 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2182 $database = $this->addIdentifierQuotes( $database );
2184 $tableName = $database . '.' . $tableName;
2191 * Fetch a number of table names into an array
2192 * This is handy when you need to construct SQL for joins
2195 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2196 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2197 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2201 public function tableNames() {
2202 $inArray = func_get_args();
2205 foreach ( $inArray as $name ) {
2206 $retVal[$name] = $this->tableName( $name );
2213 * Fetch a number of table names into an zero-indexed numerical array
2214 * This is handy when you need to construct SQL for joins
2217 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2218 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2219 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2223 public function tableNamesN() {
2224 $inArray = func_get_args();
2227 foreach ( $inArray as $name ) {
2228 $retVal[] = $this->tableName( $name );
2235 * Get an aliased table name
2236 * e.g. tableName AS newTableName
2238 * @param string $name Table name, see tableName()
2239 * @param string|bool $alias Alias (optional)
2240 * @return string SQL name for aliased table. Will not alias a table to its own name
2242 public function tableNameWithAlias( $name, $alias = false ) {
2243 if ( !$alias ||
$alias == $name ) {
2244 return $this->tableName( $name );
2246 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2251 * Gets an array of aliased table names
2253 * @param $tables array( [alias] => table )
2254 * @return array of strings, see tableNameWithAlias()
2256 public function tableNamesWithAlias( $tables ) {
2258 foreach ( $tables as $alias => $table ) {
2259 if ( is_numeric( $alias ) ) {
2262 $retval[] = $this->tableNameWithAlias( $table, $alias );
2268 * Get an aliased field name
2269 * e.g. fieldName AS newFieldName
2271 * @param string $name Field name
2272 * @param string|bool $alias Alias (optional)
2273 * @return string SQL name for aliased field. Will not alias a field to its own name
2275 public function fieldNameWithAlias( $name, $alias = false ) {
2276 if ( !$alias ||
(string)$alias === (string)$name ) {
2279 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2284 * Gets an array of aliased field names
2286 * @param $fields array( [alias] => field )
2287 * @return array of strings, see fieldNameWithAlias()
2289 public function fieldNamesWithAlias( $fields ) {
2291 foreach ( $fields as $alias => $field ) {
2292 if ( is_numeric( $alias ) ) {
2295 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2301 * Get the aliased table name clause for a FROM clause
2302 * which might have a JOIN and/or USE INDEX clause
2304 * @param array $tables ( [alias] => table )
2305 * @param $use_index array Same as for select()
2306 * @param $join_conds array Same as for select()
2309 protected function tableNamesWithUseIndexOrJOIN(
2310 $tables, $use_index = array(), $join_conds = array()
2314 $use_index = (array)$use_index;
2315 $join_conds = (array)$join_conds;
2317 foreach ( $tables as $alias => $table ) {
2318 if ( !is_string( $alias ) ) {
2319 // No alias? Set it equal to the table name
2322 // Is there a JOIN clause for this table?
2323 if ( isset( $join_conds[$alias] ) ) {
2324 list( $joinType, $conds ) = $join_conds[$alias];
2325 $tableClause = $joinType;
2326 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2327 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2328 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2330 $tableClause .= ' ' . $use;
2333 $on = $this->makeList( (array)$conds, LIST_AND
);
2335 $tableClause .= ' ON (' . $on . ')';
2338 $retJOIN[] = $tableClause;
2339 // Is there an INDEX clause for this table?
2340 } elseif ( isset( $use_index[$alias] ) ) {
2341 $tableClause = $this->tableNameWithAlias( $table, $alias );
2342 $tableClause .= ' ' . $this->useIndexClause(
2343 implode( ',', (array)$use_index[$alias] ) );
2345 $ret[] = $tableClause;
2347 $tableClause = $this->tableNameWithAlias( $table, $alias );
2349 $ret[] = $tableClause;
2353 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2354 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2355 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2357 // Compile our final table clause
2358 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2362 * Get the name of an index in a given table
2368 protected function indexName( $index ) {
2369 // Backwards-compatibility hack
2371 'ar_usertext_timestamp' => 'usertext_timestamp',
2372 'un_user_id' => 'user_id',
2373 'un_user_ip' => 'user_ip',
2376 if ( isset( $renamed[$index] ) ) {
2377 return $renamed[$index];
2384 * Adds quotes and backslashes.
2390 public function addQuotes( $s ) {
2391 if ( $s === null ) {
2394 # This will also quote numeric values. This should be harmless,
2395 # and protects against weird problems that occur when they really
2396 # _are_ strings such as article titles and string->number->string
2397 # conversion is not 1:1.
2398 return "'" . $this->strencode( $s ) . "'";
2403 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2404 * MySQL uses `backticks` while basically everything else uses double quotes.
2405 * Since MySQL is the odd one out here the double quotes are our generic
2406 * and we implement backticks in DatabaseMysql.
2412 public function addIdentifierQuotes( $s ) {
2413 return '"' . str_replace( '"', '""', $s ) . '"';
2417 * Returns if the given identifier looks quoted or not according to
2418 * the database convention for quoting identifiers .
2420 * @param $name string
2424 public function isQuotedIdentifier( $name ) {
2425 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2432 protected function escapeLikeInternal( $s ) {
2433 $s = str_replace( '\\', '\\\\', $s );
2434 $s = $this->strencode( $s );
2435 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
2441 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
2442 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
2443 * Alternatively, the function could be provided with an array of aforementioned parameters.
2445 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
2446 * for subpages of 'My page title'.
2447 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
2450 * @return String: fully built LIKE statement
2452 public function buildLike() {
2453 $params = func_get_args();
2455 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2456 $params = $params[0];
2461 foreach ( $params as $value ) {
2462 if ( $value instanceof LikeMatch
) {
2463 $s .= $value->toString();
2465 $s .= $this->escapeLikeInternal( $value );
2469 return " LIKE '" . $s . "' ";
2473 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2477 public function anyChar() {
2478 return new LikeMatch( '_' );
2482 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2486 public function anyString() {
2487 return new LikeMatch( '%' );
2491 * Returns an appropriately quoted sequence value for inserting a new row.
2492 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2493 * subclass will return an integer, and save the value for insertId()
2495 * Any implementation of this function should *not* involve reusing
2496 * sequence numbers created for rolled-back transactions.
2497 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2498 * @param $seqName string
2501 public function nextSequenceValue( $seqName ) {
2506 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2507 * is only needed because a) MySQL must be as efficient as possible due to
2508 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2509 * which index to pick. Anyway, other databases might have different
2510 * indexes on a given table. So don't bother overriding this unless you're
2515 public function useIndexClause( $index ) {
2520 * REPLACE query wrapper.
2522 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2523 * except that when there is a duplicate key error, the old row is deleted
2524 * and the new row is inserted in its place.
2526 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2527 * perform the delete, we need to know what the unique indexes are so that
2528 * we know how to find the conflicting rows.
2530 * It may be more efficient to leave off unique indexes which are unlikely
2531 * to collide. However if you do this, you run the risk of encountering
2532 * errors which wouldn't have occurred in MySQL.
2534 * @param string $table The table to replace the row(s) in.
2535 * @param array $rows Can be either a single row to insert, or multiple rows,
2536 * in the same format as for DatabaseBase::insert()
2537 * @param array $uniqueIndexes is an array of indexes. Each element may be either
2538 * a field name or an array of field names
2539 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2541 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2542 $quotedTable = $this->tableName( $table );
2544 if ( count( $rows ) == 0 ) {
2549 if ( !is_array( reset( $rows ) ) ) {
2550 $rows = array( $rows );
2553 foreach ( $rows as $row ) {
2554 # Delete rows which collide
2555 if ( $uniqueIndexes ) {
2556 $sql = "DELETE FROM $quotedTable WHERE ";
2558 foreach ( $uniqueIndexes as $index ) {
2565 if ( is_array( $index ) ) {
2567 foreach ( $index as $col ) {
2573 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2576 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2580 $this->query( $sql, $fname );
2583 # Now insert the row
2584 $this->insert( $table, $row, $fname );
2589 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2592 * @param string $table Table name
2593 * @param array $rows Rows to insert
2594 * @param string $fname Caller function name
2596 * @return ResultWrapper
2598 protected function nativeReplace( $table, $rows, $fname ) {
2599 $table = $this->tableName( $table );
2602 if ( !is_array( reset( $rows ) ) ) {
2603 $rows = array( $rows );
2606 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2609 foreach ( $rows as $row ) {
2616 $sql .= '(' . $this->makeList( $row ) . ')';
2619 return $this->query( $sql, $fname );
2623 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2625 * This updates any conflicting rows (according to the unique indexes) using
2626 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2628 * $rows may be either:
2629 * - A single associative array. The array keys are the field names, and
2630 * the values are the values to insert. The values are treated as data
2631 * and will be quoted appropriately. If NULL is inserted, this will be
2632 * converted to a database NULL.
2633 * - An array with numeric keys, holding a list of associative arrays.
2634 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2635 * each subarray must be identical to each other, and in the same order.
2637 * It may be more efficient to leave off unique indexes which are unlikely
2638 * to collide. However if you do this, you run the risk of encountering
2639 * errors which wouldn't have occurred in MySQL.
2641 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2644 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2645 * @param array $rows A single row or list of rows to insert
2646 * @param array $uniqueIndexes List of single field names or field name tuples
2647 * @param array $set An array of values to SET. For each array element,
2648 * the key gives the field name, and the value gives the data
2649 * to set that field to. The data will be quoted by
2650 * DatabaseBase::addQuotes().
2651 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2652 * @param array $options of options
2657 public function upsert(
2658 $table, array $rows, array $uniqueIndexes, array $set, $fname = __METHOD__
2660 if ( !count( $rows ) ) {
2661 return true; // nothing to do
2663 $rows = is_array( reset( $rows ) ) ?
$rows : array( $rows );
2665 if ( count( $uniqueIndexes ) ) {
2666 $clauses = array(); // list WHERE clauses that each identify a single row
2667 foreach ( $rows as $row ) {
2668 foreach ( $uniqueIndexes as $index ) {
2669 $index = is_array( $index ) ?
$index : array( $index ); // columns
2670 $rowKey = array(); // unique key to this row
2671 foreach ( $index as $column ) {
2672 $rowKey[$column] = $row[$column];
2674 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2677 $where = array( $this->makeList( $clauses, LIST_OR
) );
2682 $useTrx = !$this->mTrxLevel
;
2684 $this->begin( $fname );
2687 # Update any existing conflicting row(s)
2688 if ( $where !== false ) {
2689 $ok = $this->update( $table, $set, $where, $fname );
2693 # Now insert any non-conflicting row(s)
2694 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2695 } catch ( Exception
$e ) {
2697 $this->rollback( $fname );
2702 $this->commit( $fname );
2709 * DELETE where the condition is a join.
2711 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2712 * we use sub-selects
2714 * For safety, an empty $conds will not delete everything. If you want to
2715 * delete all rows where the join condition matches, set $conds='*'.
2717 * DO NOT put the join condition in $conds.
2719 * @param $delTable String: The table to delete from.
2720 * @param $joinTable String: The other table.
2721 * @param $delVar String: The variable to join on, in the first table.
2722 * @param $joinVar String: The variable to join on, in the second table.
2723 * @param $conds Array: Condition array of field names mapped to variables,
2724 * ANDed together in the WHERE clause
2725 * @param $fname String: Calling function name (use __METHOD__) for
2727 * @throws DBUnexpectedError
2729 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2730 $fname = __METHOD__
)
2733 throw new DBUnexpectedError( $this,
2734 'DatabaseBase::deleteJoin() called with empty $conds' );
2737 $delTable = $this->tableName( $delTable );
2738 $joinTable = $this->tableName( $joinTable );
2739 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2740 if ( $conds != '*' ) {
2741 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2745 $this->query( $sql, $fname );
2749 * Returns the size of a text field, or -1 for "unlimited"
2751 * @param $table string
2752 * @param $field string
2756 public function textFieldSize( $table, $field ) {
2757 $table = $this->tableName( $table );
2758 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2759 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2760 $row = $this->fetchObject( $res );
2764 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2774 * A string to insert into queries to show that they're low-priority, like
2775 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2776 * string and nothing bad should happen.
2778 * @return string Returns the text of the low priority option if it is
2779 * supported, or a blank string otherwise
2781 public function lowPriorityOption() {
2786 * DELETE query wrapper.
2788 * @param array $table Table name
2789 * @param string|array $conds of conditions. See $conds in DatabaseBase::select() for
2790 * the format. Use $conds == "*" to delete all rows
2791 * @param string $fname name of the calling function
2793 * @throws DBUnexpectedError
2794 * @return bool|ResultWrapper
2796 public function delete( $table, $conds, $fname = __METHOD__
) {
2798 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2801 $table = $this->tableName( $table );
2802 $sql = "DELETE FROM $table";
2804 if ( $conds != '*' ) {
2805 if ( is_array( $conds ) ) {
2806 $conds = $this->makeList( $conds, LIST_AND
);
2808 $sql .= ' WHERE ' . $conds;
2811 return $this->query( $sql, $fname );
2815 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2816 * into another table.
2818 * @param string $destTable The table name to insert into
2819 * @param string|array $srcTable May be either a table name, or an array of table names
2820 * to include in a join.
2822 * @param array $varMap must be an associative array of the form
2823 * array( 'dest1' => 'source1', ...). Source items may be literals
2824 * rather than field names, but strings should be quoted with
2825 * DatabaseBase::addQuotes()
2827 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
2828 * the details of the format of condition arrays. May be "*" to copy the
2831 * @param string $fname The function name of the caller, from __METHOD__
2833 * @param array $insertOptions Options for the INSERT part of the query, see
2834 * DatabaseBase::insert() for details.
2835 * @param array $selectOptions Options for the SELECT part of the query, see
2836 * DatabaseBase::select() for details.
2838 * @return ResultWrapper
2840 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2841 $fname = __METHOD__
,
2842 $insertOptions = array(), $selectOptions = array() )
2844 $destTable = $this->tableName( $destTable );
2846 if ( is_array( $insertOptions ) ) {
2847 $insertOptions = implode( ' ', $insertOptions );
2850 if ( !is_array( $selectOptions ) ) {
2851 $selectOptions = array( $selectOptions );
2854 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2856 if ( is_array( $srcTable ) ) {
2857 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2859 $srcTable = $this->tableName( $srcTable );
2862 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2863 " SELECT $startOpts " . implode( ',', $varMap ) .
2864 " FROM $srcTable $useIndex ";
2866 if ( $conds != '*' ) {
2867 if ( is_array( $conds ) ) {
2868 $conds = $this->makeList( $conds, LIST_AND
);
2870 $sql .= " WHERE $conds";
2873 $sql .= " $tailOpts";
2875 return $this->query( $sql, $fname );
2879 * Construct a LIMIT query with optional offset. This is used for query
2880 * pages. The SQL should be adjusted so that only the first $limit rows
2881 * are returned. If $offset is provided as well, then the first $offset
2882 * rows should be discarded, and the next $limit rows should be returned.
2883 * If the result of the query is not ordered, then the rows to be returned
2884 * are theoretically arbitrary.
2886 * $sql is expected to be a SELECT, if that makes a difference.
2888 * The version provided by default works in MySQL and SQLite. It will very
2889 * likely need to be overridden for most other DBMSes.
2891 * @param string $sql SQL query we will append the limit too
2892 * @param $limit Integer the SQL limit
2893 * @param $offset Integer|bool the SQL offset (default false)
2895 * @throws DBUnexpectedError
2898 public function limitResult( $sql, $limit, $offset = false ) {
2899 if ( !is_numeric( $limit ) ) {
2900 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2902 return "$sql LIMIT "
2903 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2908 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2909 * within the UNION construct.
2912 public function unionSupportsOrderAndLimit() {
2913 return true; // True for almost every DB supported
2917 * Construct a UNION query
2918 * This is used for providing overload point for other DB abstractions
2919 * not compatible with the MySQL syntax.
2920 * @param array $sqls SQL statements to combine
2921 * @param $all Boolean: use UNION ALL
2922 * @return String: SQL fragment
2924 public function unionQueries( $sqls, $all ) {
2925 $glue = $all ?
') UNION ALL (' : ') UNION (';
2926 return '(' . implode( $glue, $sqls ) . ')';
2930 * Returns an SQL expression for a simple conditional. This doesn't need
2931 * to be overridden unless CASE isn't supported in your DBMS.
2933 * @param string|array $cond SQL expression which will result in a boolean value
2934 * @param string $trueVal SQL expression to return if true
2935 * @param string $falseVal SQL expression to return if false
2936 * @return String: SQL fragment
2938 public function conditional( $cond, $trueVal, $falseVal ) {
2939 if ( is_array( $cond ) ) {
2940 $cond = $this->makeList( $cond, LIST_AND
);
2942 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2946 * Returns a comand for str_replace function in SQL query.
2947 * Uses REPLACE() in MySQL
2949 * @param string $orig column to modify
2950 * @param string $old column to seek
2951 * @param string $new column to replace with
2955 public function strreplace( $orig, $old, $new ) {
2956 return "REPLACE({$orig}, {$old}, {$new})";
2960 * Determines how long the server has been up
2965 public function getServerUptime() {
2970 * Determines if the last failure was due to a deadlock
2975 public function wasDeadlock() {
2980 * Determines if the last failure was due to a lock timeout
2985 public function wasLockTimeout() {
2990 * Determines if the last query error was something that should be dealt
2991 * with by pinging the connection and reissuing the query.
2996 public function wasErrorReissuable() {
3001 * Determines if the last failure was due to the database being read-only.
3006 public function wasReadOnlyError() {
3011 * Perform a deadlock-prone transaction.
3013 * This function invokes a callback function to perform a set of write
3014 * queries. If a deadlock occurs during the processing, the transaction
3015 * will be rolled back and the callback function will be called again.
3018 * $dbw->deadlockLoop( callback, ... );
3020 * Extra arguments are passed through to the specified callback function.
3022 * Returns whatever the callback function returned on its successful,
3023 * iteration, or false on error, for example if the retry limit was
3028 public function deadlockLoop() {
3029 $this->begin( __METHOD__
);
3030 $args = func_get_args();
3031 $function = array_shift( $args );
3032 $oldIgnore = $this->ignoreErrors( true );
3033 $tries = self
::DEADLOCK_TRIES
;
3035 if ( is_array( $function ) ) {
3036 $fname = $function[0];
3042 $retVal = call_user_func_array( $function, $args );
3043 $error = $this->lastError();
3044 $errno = $this->lastErrno();
3045 $sql = $this->lastQuery();
3048 if ( $this->wasDeadlock() ) {
3050 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3052 $this->reportQueryError( $error, $errno, $sql, $fname );
3055 } while ( $this->wasDeadlock() && --$tries > 0 );
3057 $this->ignoreErrors( $oldIgnore );
3059 if ( $tries <= 0 ) {
3060 $this->rollback( __METHOD__
);
3061 $this->reportQueryError( $error, $errno, $sql, $fname );
3064 $this->commit( __METHOD__
);
3070 * Wait for the slave to catch up to a given master position.
3072 * @param $pos DBMasterPos object
3073 * @param $timeout Integer: the maximum number of seconds to wait for
3076 * @return integer: zero if the slave was past that position already,
3077 * greater than zero if we waited for some period of time, less than
3078 * zero if we timed out.
3080 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3081 wfProfileIn( __METHOD__
);
3083 if ( !is_null( $this->mFakeSlaveLag
) ) {
3084 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
3086 if ( $wait > $timeout * 1e6
) {
3087 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
3088 wfProfileOut( __METHOD__
);
3090 } elseif ( $wait > 0 ) {
3091 wfDebug( "Fake slave waiting $wait us\n" );
3093 wfProfileOut( __METHOD__
);
3096 wfDebug( "Fake slave up to date ($wait us)\n" );
3097 wfProfileOut( __METHOD__
);
3102 wfProfileOut( __METHOD__
);
3104 # Real waits are implemented in the subclass.
3109 * Get the replication position of this slave
3111 * @return DBMasterPos, or false if this is not a slave.
3113 public function getSlavePos() {
3114 if ( !is_null( $this->mFakeSlaveLag
) ) {
3115 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
3116 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
3125 * Get the position of this master
3127 * @return DBMasterPos, or false if this is not a master
3129 public function getMasterPos() {
3130 if ( $this->mFakeMaster
) {
3131 return new MySQLMasterPos( 'fake', microtime( true ) );
3138 * Run an anonymous function as soon as there is no transaction pending.
3139 * If there is a transaction and it is rolled back, then the callback is cancelled.
3140 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3141 * Callbacks must commit any transactions that they begin.
3143 * This is useful for updates to different systems or when separate transactions are needed.
3144 * For example, one might want to enqueue jobs into a system outside the database, but only
3145 * after the database is updated so that the jobs will see the data when they actually run.
3146 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3148 * @param callable $callback
3151 final public function onTransactionIdle( $callback ) {
3152 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
3153 if ( !$this->mTrxLevel
) {
3154 $this->runOnTransactionIdleCallbacks();
3159 * Run an anonymous function before the current transaction commits or now if there is none.
3160 * If there is a transaction and it is rolled back, then the callback is cancelled.
3161 * Callbacks must not start nor commit any transactions.
3163 * This is useful for updates that easily cause deadlocks if locks are held too long
3164 * but where atomicity is strongly desired for these updates and some related updates.
3166 * @param callable $callback
3169 final public function onTransactionPreCommitOrIdle( $callback ) {
3170 if ( $this->mTrxLevel
) {
3171 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
3173 $this->onTransactionIdle( $callback ); // this will trigger immediately
3178 * Actually any "on transaction idle" callbacks.
3182 protected function runOnTransactionIdleCallbacks() {
3183 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
3185 $e = null; // last exception
3186 do { // callbacks may add callbacks :)
3187 $callbacks = $this->mTrxIdleCallbacks
;
3188 $this->mTrxIdleCallbacks
= array(); // recursion guard
3189 foreach ( $callbacks as $callback ) {
3191 list( $phpCallback ) = $callback;
3192 $this->clearFlag( DBO_TRX
); // make each query its own transaction
3193 call_user_func( $phpCallback );
3194 $this->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
3195 } catch ( Exception
$e ) {}
3197 } while ( count( $this->mTrxIdleCallbacks
) );
3199 if ( $e instanceof Exception
) {
3200 throw $e; // re-throw any last exception
3205 * Actually any "on transaction pre-commit" callbacks.
3209 protected function runOnTransactionPreCommitCallbacks() {
3210 $e = null; // last exception
3211 do { // callbacks may add callbacks :)
3212 $callbacks = $this->mTrxPreCommitCallbacks
;
3213 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
3214 foreach ( $callbacks as $callback ) {
3216 list( $phpCallback ) = $callback;
3217 call_user_func( $phpCallback );
3218 } catch ( Exception
$e ) {}
3220 } while ( count( $this->mTrxPreCommitCallbacks
) );
3222 if ( $e instanceof Exception
) {
3223 throw $e; // re-throw any last exception
3228 * Begin an atomic section of statements
3230 * If a transaction has been started already, just keep track of the given
3231 * section name to make sure the transaction is not committed pre-maturely.
3232 * This function can be used in layers (with sub-sections), so use a stack
3233 * to keep track of the different atomic sections. If there is no transaction,
3234 * start one implicitly.
3236 * The goal of this function is to create an atomic section of SQL queries
3237 * without having to start a new transaction if it already exists.
3239 * Atomic sections are more strict than transactions. With transactions,
3240 * attempting to begin a new transaction when one is already running results
3241 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3242 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3243 * and any database transactions cannot be began or committed until all atomic
3244 * levels are closed. There is no such thing as implicitly opening or closing
3245 * an atomic section.
3248 * @param string $fname
3251 final public function startAtomic( $fname = __METHOD__
) {
3252 if ( !$this->mTrxLevel
) {
3253 $this->begin( $fname );
3254 $this->mTrxAutomatic
= true;
3255 $this->mTrxAutomaticAtomic
= true;
3258 $this->mTrxAtomicLevels
->push( $fname );
3262 * Ends an atomic section of SQL statements
3264 * Ends the next section of atomic SQL statements and commits the transaction
3268 * @see DatabaseBase::startAtomic
3269 * @param string $fname
3272 final public function endAtomic( $fname = __METHOD__
) {
3273 if ( !$this->mTrxLevel
) {
3274 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3276 if ( $this->mTrxAtomicLevels
->isEmpty() ||
3277 $this->mTrxAtomicLevels
->pop() !== $fname
3279 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3282 if ( $this->mTrxAtomicLevels
->isEmpty() && $this->mTrxAutomaticAtomic
) {
3283 $this->commit( $fname, 'flush' );
3288 * Begin a transaction. If a transaction is already in progress, that transaction will be committed before the
3289 * new transaction is started.
3291 * Note that when the DBO_TRX flag is set (which is usually the case for web requests, but not for maintenance scripts),
3292 * any previous database query will have started a transaction automatically.
3294 * Nesting of transactions is not supported. Attempts to nest transactions will cause a warning, unless the current
3295 * transaction was started automatically because of the DBO_TRX flag.
3297 * @param $fname string
3300 final public function begin( $fname = __METHOD__
) {
3301 global $wgDebugDBTransactions;
3303 if ( $this->mTrxLevel
) { // implicit commit
3304 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3305 // If the current transaction was an automatic atomic one, then we definitely have
3306 // a problem. Same if there is any unclosed atomic level.
3307 throw new DBUnexpectedError( $this,
3308 "Attempted to start explicit transaction when atomic levels are still open."
3310 } elseif ( !$this->mTrxAutomatic
) {
3311 // We want to warn about inadvertently nested begin/commit pairs, but not about
3312 // auto-committing implicit transactions that were started by query() via DBO_TRX
3313 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3314 " performing implicit commit!";
3316 wfLogDBError( $msg );
3318 // if the transaction was automatic and has done write operations,
3319 // log it if $wgDebugDBTransactions is enabled.
3320 if ( $this->mTrxDoneWrites
&& $wgDebugDBTransactions ) {
3321 wfDebug( "$fname: Automatic transaction with writes in progress" .
3322 " (from {$this->mTrxFname}), performing implicit commit!\n"
3327 $this->runOnTransactionPreCommitCallbacks();
3328 $this->doCommit( $fname );
3329 if ( $this->mTrxDoneWrites
) {
3330 Profiler
::instance()->transactionWritingOut( $this->mServer
, $this->mDBname
);
3332 $this->runOnTransactionIdleCallbacks();
3335 $this->doBegin( $fname );
3336 $this->mTrxFname
= $fname;
3337 $this->mTrxDoneWrites
= false;
3338 $this->mTrxAutomatic
= false;
3339 $this->mTrxAutomaticAtomic
= false;
3340 $this->mTrxAtomicLevels
= new SplStack
;
3341 $this->mTrxIdleCallbacks
= array();
3342 $this->mTrxPreCommitCallbacks
= array();
3346 * Issues the BEGIN command to the database server.
3348 * @see DatabaseBase::begin()
3349 * @param type $fname
3351 protected function doBegin( $fname ) {
3352 $this->query( 'BEGIN', $fname );
3353 $this->mTrxLevel
= 1;
3357 * Commits a transaction previously started using begin().
3358 * If no transaction is in progress, a warning is issued.
3360 * Nesting of transactions is not supported.
3362 * @param $fname string
3363 * @param string $flush Flush flag, set to 'flush' to disable warnings about explicitly committing implicit
3364 * transactions, or calling commit when no transaction is in progress.
3365 * This will silently break any ongoing explicit transaction. Only set the flush flag if you are sure
3366 * that it is safe to ignore these warnings in your context.
3368 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3369 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3370 // There are still atomic sections open. This cannot be ignored
3371 throw new DBUnexpectedError( $this, "Attempted to commit transaction while atomic sections are still open" );
3374 if ( $flush != 'flush' ) {
3375 if ( !$this->mTrxLevel
) {
3376 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3377 } elseif ( $this->mTrxAutomatic
) {
3378 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3381 if ( !$this->mTrxLevel
) {
3382 return; // nothing to do
3383 } elseif ( !$this->mTrxAutomatic
) {
3384 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3388 $this->runOnTransactionPreCommitCallbacks();
3389 $this->doCommit( $fname );
3390 if ( $this->mTrxDoneWrites
) {
3391 Profiler
::instance()->transactionWritingOut( $this->mServer
, $this->mDBname
);
3393 $this->runOnTransactionIdleCallbacks();
3397 * Issues the COMMIT command to the database server.
3399 * @see DatabaseBase::commit()
3400 * @param type $fname
3402 protected function doCommit( $fname ) {
3403 if ( $this->mTrxLevel
) {
3404 $this->query( 'COMMIT', $fname );
3405 $this->mTrxLevel
= 0;
3410 * Rollback a transaction previously started using begin().
3411 * If no transaction is in progress, a warning is issued.
3413 * No-op on non-transactional databases.
3415 * @param $fname string
3417 final public function rollback( $fname = __METHOD__
) {
3418 if ( !$this->mTrxLevel
) {
3419 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3421 $this->doRollback( $fname );
3422 $this->mTrxIdleCallbacks
= array(); // cancel
3423 $this->mTrxPreCommitCallbacks
= array(); // cancel
3424 $this->mTrxAtomicLevels
= new SplStack
;
3425 if ( $this->mTrxDoneWrites
) {
3426 Profiler
::instance()->transactionWritingOut( $this->mServer
, $this->mDBname
);
3431 * Issues the ROLLBACK command to the database server.
3433 * @see DatabaseBase::rollback()
3434 * @param type $fname
3436 protected function doRollback( $fname ) {
3437 if ( $this->mTrxLevel
) {
3438 $this->query( 'ROLLBACK', $fname, true );
3439 $this->mTrxLevel
= 0;
3444 * Creates a new table with structure copied from existing table
3445 * Note that unlike most database abstraction functions, this function does not
3446 * automatically append database prefix, because it works at a lower
3447 * abstraction level.
3448 * The table names passed to this function shall not be quoted (this
3449 * function calls addIdentifierQuotes when needed).
3451 * @param string $oldName name of table whose structure should be copied
3452 * @param string $newName name of table to be created
3453 * @param $temporary Boolean: whether the new table should be temporary
3454 * @param string $fname calling function name
3455 * @throws MWException
3456 * @return Boolean: true if operation was successful
3458 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3461 throw new MWException(
3462 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3466 * List all tables on the database
3468 * @param string $prefix Only show tables with this prefix, e.g. mw_
3469 * @param string $fname calling function name
3470 * @throws MWException
3472 function listTables( $prefix = null, $fname = __METHOD__
) {
3473 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3477 * Reset the views process cache set by listViews()
3480 final public function clearViewsCache() {
3481 $this->allViews
= null;
3485 * Lists all the VIEWs in the database
3487 * For caching purposes the list of all views should be stored in
3488 * $this->allViews. The process cache can be cleared with clearViewsCache()
3490 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3491 * @param string $fname Name of calling function
3492 * @throws MWException
3495 public function listViews( $prefix = null, $fname = __METHOD__
) {
3496 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3500 * Differentiates between a TABLE and a VIEW
3502 * @param $name string: Name of the database-structure to test.
3503 * @throws MWException
3506 public function isView( $name ) {
3507 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3511 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3512 * to the format used for inserting into timestamp fields in this DBMS.
3514 * The result is unquoted, and needs to be passed through addQuotes()
3515 * before it can be included in raw SQL.
3517 * @param $ts string|int
3521 public function timestamp( $ts = 0 ) {
3522 return wfTimestamp( TS_MW
, $ts );
3526 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3527 * to the format used for inserting into timestamp fields in this DBMS. If
3528 * NULL is input, it is passed through, allowing NULL values to be inserted
3529 * into timestamp fields.
3531 * The result is unquoted, and needs to be passed through addQuotes()
3532 * before it can be included in raw SQL.
3534 * @param $ts string|int
3538 public function timestampOrNull( $ts = null ) {
3539 if ( is_null( $ts ) ) {
3542 return $this->timestamp( $ts );
3547 * Take the result from a query, and wrap it in a ResultWrapper if
3548 * necessary. Boolean values are passed through as is, to indicate success
3549 * of write queries or failure.
3551 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3552 * resource, and it was necessary to call this function to convert it to
3553 * a wrapper. Nowadays, raw database objects are never exposed to external
3554 * callers, so this is unnecessary in external code. For compatibility with
3555 * old code, ResultWrapper objects are passed through unaltered.
3557 * @param $result bool|ResultWrapper
3559 * @return bool|ResultWrapper
3561 public function resultObject( $result ) {
3562 if ( empty( $result ) ) {
3564 } elseif ( $result instanceof ResultWrapper
) {
3566 } elseif ( $result === true ) {
3567 // Successful write query
3570 return new ResultWrapper( $this, $result );
3575 * Ping the server and try to reconnect if it there is no connection
3577 * @return bool Success or failure
3579 public function ping() {
3580 # Stub. Not essential to override.
3585 * Get slave lag. Currently supported only by MySQL.
3587 * Note that this function will generate a fatal error on many
3588 * installations. Most callers should use LoadBalancer::safeGetLag()
3591 * @return int Database replication lag in seconds
3593 public function getLag() {
3594 return intval( $this->mFakeSlaveLag
);
3598 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3602 function maxListLen() {
3607 * Some DBMSs have a special format for inserting into blob fields, they
3608 * don't allow simple quoted strings to be inserted. To insert into such
3609 * a field, pass the data through this function before passing it to
3610 * DatabaseBase::insert().
3614 public function encodeBlob( $b ) {
3619 * Some DBMSs return a special placeholder object representing blob fields
3620 * in result objects. Pass the object through this function to return the
3625 public function decodeBlob( $b ) {
3630 * Override database's default behavior. $options include:
3631 * 'connTimeout' : Set the connection timeout value in seconds.
3632 * May be useful for very long batch queries such as
3633 * full-wiki dumps, where a single query reads out over
3636 * @param $options Array
3639 public function setSessionOptions( array $options ) {
3643 * Read and execute SQL commands from a file.
3645 * Returns true on success, error string or exception on failure (depending
3646 * on object's error ignore settings).
3648 * @param string $filename File name to open
3649 * @param bool|callable $lineCallback Optional function called before reading each line
3650 * @param bool|callable $resultCallback Optional function called for each MySQL result
3651 * @param bool|string $fname Calling function name or false if name should be
3652 * generated dynamically using $filename
3653 * @param bool|callable $inputCallback Callback: Optional function called for each complete line sent
3654 * @throws MWException
3655 * @throws Exception|MWException
3656 * @return bool|string
3658 public function sourceFile(
3659 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3661 wfSuppressWarnings();
3662 $fp = fopen( $filename, 'r' );
3663 wfRestoreWarnings();
3665 if ( false === $fp ) {
3666 throw new MWException( "Could not open \"{$filename}\".\n" );
3670 $fname = __METHOD__
. "( $filename )";
3674 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3676 catch ( MWException
$e ) {
3687 * Get the full path of a patch file. Originally based on archive()
3688 * from updaters.inc. Keep in mind this always returns a patch, as
3689 * it fails back to MySQL if no DB-specific patch can be found
3691 * @param string $patch The name of the patch, like patch-something.sql
3692 * @return String Full path to patch file
3694 public function patchPath( $patch ) {
3697 $dbType = $this->getType();
3698 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3699 return "$IP/maintenance/$dbType/archives/$patch";
3701 return "$IP/maintenance/archives/$patch";
3706 * Set variables to be used in sourceFile/sourceStream, in preference to the
3707 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3708 * all. If it's set to false, $GLOBALS will be used.
3710 * @param bool|array $vars mapping variable name to value.
3712 public function setSchemaVars( $vars ) {
3713 $this->mSchemaVars
= $vars;
3717 * Read and execute commands from an open file handle.
3719 * Returns true on success, error string or exception on failure (depending
3720 * on object's error ignore settings).
3722 * @param $fp Resource: File handle
3723 * @param $lineCallback Callback: Optional function called before reading each query
3724 * @param $resultCallback Callback: Optional function called for each MySQL result
3725 * @param string $fname Calling function name
3726 * @param $inputCallback Callback: Optional function called for each complete query sent
3727 * @return bool|string
3729 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3730 $fname = __METHOD__
, $inputCallback = false )
3734 while ( !feof( $fp ) ) {
3735 if ( $lineCallback ) {
3736 call_user_func( $lineCallback );
3739 $line = trim( fgets( $fp ) );
3741 if ( $line == '' ) {
3745 if ( '-' == $line[0] && '-' == $line[1] ) {
3753 $done = $this->streamStatementEnd( $cmd, $line );
3757 if ( $done ||
feof( $fp ) ) {
3758 $cmd = $this->replaceVars( $cmd );
3760 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3761 $res = $this->query( $cmd, $fname );
3763 if ( $resultCallback ) {
3764 call_user_func( $resultCallback, $res, $this );
3767 if ( false === $res ) {
3768 $err = $this->lastError();
3769 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3780 * Called by sourceStream() to check if we've reached a statement end
3782 * @param string $sql SQL assembled so far
3783 * @param string $newLine New line about to be added to $sql
3784 * @return Bool Whether $newLine contains end of the statement
3786 public function streamStatementEnd( &$sql, &$newLine ) {
3787 if ( $this->delimiter
) {
3789 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3790 if ( $newLine != $prev ) {
3798 * Database independent variable replacement. Replaces a set of variables
3799 * in an SQL statement with their contents as given by $this->getSchemaVars().
3801 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3803 * - '{$var}' should be used for text and is passed through the database's
3805 * - `{$var}` should be used for identifiers (eg: table and database names),
3806 * it is passed through the database's addIdentifierQuotes method which
3807 * can be overridden if the database uses something other than backticks.
3808 * - / *$var* / is just encoded, besides traditional table prefix and
3809 * table options its use should be avoided.
3811 * @param string $ins SQL statement to replace variables in
3812 * @return String The new SQL statement with variables replaced
3814 protected function replaceSchemaVars( $ins ) {
3815 $vars = $this->getSchemaVars();
3816 foreach ( $vars as $var => $value ) {
3818 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
3820 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
3822 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ), $ins );
3828 * Replace variables in sourced SQL
3830 * @param $ins string
3834 protected function replaceVars( $ins ) {
3835 $ins = $this->replaceSchemaVars( $ins );
3838 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3839 array( $this, 'tableNameCallback' ), $ins );
3842 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
3843 array( $this, 'indexNameCallback' ), $ins );
3849 * Get schema variables. If none have been set via setSchemaVars(), then
3850 * use some defaults from the current object.
3854 protected function getSchemaVars() {
3855 if ( $this->mSchemaVars
) {
3856 return $this->mSchemaVars
;
3858 return $this->getDefaultSchemaVars();
3863 * Get schema variables to use if none have been set via setSchemaVars().
3865 * Override this in derived classes to provide variables for tables.sql
3866 * and SQL patch files.
3870 protected function getDefaultSchemaVars() {
3875 * Table name callback
3877 * @param $matches array
3881 protected function tableNameCallback( $matches ) {
3882 return $this->tableName( $matches[1] );
3886 * Index name callback
3888 * @param $matches array
3892 protected function indexNameCallback( $matches ) {
3893 return $this->indexName( $matches[1] );
3897 * Check to see if a named lock is available. This is non-blocking.
3899 * @param string $lockName name of lock to poll
3900 * @param string $method name of method calling us
3904 public function lockIsFree( $lockName, $method ) {
3909 * Acquire a named lock
3911 * Abstracted from Filestore::lock() so child classes can implement for
3914 * @param string $lockName name of lock to aquire
3915 * @param string $method name of method calling us
3916 * @param $timeout Integer: timeout
3919 public function lock( $lockName, $method, $timeout = 5 ) {
3926 * @param string $lockName Name of lock to release
3927 * @param string $method Name of method calling us
3929 * @return int Returns 1 if the lock was released, 0 if the lock was not established
3930 * by this thread (in which case the lock is not released), and NULL if the named
3931 * lock did not exist
3933 public function unlock( $lockName, $method ) {
3938 * Lock specific tables
3940 * @param array $read of tables to lock for read access
3941 * @param array $write of tables to lock for write access
3942 * @param string $method name of caller
3943 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3947 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3952 * Unlock specific tables
3954 * @param string $method the caller
3958 public function unlockTables( $method ) {
3964 * @param $tableName string
3965 * @param $fName string
3966 * @return bool|ResultWrapper
3969 public function dropTable( $tableName, $fName = __METHOD__
) {
3970 if ( !$this->tableExists( $tableName, $fName ) ) {
3973 $sql = "DROP TABLE " . $this->tableName( $tableName );
3974 if ( $this->cascadingDeletes() ) {
3977 return $this->query( $sql, $fName );
3981 * Get search engine class. All subclasses of this need to implement this
3982 * if they wish to use searching.
3986 public function getSearchEngine() {
3987 return 'SearchEngineDummy';
3991 * Find out when 'infinity' is. Most DBMSes support this. This is a special
3992 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
3993 * because "i" sorts after all numbers.
3997 public function getInfinity() {
4002 * Encode an expiry time into the DBMS dependent format
4004 * @param string $expiry timestamp for expiry, or the 'infinity' string
4007 public function encodeExpiry( $expiry ) {
4008 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4009 ?
$this->getInfinity()
4010 : $this->timestamp( $expiry );
4014 * Decode an expiry time into a DBMS independent format
4016 * @param string $expiry DB timestamp field value for expiry
4017 * @param $format integer: TS_* constant, defaults to TS_MW
4020 public function decodeExpiry( $expiry, $format = TS_MW
) {
4021 return ( $expiry == '' ||
$expiry == $this->getInfinity() )
4023 : wfTimestamp( $format, $expiry );
4027 * Allow or deny "big selects" for this session only. This is done by setting
4028 * the sql_big_selects session variable.
4030 * This is a MySQL-specific feature.
4032 * @param $value Mixed: true for allow, false for deny, or "default" to
4033 * restore the initial value
4035 public function setBigSelects( $value = true ) {
4042 public function __toString() {
4043 return (string)$this->mConn
;
4047 * Run a few simple sanity checks
4049 public function __destruct() {
4050 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
4051 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4053 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
4055 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
4056 $callers[] = $callbackInfo[1];
4059 $callers = implode( ', ', $callers );
4060 trigger_error( "DB transaction callbacks still pending (from $callers)." );