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
27 /** Number of times to re-try an operation in case of deadlock */
28 define( 'DEADLOCK_TRIES', 4 );
29 /** Minimum time to wait before retry, in microseconds */
30 define( 'DEADLOCK_DELAY_MIN', 500000 );
31 /** Maximum time to wait before retry */
32 define( 'DEADLOCK_DELAY_MAX', 1500000 );
35 * Base interface for all DBMS-specific code. At a bare minimum, all of the
36 * following must be implemented to support MediaWiki
41 interface DatabaseType
{
43 * Get the type of the DBMS, as it appears in $wgDBtype.
50 * Open a connection to the database. Usually aborts on failure
52 * @param $server String: database server host
53 * @param $user String: database user name
54 * @param $password String: database user password
55 * @param $dbName String: database name
57 * @throws DBConnectionError
59 function open( $server, $user, $password, $dbName );
62 * Fetch the next row from the given result object, in object form.
63 * Fields can be retrieved with $row->fieldname, with fields acting like
66 * @param $res ResultWrapper|object as returned from DatabaseBase::query(), etc.
68 * @throws DBUnexpectedError Thrown if the database returns an error
70 function fetchObject( $res );
73 * Fetch the next row from the given result object, in associative array
74 * form. Fields are retrieved with $row['fieldname'].
76 * @param $res ResultWrapper result object as returned from DatabaseBase::query(), etc.
78 * @throws DBUnexpectedError Thrown if the database returns an error
80 function fetchRow( $res );
83 * Get the number of rows in a result object
85 * @param $res Mixed: A SQL result
88 function numRows( $res );
91 * Get the number of fields in a result object
92 * @see http://www.php.net/mysql_num_fields
94 * @param $res Mixed: A SQL result
97 function numFields( $res );
100 * Get a field name in a result object
101 * @see http://www.php.net/mysql_field_name
103 * @param $res Mixed: A SQL result
107 function fieldName( $res, $n );
110 * Get the inserted value of an auto-increment row
112 * The value inserted should be fetched from nextSequenceValue()
115 * $id = $dbw->nextSequenceValue('page_page_id_seq');
116 * $dbw->insert('page',array('page_id' => $id));
117 * $id = $dbw->insertId();
124 * Change the position of the cursor in a result object
125 * @see http://www.php.net/mysql_data_seek
127 * @param $res Mixed: A SQL result
128 * @param $row Mixed: Either MySQL row or ResultWrapper
130 function dataSeek( $res, $row );
133 * Get the last error number
134 * @see http://www.php.net/mysql_errno
138 function lastErrno();
141 * Get a description of the last error
142 * @see http://www.php.net/mysql_error
146 function lastError();
149 * mysql_fetch_field() wrapper
150 * Returns false if the field doesn't exist
152 * @param $table string: table name
153 * @param $field string: field name
157 function fieldInfo( $table, $field );
160 * Get information about an index into an object
161 * @param $table string: Table name
162 * @param $index string: Index name
163 * @param $fname string: Calling function name
164 * @return Mixed: Database-specific index description class or false if the index does not exist
166 function indexInfo( $table, $index, $fname = 'Database::indexInfo' );
169 * Get the number of rows affected by the last write query
170 * @see http://www.php.net/mysql_affected_rows
174 function affectedRows();
177 * Wrapper for addslashes()
179 * @param $s string: to be slashed.
180 * @return string: slashed string.
182 function strencode( $s );
185 * Returns a wikitext link to the DB's website, e.g.,
186 * return "[http://www.mysql.com/ MySQL]";
187 * Should at least contain plain text, if for some reason
188 * your database has no website.
190 * @return string: wikitext of a link to the server software's web site
192 static function getSoftwareLink();
195 * A string describing the current software version, like from
196 * mysql_get_server_info().
198 * @return string: Version information from the database server.
200 function getServerVersion();
203 * A string describing the current software version, and possibly
204 * other details in a user-friendly way. Will be listed on Special:Version, etc.
205 * Use getServerVersion() to get machine-friendly information.
207 * @return string: Version information from the database server
209 function getServerInfo();
213 * Database abstraction object
216 abstract class DatabaseBase
implements DatabaseType
{
218 # ------------------------------------------------------------------------------
220 # ------------------------------------------------------------------------------
222 protected $mLastQuery = '';
223 protected $mDoneWrites = false;
224 protected $mPHPError = false;
226 protected $mServer, $mUser, $mPassword, $mDBname;
228 protected $mConn = null;
229 protected $mOpened = false;
233 * @var array of callable
235 protected $trxIdleCallbacks = array();
237 protected $mTablePrefix;
239 protected $mTrxLevel = 0;
240 protected $mErrorCount = 0;
241 protected $mLBInfo = array();
242 protected $mFakeSlaveLag = null, $mFakeMaster = false;
243 protected $mDefaultBigSelects = null;
244 protected $mSchemaVars = false;
246 protected $preparedArgs;
248 protected $htmlErrors;
250 protected $delimiter = ';';
253 * Remembers the function name given for starting the most recent transaction via begin().
254 * Used to provide additional context for error reporting.
257 * @see DatabaseBase::mTrxLevel
259 private $mTrxFname = null;
262 * Record if possible write queries were done in the last transaction started
265 * @see DatabaseBase::mTrxLevel
267 private $mTrxDoneWrites = false;
270 * Record if the current transaction was started implicitly due to DBO_TRX being set.
273 * @see DatabaseBase::mTrxLevel
275 private $mTrxAutomatic = false;
277 # ------------------------------------------------------------------------------
279 # ------------------------------------------------------------------------------
280 # These optionally set a variable and return the previous state
283 * A string describing the current software version, and possibly
284 * other details in a user-friendly way. Will be listed on Special:Version, etc.
285 * Use getServerVersion() to get machine-friendly information.
287 * @return string: Version information from the database server
289 public function getServerInfo() {
290 return $this->getServerVersion();
294 * Boolean, controls output of large amounts of debug information.
295 * @param $debug bool|null
296 * - true to enable debugging
297 * - false to disable debugging
298 * - omitted or null to do nothing
300 * @return bool|null previous value of the flag
302 public function debug( $debug = null ) {
303 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
307 * Turns buffering of SQL result sets on (true) or off (false). Default is
310 * Unbuffered queries are very troublesome in MySQL:
312 * - If another query is executed while the first query is being read
313 * out, the first query is killed. This means you can't call normal
314 * MediaWiki functions while you are reading an unbuffered query result
315 * from a normal wfGetDB() connection.
317 * - Unbuffered queries cause the MySQL server to use large amounts of
318 * memory and to hold broad locks which block other queries.
320 * If you want to limit client-side memory, it's almost always better to
321 * split up queries into batches using a LIMIT clause than to switch off
324 * @param $buffer null|bool
326 * @return null|bool The previous value of the flag
328 public function bufferResults( $buffer = null ) {
329 if ( is_null( $buffer ) ) {
330 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
332 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
337 * Turns on (false) or off (true) the automatic generation and sending
338 * of a "we're sorry, but there has been a database error" page on
339 * database errors. Default is on (false). When turned off, the
340 * code should use lastErrno() and lastError() to handle the
341 * situation as appropriate.
343 * @param $ignoreErrors bool|null
345 * @return bool The previous value of the flag.
347 public function ignoreErrors( $ignoreErrors = null ) {
348 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
352 * Gets or sets the current transaction level.
354 * Historically, transactions were allowed to be "nested". This is no
355 * longer supported, so this function really only returns a boolean.
357 * @param $level int An integer (0 or 1), or omitted to leave it unchanged.
358 * @return int The previous value
360 public function trxLevel( $level = null ) {
361 return wfSetVar( $this->mTrxLevel
, $level );
365 * Get/set the number of errors logged. Only useful when errors are ignored
366 * @param $count int The count to set, or omitted to leave it unchanged.
367 * @return int The error count
369 public function errorCount( $count = null ) {
370 return wfSetVar( $this->mErrorCount
, $count );
374 * Get/set the table prefix.
375 * @param $prefix string The table prefix to set, or omitted to leave it unchanged.
376 * @return string The previous table prefix.
378 public function tablePrefix( $prefix = null ) {
379 return wfSetVar( $this->mTablePrefix
, $prefix );
383 * Get properties passed down from the server info array of the load
386 * @param $name string The entry of the info array to get, or null to get the
389 * @return LoadBalancer|null
391 public function getLBInfo( $name = null ) {
392 if ( is_null( $name ) ) {
393 return $this->mLBInfo
;
395 if ( array_key_exists( $name, $this->mLBInfo
) ) {
396 return $this->mLBInfo
[$name];
404 * Set the LB info array, or a member of it. If called with one parameter,
405 * the LB info array is set to that parameter. If it is called with two
406 * parameters, the member with the given name is set to the given value.
411 public function setLBInfo( $name, $value = null ) {
412 if ( is_null( $value ) ) {
413 $this->mLBInfo
= $name;
415 $this->mLBInfo
[$name] = $value;
420 * Set lag time in seconds for a fake slave
424 public function setFakeSlaveLag( $lag ) {
425 $this->mFakeSlaveLag
= $lag;
429 * Make this connection a fake master
431 * @param $enabled bool
433 public function setFakeMaster( $enabled = true ) {
434 $this->mFakeMaster
= $enabled;
438 * Returns true if this database supports (and uses) cascading deletes
442 public function cascadingDeletes() {
447 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
451 public function cleanupTriggers() {
456 * Returns true if this database is strict about what can be put into an IP field.
457 * Specifically, it uses a NULL value instead of an empty string.
461 public function strictIPs() {
466 * Returns true if this database uses timestamps rather than integers
470 public function realTimestamps() {
475 * Returns true if this database does an implicit sort when doing GROUP BY
479 public function implicitGroupby() {
484 * Returns true if this database does an implicit order by when the column has an index
485 * For example: SELECT page_title FROM page LIMIT 1
489 public function implicitOrderby() {
494 * Returns true if this database can do a native search on IP columns
495 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
499 public function searchableIPs() {
504 * Returns true if this database can use functional indexes
508 public function functionalIndexes() {
513 * Return the last query that went through DatabaseBase::query()
516 public function lastQuery() {
517 return $this->mLastQuery
;
521 * Returns true if the connection may have been used for write queries.
522 * Should return true if unsure.
526 public function doneWrites() {
527 return $this->mDoneWrites
;
531 * Is a connection to the database open?
534 public function isOpen() {
535 return $this->mOpened
;
539 * Set a flag for this connection
541 * @param $flag Integer: DBO_* constants from Defines.php:
542 * - DBO_DEBUG: output some debug info (same as debug())
543 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
544 * - DBO_IGNORE: ignore errors (same as ignoreErrors())
545 * - DBO_TRX: automatically start transactions
546 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
547 * and removes it in command line mode
548 * - DBO_PERSISTENT: use persistant database connection
550 public function setFlag( $flag ) {
551 global $wgDebugDBTransactions;
552 $this->mFlags |
= $flag;
553 if ( ( $flag & DBO_TRX
) & $wgDebugDBTransactions ) {
554 wfDebug("Implicit transactions are now disabled.\n");
559 * Clear a flag for this connection
561 * @param $flag: same as setFlag()'s $flag param
563 public function clearFlag( $flag ) {
564 global $wgDebugDBTransactions;
565 $this->mFlags
&= ~
$flag;
566 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
567 wfDebug("Implicit transactions are now disabled.\n");
572 * Returns a boolean whether the flag $flag is set for this connection
574 * @param $flag: same as setFlag()'s $flag param
577 public function getFlag( $flag ) {
578 return !!( $this->mFlags
& $flag );
582 * General read-only accessor
584 * @param $name string
588 public function getProperty( $name ) {
595 public function getWikiID() {
596 if ( $this->mTablePrefix
) {
597 return "{$this->mDBname}-{$this->mTablePrefix}";
599 return $this->mDBname
;
604 * Return a path to the DBMS-specific schema file, otherwise default to tables.sql
608 public function getSchemaPath() {
610 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
611 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
613 return "$IP/maintenance/tables.sql";
617 # ------------------------------------------------------------------------------
619 # ------------------------------------------------------------------------------
623 * @param $server String: database server host
624 * @param $user String: database user name
625 * @param $password String: database user password
626 * @param $dbName String: database name
628 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
630 function __construct( $server = false, $user = false, $password = false, $dbName = false,
631 $flags = 0, $tablePrefix = 'get from global'
633 global $wgDBprefix, $wgCommandLineMode, $wgDebugDBTransactions;
635 $this->mFlags
= $flags;
637 if ( $this->mFlags
& DBO_DEFAULT
) {
638 if ( $wgCommandLineMode ) {
639 $this->mFlags
&= ~DBO_TRX
;
640 if ( $wgDebugDBTransactions ) {
641 wfDebug("Implicit transaction open disabled.\n");
644 $this->mFlags |
= DBO_TRX
;
645 if ( $wgDebugDBTransactions ) {
646 wfDebug("Implicit transaction open enabled.\n");
651 /** Get the default table prefix*/
652 if ( $tablePrefix == 'get from global' ) {
653 $this->mTablePrefix
= $wgDBprefix;
655 $this->mTablePrefix
= $tablePrefix;
659 $this->open( $server, $user, $password, $dbName );
664 * Called by serialize. Throw an exception when DB connection is serialized.
665 * This causes problems on some database engines because the connection is
666 * not restored on unserialize.
668 public function __sleep() {
669 throw new MWException( 'Database serialization may cause problems, since the connection is not restored on wakeup.' );
673 * Given a DB type, construct the name of the appropriate child class of
674 * DatabaseBase. This is designed to replace all of the manual stuff like:
675 * $class = 'Database' . ucfirst( strtolower( $type ) );
676 * as well as validate against the canonical list of DB types we have
678 * This factory function is mostly useful for when you need to connect to a
679 * database other than the MediaWiki default (such as for external auth,
680 * an extension, et cetera). Do not use this to connect to the MediaWiki
681 * database. Example uses in core:
682 * @see LoadBalancer::reallyOpenConnection()
683 * @see ExternalUser_MediaWiki::initFromCond()
684 * @see ForeignDBRepo::getMasterDB()
685 * @see WebInstaller_DBConnect::execute()
689 * @param $dbType String A possible DB type
690 * @param $p Array An array of options to pass to the constructor.
691 * Valid options are: host, user, password, dbname, flags, tablePrefix
692 * @return DatabaseBase subclass or null
694 public final static function factory( $dbType, $p = array() ) {
695 $canonicalDBTypes = array(
696 'mysql', 'postgres', 'sqlite', 'oracle', 'mssql', 'ibm_db2'
698 $dbType = strtolower( $dbType );
699 $class = 'Database' . ucfirst( $dbType );
701 if( in_array( $dbType, $canonicalDBTypes ) ||
( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) ) {
703 isset( $p['host'] ) ?
$p['host'] : false,
704 isset( $p['user'] ) ?
$p['user'] : false,
705 isset( $p['password'] ) ?
$p['password'] : false,
706 isset( $p['dbname'] ) ?
$p['dbname'] : false,
707 isset( $p['flags'] ) ?
$p['flags'] : 0,
708 isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global'
715 protected function installErrorHandler() {
716 $this->mPHPError
= false;
717 $this->htmlErrors
= ini_set( 'html_errors', '0' );
718 set_error_handler( array( $this, 'connectionErrorHandler' ) );
722 * @return bool|string
724 protected function restoreErrorHandler() {
725 restore_error_handler();
726 if ( $this->htmlErrors
!== false ) {
727 ini_set( 'html_errors', $this->htmlErrors
);
729 if ( $this->mPHPError
) {
730 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
731 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
742 protected function connectionErrorHandler( $errno, $errstr ) {
743 $this->mPHPError
= $errstr;
747 * Closes a database connection.
748 * if it is open : commits any open transactions
750 * @return Bool operation success. true if already closed.
752 public function close() {
753 $this->mOpened
= false;
754 if ( $this->mConn
) {
755 if ( $this->trxLevel() ) {
756 if ( $this->mTrxAutomatic
) {
757 // clear flag, so commit() doesn't complain about an explicit commit of an implicit transaction.
758 $this->mTrxAutomatic
= false;
760 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
761 " performing implicit commit before closing connection!" );
764 $this->commit( __METHOD__
);
767 $ret = $this->closeConnection();
768 $this->mConn
= false;
776 * Closes underlying database connection
778 * @return bool: Whether connection was closed successfully
780 protected abstract function closeConnection();
783 * @param $error String: fallback error message, used if none is given by DB
784 * @throws DBConnectionError
786 function reportConnectionError( $error = 'Unknown error' ) {
787 $myError = $this->lastError();
793 throw new DBConnectionError( $this, $error );
797 * The DBMS-dependent part of query()
799 * @param $sql String: SQL query.
800 * @return ResultWrapper Result object to feed to fetchObject, fetchRow, ...; or false on failure
802 protected abstract function doQuery( $sql );
805 * Determine whether a query writes to the DB.
806 * Should return true if unsure.
812 public function isWriteQuery( $sql ) {
813 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
817 * Run an SQL query and return the result. Normally throws a DBQueryError
818 * on failure. If errors are ignored, returns false instead.
820 * In new code, the query wrappers select(), insert(), update(), delete(),
821 * etc. should be used where possible, since they give much better DBMS
822 * independence and automatically quote or validate user input in a variety
823 * of contexts. This function is generally only useful for queries which are
824 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
827 * However, the query wrappers themselves should call this function.
829 * @param $sql String: SQL query
830 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
831 * comment (you can use __METHOD__ or add some extra info)
832 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
833 * maybe best to catch the exception instead?
834 * @throws MWException
835 * @return boolean|ResultWrapper. true for a successful write query, ResultWrapper object
836 * for a successful read query, or false on failure if $tempIgnore set
838 public function query( $sql, $fname = '', $tempIgnore = false ) {
839 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
840 if ( !Profiler
::instance()->isStub() ) {
841 # generalizeSQL will probably cut down the query to reasonable
842 # logging size most of the time. The substr is really just a sanity check.
845 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
846 $totalProf = 'DatabaseBase::query-master';
848 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
849 $totalProf = 'DatabaseBase::query';
852 wfProfileIn( $totalProf );
853 wfProfileIn( $queryProf );
856 $this->mLastQuery
= $sql;
857 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
858 # Set a flag indicating that writes have been done
859 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
860 $this->mDoneWrites
= true;
863 # Add a comment for easy SHOW PROCESSLIST interpretation
865 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
866 $userName = $wgUser->getName();
867 if ( mb_strlen( $userName ) > 15 ) {
868 $userName = mb_substr( $userName, 0, 15 ) . '...';
870 $userName = str_replace( '/', '', $userName );
874 $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
876 # If DBO_TRX is set, start a transaction
877 if ( ( $this->mFlags
& DBO_TRX
) && !$this->mTrxLevel
&&
878 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' )
880 # Avoid establishing transactions for SHOW and SET statements too -
881 # that would delay transaction initializations to once connection
882 # is really used by application
883 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
884 if ( strpos( $sqlstart, "SHOW " ) !== 0 && strpos( $sqlstart, "SET " ) !== 0 ) {
885 global $wgDebugDBTransactions;
886 if ( $wgDebugDBTransactions ) {
887 wfDebug("Implicit transaction start.\n");
889 $this->begin( __METHOD__
. " ($fname)" );
890 $this->mTrxAutomatic
= true;
894 # Keep track of whether the transaction has write queries pending
895 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $this->isWriteQuery( $sql ) ) {
896 $this->mTrxDoneWrites
= true;
899 if ( $this->debug() ) {
903 $sqlx = substr( $commentedSql, 0, 500 );
904 $sqlx = strtr( $sqlx, "\t\n", ' ' );
906 $master = $isMaster ?
'master' : 'slave';
907 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
910 if ( istainted( $sql ) & TC_MYSQL
) {
911 throw new MWException( 'Tainted query found' );
914 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
916 # Do the query and handle errors
917 $ret = $this->doQuery( $commentedSql );
919 MWDebug
::queryTime( $queryId );
921 # Try reconnecting if the connection was lost
922 if ( false === $ret && $this->wasErrorReissuable() ) {
923 # Transaction is gone, like it or not
924 $this->mTrxLevel
= 0;
925 $this->trxIdleCallbacks
= array(); // cancel
926 wfDebug( "Connection lost, reconnecting...\n" );
928 if ( $this->ping() ) {
929 wfDebug( "Reconnected\n" );
930 $sqlx = substr( $commentedSql, 0, 500 );
931 $sqlx = strtr( $sqlx, "\t\n", ' ' );
932 global $wgRequestTime;
933 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
934 if ( $elapsed < 300 ) {
935 # Not a database error to lose a transaction after a minute or two
936 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
938 $ret = $this->doQuery( $commentedSql );
940 wfDebug( "Failed\n" );
944 if ( false === $ret ) {
945 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
948 if ( !Profiler
::instance()->isStub() ) {
949 wfProfileOut( $queryProf );
950 wfProfileOut( $totalProf );
953 return $this->resultObject( $ret );
957 * Report a query error. Log the error, and if neither the object ignore
958 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
960 * @param $error String
961 * @param $errno Integer
963 * @param $fname String
964 * @param $tempIgnore Boolean
965 * @throws DBQueryError
967 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
968 # Ignore errors during error handling to avoid infinite recursion
969 $ignore = $this->ignoreErrors( true );
970 ++
$this->mErrorCount
;
972 if ( $ignore ||
$tempIgnore ) {
973 wfDebug( "SQL ERROR (ignored): $error\n" );
974 $this->ignoreErrors( $ignore );
976 $sql1line = str_replace( "\n", "\\n", $sql );
977 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
978 wfDebug( "SQL ERROR: " . $error . "\n" );
979 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
984 * Intended to be compatible with the PEAR::DB wrapper functions.
985 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
987 * ? = scalar value, quoted as necessary
988 * ! = raw SQL bit (a function for instance)
989 * & = filename; reads the file and inserts as a blob
990 * (we don't use this though...)
993 * @param $func string
997 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
998 /* MySQL doesn't support prepared statements (yet), so just
999 pack up the query for reference. We'll manually replace
1001 return array( 'query' => $sql, 'func' => $func );
1005 * Free a prepared query, generated by prepare().
1008 protected function freePrepared( $prepared ) {
1009 /* No-op by default */
1013 * Execute a prepared query with the various arguments
1014 * @param $prepared String: the prepared sql
1015 * @param $args Mixed: Either an array here, or put scalars as varargs
1017 * @return ResultWrapper
1019 public function execute( $prepared, $args = null ) {
1020 if ( !is_array( $args ) ) {
1022 $args = func_get_args();
1023 array_shift( $args );
1026 $sql = $this->fillPrepared( $prepared['query'], $args );
1028 return $this->query( $sql, $prepared['func'] );
1032 * For faking prepared SQL statements on DBs that don't support it directly.
1034 * @param $preparedQuery String: a 'preparable' SQL statement
1035 * @param $args Array of arguments to fill it with
1036 * @return string executable SQL
1038 public function fillPrepared( $preparedQuery, $args ) {
1040 $this->preparedArgs
=& $args;
1042 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1043 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1047 * preg_callback func for fillPrepared()
1048 * The arguments should be in $this->preparedArgs and must not be touched
1049 * while we're doing this.
1051 * @param $matches Array
1052 * @throws DBUnexpectedError
1055 protected function fillPreparedArg( $matches ) {
1056 switch( $matches[1] ) {
1057 case '\\?': return '?';
1058 case '\\!': return '!';
1059 case '\\&': return '&';
1062 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
1064 switch( $matches[1] ) {
1065 case '?': return $this->addQuotes( $arg );
1066 case '!': return $arg;
1068 # return $this->addQuotes( file_get_contents( $arg ) );
1069 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
1071 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
1076 * Free a result object returned by query() or select(). It's usually not
1077 * necessary to call this, just use unset() or let the variable holding
1078 * the result object go out of scope.
1080 * @param $res Mixed: A SQL result
1082 public function freeResult( $res ) {}
1085 * A SELECT wrapper which returns a single field from a single result row.
1087 * Usually throws a DBQueryError on failure. If errors are explicitly
1088 * ignored, returns false on failure.
1090 * If no result rows are returned from the query, false is returned.
1092 * @param $table string|array Table name. See DatabaseBase::select() for details.
1093 * @param $var string The field name to select. This must be a valid SQL
1094 * fragment: do not use unvalidated user input.
1095 * @param $cond string|array The condition array. See DatabaseBase::select() for details.
1096 * @param $fname string The function name of the caller.
1097 * @param $options string|array The query options. See DatabaseBase::select() for details.
1099 * @return bool|mixed The value from the field, or false on failure.
1101 public function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField',
1102 $options = array() )
1104 if ( !is_array( $options ) ) {
1105 $options = array( $options );
1108 $options['LIMIT'] = 1;
1110 $res = $this->select( $table, $var, $cond, $fname, $options );
1112 if ( $res === false ||
!$this->numRows( $res ) ) {
1116 $row = $this->fetchRow( $res );
1118 if ( $row !== false ) {
1119 return reset( $row );
1126 * Returns an optional USE INDEX clause to go after the table, and a
1127 * string to go at the end of the query.
1129 * @param $options Array: associative array of options to be turned into
1130 * an SQL query, valid keys are listed in the function.
1132 * @see DatabaseBase::select()
1134 public function makeSelectOptions( $options ) {
1135 $preLimitTail = $postLimitTail = '';
1138 $noKeyOptions = array();
1140 foreach ( $options as $key => $option ) {
1141 if ( is_numeric( $key ) ) {
1142 $noKeyOptions[$option] = true;
1146 if ( isset( $options['GROUP BY'] ) ) {
1147 $gb = is_array( $options['GROUP BY'] )
1148 ?
implode( ',', $options['GROUP BY'] )
1149 : $options['GROUP BY'];
1150 $preLimitTail .= " GROUP BY {$gb}";
1153 if ( isset( $options['HAVING'] ) ) {
1154 $having = is_array( $options['HAVING'] )
1155 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1156 : $options['HAVING'];
1157 $preLimitTail .= " HAVING {$having}";
1160 if ( isset( $options['ORDER BY'] ) ) {
1161 $ob = is_array( $options['ORDER BY'] )
1162 ?
implode( ',', $options['ORDER BY'] )
1163 : $options['ORDER BY'];
1164 $preLimitTail .= " ORDER BY {$ob}";
1167 // if (isset($options['LIMIT'])) {
1168 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1169 // isset($options['OFFSET']) ? $options['OFFSET']
1173 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1174 $postLimitTail .= ' FOR UPDATE';
1177 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1178 $postLimitTail .= ' LOCK IN SHARE MODE';
1181 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1182 $startOpts .= 'DISTINCT';
1185 # Various MySQL extensions
1186 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1187 $startOpts .= ' /*! STRAIGHT_JOIN */';
1190 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1191 $startOpts .= ' HIGH_PRIORITY';
1194 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1195 $startOpts .= ' SQL_BIG_RESULT';
1198 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1199 $startOpts .= ' SQL_BUFFER_RESULT';
1202 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1203 $startOpts .= ' SQL_SMALL_RESULT';
1206 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1207 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1210 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1211 $startOpts .= ' SQL_CACHE';
1214 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1215 $startOpts .= ' SQL_NO_CACHE';
1218 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1219 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1224 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1228 * Execute a SELECT query constructed using the various parameters provided.
1229 * See below for full details of the parameters.
1231 * @param $table String|Array Table name
1232 * @param $vars String|Array Field names
1233 * @param $conds String|Array Conditions
1234 * @param $fname String Caller function name
1235 * @param $options Array Query options
1236 * @param $join_conds Array Join conditions
1238 * @param $table string|array
1240 * May be either an array of table names, or a single string holding a table
1241 * name. If an array is given, table aliases can be specified, for example:
1243 * array( 'a' => 'user' )
1245 * This includes the user table in the query, with the alias "a" available
1246 * for use in field names (e.g. a.user_name).
1248 * All of the table names given here are automatically run through
1249 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1250 * added, and various other table name mappings to be performed.
1253 * @param $vars string|array
1255 * May be either a field name or an array of field names. The field names
1256 * can be complete fragments of SQL, for direct inclusion into the SELECT
1257 * query. If an array is given, field aliases can be specified, for example:
1259 * array( 'maxrev' => 'MAX(rev_id)' )
1261 * This includes an expression with the alias "maxrev" in the query.
1263 * If an expression is given, care must be taken to ensure that it is
1267 * @param $conds string|array
1269 * May be either a string containing a single condition, or an array of
1270 * conditions. If an array is given, the conditions constructed from each
1271 * element are combined with AND.
1273 * Array elements may take one of two forms:
1275 * - Elements with a numeric key are interpreted as raw SQL fragments.
1276 * - Elements with a string key are interpreted as equality conditions,
1277 * where the key is the field name.
1278 * - If the value of such an array element is a scalar (such as a
1279 * string), it will be treated as data and thus quoted appropriately.
1280 * If it is null, an IS NULL clause will be added.
1281 * - If the value is an array, an IN(...) clause will be constructed,
1282 * such that the field name may match any of the elements in the
1283 * array. The elements of the array will be quoted.
1285 * Note that expressions are often DBMS-dependent in their syntax.
1286 * DBMS-independent wrappers are provided for constructing several types of
1287 * expression commonly used in condition queries. See:
1288 * - DatabaseBase::buildLike()
1289 * - DatabaseBase::conditional()
1292 * @param $options string|array
1294 * Optional: Array of query options. Boolean options are specified by
1295 * including them in the array as a string value with a numeric key, for
1298 * array( 'FOR UPDATE' )
1300 * The supported options are:
1302 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1303 * with LIMIT can theoretically be used for paging through a result set,
1304 * but this is discouraged in MediaWiki for performance reasons.
1306 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1307 * and then the first rows are taken until the limit is reached. LIMIT
1308 * is applied to a result set after OFFSET.
1310 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1311 * changed until the next COMMIT.
1313 * - DISTINCT: Boolean: return only unique result rows.
1315 * - GROUP BY: May be either an SQL fragment string naming a field or
1316 * expression to group by, or an array of such SQL fragments.
1318 * - HAVING: May be either an string containing a HAVING clause or an array of
1319 * conditions building the HAVING clause. If an array is given, the conditions
1320 * constructed from each element are combined with AND.
1322 * - ORDER BY: May be either an SQL fragment giving a field name or
1323 * expression to order by, or an array of such SQL fragments.
1325 * - USE INDEX: This may be either a string giving the index name to use
1326 * for the query, or an array. If it is an associative array, each key
1327 * gives the table name (or alias), each value gives the index name to
1328 * use for that table. All strings are SQL fragments and so should be
1329 * validated by the caller.
1331 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1332 * instead of SELECT.
1334 * And also the following boolean MySQL extensions, see the MySQL manual
1335 * for documentation:
1337 * - LOCK IN SHARE MODE
1341 * - SQL_BUFFER_RESULT
1342 * - SQL_SMALL_RESULT
1343 * - SQL_CALC_FOUND_ROWS
1348 * @param $join_conds string|array
1350 * Optional associative array of table-specific join conditions. In the
1351 * most common case, this is unnecessary, since the join condition can be
1352 * in $conds. However, it is useful for doing a LEFT JOIN.
1354 * The key of the array contains the table name or alias. The value is an
1355 * array with two elements, numbered 0 and 1. The first gives the type of
1356 * join, the second is an SQL fragment giving the join condition for that
1357 * table. For example:
1359 * array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1361 * @return ResultWrapper. If the query returned no rows, a ResultWrapper
1362 * with no rows in it will be returned. If there was a query error, a
1363 * DBQueryError exception will be thrown, except if the "ignore errors"
1364 * option was set, in which case false will be returned.
1366 public function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select',
1367 $options = array(), $join_conds = array() ) {
1368 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1370 return $this->query( $sql, $fname );
1374 * The equivalent of DatabaseBase::select() except that the constructed SQL
1375 * is returned, instead of being immediately executed. This can be useful for
1376 * doing UNION queries, where the SQL text of each query is needed. In general,
1377 * however, callers outside of Database classes should just use select().
1379 * @param $table string|array Table name
1380 * @param $vars string|array Field names
1381 * @param $conds string|array Conditions
1382 * @param $fname string Caller function name
1383 * @param $options string|array Query options
1384 * @param $join_conds string|array Join conditions
1386 * @return string SQL query string.
1387 * @see DatabaseBase::select()
1389 public function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select',
1390 $options = array(), $join_conds = array() )
1392 if ( is_array( $vars ) ) {
1393 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1396 $options = (array)$options;
1398 if ( is_array( $table ) ) {
1399 $useIndex = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1400 ?
$options['USE INDEX']
1402 if ( count( $join_conds ) ||
count( $useIndex ) ) {
1404 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndex, $join_conds );
1406 $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
1408 } elseif ( $table != '' ) {
1409 if ( $table[0] == ' ' ) {
1410 $from = ' FROM ' . $table;
1412 $from = ' FROM ' . $this->tableName( $table );
1418 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1420 if ( !empty( $conds ) ) {
1421 if ( is_array( $conds ) ) {
1422 $conds = $this->makeList( $conds, LIST_AND
);
1424 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1426 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1429 if ( isset( $options['LIMIT'] ) ) {
1430 $sql = $this->limitResult( $sql, $options['LIMIT'],
1431 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1433 $sql = "$sql $postLimitTail";
1435 if ( isset( $options['EXPLAIN'] ) ) {
1436 $sql = 'EXPLAIN ' . $sql;
1443 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1444 * that a single row object is returned. If the query returns no rows,
1445 * false is returned.
1447 * @param $table string|array Table name
1448 * @param $vars string|array Field names
1449 * @param $conds array Conditions
1450 * @param $fname string Caller function name
1451 * @param $options string|array Query options
1452 * @param $join_conds array|string Join conditions
1454 * @return object|bool
1456 public function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow',
1457 $options = array(), $join_conds = array() )
1459 $options = (array)$options;
1460 $options['LIMIT'] = 1;
1461 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1463 if ( $res === false ) {
1467 if ( !$this->numRows( $res ) ) {
1471 $obj = $this->fetchObject( $res );
1477 * Estimate rows in dataset.
1479 * MySQL allows you to estimate the number of rows that would be returned
1480 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1481 * index cardinality statistics, and is notoriously inaccurate, especially
1482 * when large numbers of rows have recently been added or deleted.
1484 * For DBMSs that don't support fast result size estimation, this function
1485 * will actually perform the SELECT COUNT(*).
1487 * Takes the same arguments as DatabaseBase::select().
1489 * @param $table String: table name
1490 * @param Array|string $vars : unused
1491 * @param Array|string $conds : filters on the table
1492 * @param $fname String: function name for profiling
1493 * @param $options Array: options for select
1494 * @return Integer: row count
1496 public function estimateRowCount( $table, $vars = '*', $conds = '',
1497 $fname = 'DatabaseBase::estimateRowCount', $options = array() )
1500 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1503 $row = $this->fetchRow( $res );
1504 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1511 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1512 * It's only slightly flawed. Don't use for anything important.
1514 * @param $sql String A SQL Query
1518 static function generalizeSQL( $sql ) {
1519 # This does the same as the regexp below would do, but in such a way
1520 # as to avoid crashing php on some large strings.
1521 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1523 $sql = str_replace ( "\\\\", '', $sql );
1524 $sql = str_replace ( "\\'", '', $sql );
1525 $sql = str_replace ( "\\\"", '', $sql );
1526 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1527 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1529 # All newlines, tabs, etc replaced by single space
1530 $sql = preg_replace ( '/\s+/', ' ', $sql );
1533 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1539 * Determines whether a field exists in a table
1541 * @param $table String: table name
1542 * @param $field String: filed to check on that table
1543 * @param $fname String: calling function name (optional)
1544 * @return Boolean: whether $table has filed $field
1546 public function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1547 $info = $this->fieldInfo( $table, $field );
1553 * Determines whether an index exists
1554 * Usually throws a DBQueryError on failure
1555 * If errors are explicitly ignored, returns NULL on failure
1559 * @param $fname string
1563 public function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1564 $info = $this->indexInfo( $table, $index, $fname );
1565 if ( is_null( $info ) ) {
1568 return $info !== false;
1573 * Query whether a given table exists
1575 * @param $table string
1576 * @param $fname string
1580 public function tableExists( $table, $fname = __METHOD__
) {
1581 $table = $this->tableName( $table );
1582 $old = $this->ignoreErrors( true );
1583 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1584 $this->ignoreErrors( $old );
1590 * mysql_field_type() wrapper
1595 public function fieldType( $res, $index ) {
1596 if ( $res instanceof ResultWrapper
) {
1597 $res = $res->result
;
1600 return mysql_field_type( $res, $index );
1604 * Determines if a given index is unique
1606 * @param $table string
1607 * @param $index string
1611 public function indexUnique( $table, $index ) {
1612 $indexInfo = $this->indexInfo( $table, $index );
1614 if ( !$indexInfo ) {
1618 return !$indexInfo[0]->Non_unique
;
1622 * Helper for DatabaseBase::insert().
1624 * @param $options array
1627 protected function makeInsertOptions( $options ) {
1628 return implode( ' ', $options );
1632 * INSERT wrapper, inserts an array into a table.
1636 * - A single associative array. The array keys are the field names, and
1637 * the values are the values to insert. The values are treated as data
1638 * and will be quoted appropriately. If NULL is inserted, this will be
1639 * converted to a database NULL.
1640 * - An array with numeric keys, holding a list of associative arrays.
1641 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1642 * each subarray must be identical to each other, and in the same order.
1644 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1647 * $options is an array of options, with boolean options encoded as values
1648 * with numeric keys, in the same style as $options in
1649 * DatabaseBase::select(). Supported options are:
1651 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1652 * any rows which cause duplicate key errors are not inserted. It's
1653 * possible to determine how many rows were successfully inserted using
1654 * DatabaseBase::affectedRows().
1656 * @param $table String Table name. This will be passed through
1657 * DatabaseBase::tableName().
1658 * @param $a Array of rows to insert
1659 * @param $fname String Calling function name (use __METHOD__) for logs/profiling
1660 * @param $options Array of options
1664 public function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1665 # No rows to insert, easy just return now
1666 if ( !count( $a ) ) {
1670 $table = $this->tableName( $table );
1672 if ( !is_array( $options ) ) {
1673 $options = array( $options );
1676 $options = $this->makeInsertOptions( $options );
1678 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1680 $keys = array_keys( $a[0] );
1683 $keys = array_keys( $a );
1686 $sql = 'INSERT ' . $options .
1687 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1691 foreach ( $a as $row ) {
1697 $sql .= '(' . $this->makeList( $row ) . ')';
1700 $sql .= '(' . $this->makeList( $a ) . ')';
1703 return (bool)$this->query( $sql, $fname );
1707 * Make UPDATE options for the DatabaseBase::update function
1709 * @param $options Array: The options passed to DatabaseBase::update
1712 protected function makeUpdateOptions( $options ) {
1713 if ( !is_array( $options ) ) {
1714 $options = array( $options );
1719 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1720 $opts[] = $this->lowPriorityOption();
1723 if ( in_array( 'IGNORE', $options ) ) {
1727 return implode( ' ', $opts );
1731 * UPDATE wrapper. Takes a condition array and a SET array.
1733 * @param $table String name of the table to UPDATE. This will be passed through
1734 * DatabaseBase::tableName().
1736 * @param $values Array: An array of values to SET. For each array element,
1737 * the key gives the field name, and the value gives the data
1738 * to set that field to. The data will be quoted by
1739 * DatabaseBase::addQuotes().
1741 * @param $conds Array: An array of conditions (WHERE). See
1742 * DatabaseBase::select() for the details of the format of
1743 * condition arrays. Use '*' to update all rows.
1745 * @param $fname String: The function name of the caller (from __METHOD__),
1746 * for logging and profiling.
1748 * @param $options Array: An array of UPDATE options, can be:
1749 * - IGNORE: Ignore unique key conflicts
1750 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1753 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1754 $table = $this->tableName( $table );
1755 $opts = $this->makeUpdateOptions( $options );
1756 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1758 if ( $conds !== array() && $conds !== '*' ) {
1759 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1762 return $this->query( $sql, $fname );
1766 * Makes an encoded list of strings from an array
1767 * @param $a Array containing the data
1768 * @param int $mode Constant
1769 * - LIST_COMMA: comma separated, no field names
1770 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
1771 * the documentation for $conds in DatabaseBase::select().
1772 * - LIST_OR: ORed WHERE clause (without the WHERE)
1773 * - LIST_SET: comma separated with field names, like a SET clause
1774 * - LIST_NAMES: comma separated field names
1776 * @throws MWException|DBUnexpectedError
1779 public function makeList( $a, $mode = LIST_COMMA
) {
1780 if ( !is_array( $a ) ) {
1781 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1787 foreach ( $a as $field => $value ) {
1789 if ( $mode == LIST_AND
) {
1791 } elseif ( $mode == LIST_OR
) {
1800 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1801 $list .= "($value)";
1802 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1804 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1805 if ( count( $value ) == 0 ) {
1806 throw new MWException( __METHOD__
. ': empty input' );
1807 } elseif ( count( $value ) == 1 ) {
1808 // Special-case single values, as IN isn't terribly efficient
1809 // Don't necessarily assume the single key is 0; we don't
1810 // enforce linear numeric ordering on other arrays here.
1811 $value = array_values( $value );
1812 $list .= $field . " = " . $this->addQuotes( $value[0] );
1814 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1816 } elseif ( $value === null ) {
1817 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1818 $list .= "$field IS ";
1819 } elseif ( $mode == LIST_SET
) {
1820 $list .= "$field = ";
1824 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1825 $list .= "$field = ";
1827 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1835 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1836 * The keys on each level may be either integers or strings.
1838 * @param $data Array: organized as 2-d
1839 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
1840 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1841 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1842 * @return Mixed: string SQL fragment, or false if no items in array.
1844 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1847 foreach ( $data as $base => $sub ) {
1848 if ( count( $sub ) ) {
1849 $conds[] = $this->makeList(
1850 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1856 return $this->makeList( $conds, LIST_OR
);
1858 // Nothing to search for...
1864 * Return aggregated value alias
1867 * @param $valuename string
1871 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1879 public function bitNot( $field ) {
1885 * @param $fieldRight
1888 public function bitAnd( $fieldLeft, $fieldRight ) {
1889 return "($fieldLeft & $fieldRight)";
1894 * @param $fieldRight
1897 public function bitOr( $fieldLeft, $fieldRight ) {
1898 return "($fieldLeft | $fieldRight)";
1902 * Build a concatenation list to feed into a SQL query
1903 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
1906 public function buildConcat( $stringList ) {
1907 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1911 * Change the current database
1913 * @todo Explain what exactly will fail if this is not overridden.
1917 * @return bool Success or failure
1919 public function selectDB( $db ) {
1920 # Stub. Shouldn't cause serious problems if it's not overridden, but
1921 # if your database engine supports a concept similar to MySQL's
1922 # databases you may as well.
1923 $this->mDBname
= $db;
1928 * Get the current DB name
1930 public function getDBname() {
1931 return $this->mDBname
;
1935 * Get the server hostname or IP address
1937 public function getServer() {
1938 return $this->mServer
;
1942 * Format a table name ready for use in constructing an SQL query
1944 * This does two important things: it quotes the table names to clean them up,
1945 * and it adds a table prefix if only given a table name with no quotes.
1947 * All functions of this object which require a table name call this function
1948 * themselves. Pass the canonical name to such functions. This is only needed
1949 * when calling query() directly.
1951 * @param $name String: database table name
1952 * @param $format String One of:
1953 * quoted - Automatically pass the table name through addIdentifierQuotes()
1954 * so that it can be used in a query.
1955 * raw - Do not add identifier quotes to the table name
1956 * @return String: full database name
1958 public function tableName( $name, $format = 'quoted' ) {
1959 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1960 # Skip the entire process when we have a string quoted on both ends.
1961 # Note that we check the end so that we will still quote any use of
1962 # use of `database`.table. But won't break things if someone wants
1963 # to query a database table with a dot in the name.
1964 if ( $this->isQuotedIdentifier( $name ) ) {
1968 # Lets test for any bits of text that should never show up in a table
1969 # name. Basically anything like JOIN or ON which are actually part of
1970 # SQL queries, but may end up inside of the table value to combine
1971 # sql. Such as how the API is doing.
1972 # Note that we use a whitespace test rather than a \b test to avoid
1973 # any remote case where a word like on may be inside of a table name
1974 # surrounded by symbols which may be considered word breaks.
1975 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1979 # Split database and table into proper variables.
1980 # We reverse the explode so that database.table and table both output
1981 # the correct table.
1982 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1983 if ( isset( $dbDetails[1] ) ) {
1984 list( $table, $database ) = $dbDetails;
1986 list( $table ) = $dbDetails;
1988 $prefix = $this->mTablePrefix
; # Default prefix
1990 # A database name has been specified in input. We don't want any
1992 if ( isset( $database ) ) {
1996 # Note that we use the long format because php will complain in in_array if
1997 # the input is not an array, and will complain in is_array if it is not set.
1998 if ( !isset( $database ) # Don't use shared database if pre selected.
1999 && isset( $wgSharedDB ) # We have a shared database
2000 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
2001 && isset( $wgSharedTables )
2002 && is_array( $wgSharedTables )
2003 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
2004 $database = $wgSharedDB;
2005 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
2008 # Quote the $database and $table and apply the prefix if not quoted.
2009 if ( isset( $database ) ) {
2010 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2011 $database = $this->addIdentifierQuotes( $database );
2015 $table = "{$prefix}{$table}";
2016 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $table ) ) {
2017 $table = $this->addIdentifierQuotes( "{$table}" );
2020 # Merge our database and table into our final table name.
2021 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
2027 * Fetch a number of table names into an array
2028 * This is handy when you need to construct SQL for joins
2031 * extract($dbr->tableNames('user','watchlist'));
2032 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2033 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2037 public function tableNames() {
2038 $inArray = func_get_args();
2041 foreach ( $inArray as $name ) {
2042 $retVal[$name] = $this->tableName( $name );
2049 * Fetch a number of table names into an zero-indexed numerical array
2050 * This is handy when you need to construct SQL for joins
2053 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
2054 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2055 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2059 public function tableNamesN() {
2060 $inArray = func_get_args();
2063 foreach ( $inArray as $name ) {
2064 $retVal[] = $this->tableName( $name );
2071 * Get an aliased table name
2072 * e.g. tableName AS newTableName
2074 * @param $name string Table name, see tableName()
2075 * @param $alias string|bool Alias (optional)
2076 * @return string SQL name for aliased table. Will not alias a table to its own name
2078 public function tableNameWithAlias( $name, $alias = false ) {
2079 if ( !$alias ||
$alias == $name ) {
2080 return $this->tableName( $name );
2082 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2087 * Gets an array of aliased table names
2089 * @param $tables array( [alias] => table )
2090 * @return array of strings, see tableNameWithAlias()
2092 public function tableNamesWithAlias( $tables ) {
2094 foreach ( $tables as $alias => $table ) {
2095 if ( is_numeric( $alias ) ) {
2098 $retval[] = $this->tableNameWithAlias( $table, $alias );
2104 * Get an aliased field name
2105 * e.g. fieldName AS newFieldName
2107 * @param $name string Field name
2108 * @param $alias string|bool Alias (optional)
2109 * @return string SQL name for aliased field. Will not alias a field to its own name
2111 public function fieldNameWithAlias( $name, $alias = false ) {
2112 if ( !$alias ||
(string)$alias === (string)$name ) {
2115 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2120 * Gets an array of aliased field names
2122 * @param $fields array( [alias] => field )
2123 * @return array of strings, see fieldNameWithAlias()
2125 public function fieldNamesWithAlias( $fields ) {
2127 foreach ( $fields as $alias => $field ) {
2128 if ( is_numeric( $alias ) ) {
2131 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2137 * Get the aliased table name clause for a FROM clause
2138 * which might have a JOIN and/or USE INDEX clause
2140 * @param $tables array ( [alias] => table )
2141 * @param $use_index array Same as for select()
2142 * @param $join_conds array Same as for select()
2145 protected function tableNamesWithUseIndexOrJOIN(
2146 $tables, $use_index = array(), $join_conds = array()
2150 $use_index = (array)$use_index;
2151 $join_conds = (array)$join_conds;
2153 foreach ( $tables as $alias => $table ) {
2154 if ( !is_string( $alias ) ) {
2155 // No alias? Set it equal to the table name
2158 // Is there a JOIN clause for this table?
2159 if ( isset( $join_conds[$alias] ) ) {
2160 list( $joinType, $conds ) = $join_conds[$alias];
2161 $tableClause = $joinType;
2162 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2163 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2164 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2166 $tableClause .= ' ' . $use;
2169 $on = $this->makeList( (array)$conds, LIST_AND
);
2171 $tableClause .= ' ON (' . $on . ')';
2174 $retJOIN[] = $tableClause;
2175 // Is there an INDEX clause for this table?
2176 } elseif ( isset( $use_index[$alias] ) ) {
2177 $tableClause = $this->tableNameWithAlias( $table, $alias );
2178 $tableClause .= ' ' . $this->useIndexClause(
2179 implode( ',', (array)$use_index[$alias] ) );
2181 $ret[] = $tableClause;
2183 $tableClause = $this->tableNameWithAlias( $table, $alias );
2185 $ret[] = $tableClause;
2189 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2190 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2191 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2193 // Compile our final table clause
2194 return implode( ' ', array( $straightJoins, $otherJoins ) );
2198 * Get the name of an index in a given table
2204 protected function indexName( $index ) {
2205 // Backwards-compatibility hack
2207 'ar_usertext_timestamp' => 'usertext_timestamp',
2208 'un_user_id' => 'user_id',
2209 'un_user_ip' => 'user_ip',
2212 if ( isset( $renamed[$index] ) ) {
2213 return $renamed[$index];
2220 * If it's a string, adds quotes and backslashes
2221 * Otherwise returns as-is
2227 public function addQuotes( $s ) {
2228 if ( $s === null ) {
2231 # This will also quote numeric values. This should be harmless,
2232 # and protects against weird problems that occur when they really
2233 # _are_ strings such as article titles and string->number->string
2234 # conversion is not 1:1.
2235 return "'" . $this->strencode( $s ) . "'";
2240 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2241 * MySQL uses `backticks` while basically everything else uses double quotes.
2242 * Since MySQL is the odd one out here the double quotes are our generic
2243 * and we implement backticks in DatabaseMysql.
2249 public function addIdentifierQuotes( $s ) {
2250 return '"' . str_replace( '"', '""', $s ) . '"';
2254 * Returns if the given identifier looks quoted or not according to
2255 * the database convention for quoting identifiers .
2257 * @param $name string
2261 public function isQuotedIdentifier( $name ) {
2262 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2269 protected function escapeLikeInternal( $s ) {
2270 $s = str_replace( '\\', '\\\\', $s );
2271 $s = $this->strencode( $s );
2272 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
2278 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
2279 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
2280 * Alternatively, the function could be provided with an array of aforementioned parameters.
2282 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
2283 * for subpages of 'My page title'.
2284 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
2287 * @return String: fully built LIKE statement
2289 public function buildLike() {
2290 $params = func_get_args();
2292 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2293 $params = $params[0];
2298 foreach ( $params as $value ) {
2299 if ( $value instanceof LikeMatch
) {
2300 $s .= $value->toString();
2302 $s .= $this->escapeLikeInternal( $value );
2306 return " LIKE '" . $s . "' ";
2310 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2314 public function anyChar() {
2315 return new LikeMatch( '_' );
2319 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2323 public function anyString() {
2324 return new LikeMatch( '%' );
2328 * Returns an appropriately quoted sequence value for inserting a new row.
2329 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2330 * subclass will return an integer, and save the value for insertId()
2332 * Any implementation of this function should *not* involve reusing
2333 * sequence numbers created for rolled-back transactions.
2334 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2335 * @param $seqName string
2338 public function nextSequenceValue( $seqName ) {
2343 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2344 * is only needed because a) MySQL must be as efficient as possible due to
2345 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2346 * which index to pick. Anyway, other databases might have different
2347 * indexes on a given table. So don't bother overriding this unless you're
2352 public function useIndexClause( $index ) {
2357 * REPLACE query wrapper.
2359 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2360 * except that when there is a duplicate key error, the old row is deleted
2361 * and the new row is inserted in its place.
2363 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2364 * perform the delete, we need to know what the unique indexes are so that
2365 * we know how to find the conflicting rows.
2367 * It may be more efficient to leave off unique indexes which are unlikely
2368 * to collide. However if you do this, you run the risk of encountering
2369 * errors which wouldn't have occurred in MySQL.
2371 * @param $table String: The table to replace the row(s) in.
2372 * @param $rows array Can be either a single row to insert, or multiple rows,
2373 * in the same format as for DatabaseBase::insert()
2374 * @param $uniqueIndexes array is an array of indexes. Each element may be either
2375 * a field name or an array of field names
2376 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
2378 public function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
2379 $quotedTable = $this->tableName( $table );
2381 if ( count( $rows ) == 0 ) {
2386 if ( !is_array( reset( $rows ) ) ) {
2387 $rows = array( $rows );
2390 foreach( $rows as $row ) {
2391 # Delete rows which collide
2392 if ( $uniqueIndexes ) {
2393 $sql = "DELETE FROM $quotedTable WHERE ";
2395 foreach ( $uniqueIndexes as $index ) {
2402 if ( is_array( $index ) ) {
2404 foreach ( $index as $col ) {
2410 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2413 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2417 $this->query( $sql, $fname );
2420 # Now insert the row
2421 $this->insert( $table, $row );
2426 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2429 * @param $table string Table name
2430 * @param $rows array Rows to insert
2431 * @param $fname string Caller function name
2433 * @return ResultWrapper
2435 protected function nativeReplace( $table, $rows, $fname ) {
2436 $table = $this->tableName( $table );
2439 if ( !is_array( reset( $rows ) ) ) {
2440 $rows = array( $rows );
2443 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2446 foreach ( $rows as $row ) {
2453 $sql .= '(' . $this->makeList( $row ) . ')';
2456 return $this->query( $sql, $fname );
2460 * DELETE where the condition is a join.
2462 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2463 * we use sub-selects
2465 * For safety, an empty $conds will not delete everything. If you want to
2466 * delete all rows where the join condition matches, set $conds='*'.
2468 * DO NOT put the join condition in $conds.
2470 * @param $delTable String: The table to delete from.
2471 * @param $joinTable String: The other table.
2472 * @param $delVar String: The variable to join on, in the first table.
2473 * @param $joinVar String: The variable to join on, in the second table.
2474 * @param $conds Array: Condition array of field names mapped to variables,
2475 * ANDed together in the WHERE clause
2476 * @param $fname String: Calling function name (use __METHOD__) for
2478 * @throws DBUnexpectedError
2480 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2481 $fname = 'DatabaseBase::deleteJoin' )
2484 throw new DBUnexpectedError( $this,
2485 'DatabaseBase::deleteJoin() called with empty $conds' );
2488 $delTable = $this->tableName( $delTable );
2489 $joinTable = $this->tableName( $joinTable );
2490 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2491 if ( $conds != '*' ) {
2492 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2496 $this->query( $sql, $fname );
2500 * Returns the size of a text field, or -1 for "unlimited"
2502 * @param $table string
2503 * @param $field string
2507 public function textFieldSize( $table, $field ) {
2508 $table = $this->tableName( $table );
2509 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2510 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2511 $row = $this->fetchObject( $res );
2515 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2525 * A string to insert into queries to show that they're low-priority, like
2526 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2527 * string and nothing bad should happen.
2529 * @return string Returns the text of the low priority option if it is
2530 * supported, or a blank string otherwise
2532 public function lowPriorityOption() {
2537 * DELETE query wrapper.
2539 * @param $table Array Table name
2540 * @param $conds String|Array of conditions. See $conds in DatabaseBase::select() for
2541 * the format. Use $conds == "*" to delete all rows
2542 * @param $fname String name of the calling function
2544 * @throws DBUnexpectedError
2547 public function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
2549 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2552 $table = $this->tableName( $table );
2553 $sql = "DELETE FROM $table";
2555 if ( $conds != '*' ) {
2556 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2559 return $this->query( $sql, $fname );
2563 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2564 * into another table.
2566 * @param $destTable string The table name to insert into
2567 * @param $srcTable string|array May be either a table name, or an array of table names
2568 * to include in a join.
2570 * @param $varMap array must be an associative array of the form
2571 * array( 'dest1' => 'source1', ...). Source items may be literals
2572 * rather than field names, but strings should be quoted with
2573 * DatabaseBase::addQuotes()
2575 * @param $conds array Condition array. See $conds in DatabaseBase::select() for
2576 * the details of the format of condition arrays. May be "*" to copy the
2579 * @param $fname string The function name of the caller, from __METHOD__
2581 * @param $insertOptions array Options for the INSERT part of the query, see
2582 * DatabaseBase::insert() for details.
2583 * @param $selectOptions array Options for the SELECT part of the query, see
2584 * DatabaseBase::select() for details.
2586 * @return ResultWrapper
2588 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2589 $fname = 'DatabaseBase::insertSelect',
2590 $insertOptions = array(), $selectOptions = array() )
2592 $destTable = $this->tableName( $destTable );
2594 if ( is_array( $insertOptions ) ) {
2595 $insertOptions = implode( ' ', $insertOptions );
2598 if ( !is_array( $selectOptions ) ) {
2599 $selectOptions = array( $selectOptions );
2602 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2604 if ( is_array( $srcTable ) ) {
2605 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2607 $srcTable = $this->tableName( $srcTable );
2610 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2611 " SELECT $startOpts " . implode( ',', $varMap ) .
2612 " FROM $srcTable $useIndex ";
2614 if ( $conds != '*' ) {
2615 if ( is_array( $conds ) ) {
2616 $conds = $this->makeList( $conds, LIST_AND
);
2618 $sql .= " WHERE $conds";
2621 $sql .= " $tailOpts";
2623 return $this->query( $sql, $fname );
2627 * Construct a LIMIT query with optional offset. This is used for query
2628 * pages. The SQL should be adjusted so that only the first $limit rows
2629 * are returned. If $offset is provided as well, then the first $offset
2630 * rows should be discarded, and the next $limit rows should be returned.
2631 * If the result of the query is not ordered, then the rows to be returned
2632 * are theoretically arbitrary.
2634 * $sql is expected to be a SELECT, if that makes a difference.
2636 * The version provided by default works in MySQL and SQLite. It will very
2637 * likely need to be overridden for most other DBMSes.
2639 * @param $sql String SQL query we will append the limit too
2640 * @param $limit Integer the SQL limit
2641 * @param $offset Integer|bool the SQL offset (default false)
2643 * @throws DBUnexpectedError
2646 public function limitResult( $sql, $limit, $offset = false ) {
2647 if ( !is_numeric( $limit ) ) {
2648 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2650 return "$sql LIMIT "
2651 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2656 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2657 * within the UNION construct.
2660 public function unionSupportsOrderAndLimit() {
2661 return true; // True for almost every DB supported
2665 * Construct a UNION query
2666 * This is used for providing overload point for other DB abstractions
2667 * not compatible with the MySQL syntax.
2668 * @param $sqls Array: SQL statements to combine
2669 * @param $all Boolean: use UNION ALL
2670 * @return String: SQL fragment
2672 public function unionQueries( $sqls, $all ) {
2673 $glue = $all ?
') UNION ALL (' : ') UNION (';
2674 return '(' . implode( $glue, $sqls ) . ')';
2678 * Returns an SQL expression for a simple conditional. This doesn't need
2679 * to be overridden unless CASE isn't supported in your DBMS.
2681 * @param $cond string|array SQL expression which will result in a boolean value
2682 * @param $trueVal String: SQL expression to return if true
2683 * @param $falseVal String: SQL expression to return if false
2684 * @return String: SQL fragment
2686 public function conditional( $cond, $trueVal, $falseVal ) {
2687 if ( is_array( $cond ) ) {
2688 $cond = $this->makeList( $cond, LIST_AND
);
2690 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2694 * Returns a comand for str_replace function in SQL query.
2695 * Uses REPLACE() in MySQL
2697 * @param $orig String: column to modify
2698 * @param $old String: column to seek
2699 * @param $new String: column to replace with
2703 public function strreplace( $orig, $old, $new ) {
2704 return "REPLACE({$orig}, {$old}, {$new})";
2708 * Determines how long the server has been up
2713 public function getServerUptime() {
2718 * Determines if the last failure was due to a deadlock
2723 public function wasDeadlock() {
2728 * Determines if the last failure was due to a lock timeout
2733 public function wasLockTimeout() {
2738 * Determines if the last query error was something that should be dealt
2739 * with by pinging the connection and reissuing the query.
2744 public function wasErrorReissuable() {
2749 * Determines if the last failure was due to the database being read-only.
2754 public function wasReadOnlyError() {
2759 * Perform a deadlock-prone transaction.
2761 * This function invokes a callback function to perform a set of write
2762 * queries. If a deadlock occurs during the processing, the transaction
2763 * will be rolled back and the callback function will be called again.
2766 * $dbw->deadlockLoop( callback, ... );
2768 * Extra arguments are passed through to the specified callback function.
2770 * Returns whatever the callback function returned on its successful,
2771 * iteration, or false on error, for example if the retry limit was
2776 public function deadlockLoop() {
2777 $this->begin( __METHOD__
);
2778 $args = func_get_args();
2779 $function = array_shift( $args );
2780 $oldIgnore = $this->ignoreErrors( true );
2781 $tries = DEADLOCK_TRIES
;
2783 if ( is_array( $function ) ) {
2784 $fname = $function[0];
2790 $retVal = call_user_func_array( $function, $args );
2791 $error = $this->lastError();
2792 $errno = $this->lastErrno();
2793 $sql = $this->lastQuery();
2796 if ( $this->wasDeadlock() ) {
2798 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
2800 $this->reportQueryError( $error, $errno, $sql, $fname );
2803 } while ( $this->wasDeadlock() && --$tries > 0 );
2805 $this->ignoreErrors( $oldIgnore );
2807 if ( $tries <= 0 ) {
2808 $this->rollback( __METHOD__
);
2809 $this->reportQueryError( $error, $errno, $sql, $fname );
2812 $this->commit( __METHOD__
);
2818 * Wait for the slave to catch up to a given master position.
2820 * @param $pos DBMasterPos object
2821 * @param $timeout Integer: the maximum number of seconds to wait for
2824 * @return integer: zero if the slave was past that position already,
2825 * greater than zero if we waited for some period of time, less than
2826 * zero if we timed out.
2828 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2829 wfProfileIn( __METHOD__
);
2831 if ( !is_null( $this->mFakeSlaveLag
) ) {
2832 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
2834 if ( $wait > $timeout * 1e6
) {
2835 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2836 wfProfileOut( __METHOD__
);
2838 } elseif ( $wait > 0 ) {
2839 wfDebug( "Fake slave waiting $wait us\n" );
2841 wfProfileOut( __METHOD__
);
2844 wfDebug( "Fake slave up to date ($wait us)\n" );
2845 wfProfileOut( __METHOD__
);
2850 wfProfileOut( __METHOD__
);
2852 # Real waits are implemented in the subclass.
2857 * Get the replication position of this slave
2859 * @return DBMasterPos, or false if this is not a slave.
2861 public function getSlavePos() {
2862 if ( !is_null( $this->mFakeSlaveLag
) ) {
2863 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
2864 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
2873 * Get the position of this master
2875 * @return DBMasterPos, or false if this is not a master
2877 public function getMasterPos() {
2878 if ( $this->mFakeMaster
) {
2879 return new MySQLMasterPos( 'fake', microtime( true ) );
2886 * Run an anonymous function as soon as there is no transaction pending.
2887 * If there is a transaction and it is rolled back, then the callback is cancelled.
2888 * Callbacks must commit any transactions that they begin.
2890 * This is useful for updates to different systems or separate transactions are needed.
2894 * @param Closure $callback
2896 final public function onTransactionIdle( Closure
$callback ) {
2897 if ( $this->mTrxLevel
) {
2898 $this->trxIdleCallbacks
[] = $callback;
2905 * Actually run the "on transaction idle" callbacks.
2909 protected function runOnTransactionIdleCallbacks() {
2910 $e = null; // last exception
2911 do { // callbacks may add callbacks :)
2912 $callbacks = $this->trxIdleCallbacks
;
2913 $this->trxIdleCallbacks
= array(); // recursion guard
2914 foreach ( $callbacks as $callback ) {
2917 } catch ( Exception
$e ) {}
2919 } while ( count( $this->trxIdleCallbacks
) );
2921 if ( $e instanceof Exception
) {
2922 throw $e; // re-throw any last exception
2927 * Begin a transaction. If a transaction is already in progress, that transaction will be committed before the
2928 * new transaction is started.
2930 * Note that when the DBO_TRX flag is set (which is usually the case for web requests, but not for maintenance scripts),
2931 * any previous database query will have started a transaction automatically.
2933 * Nesting of transactions is not supported. Attempts to nest transactions will cause a warning, unless the current
2934 * transaction was started automatically because of the DBO_TRX flag.
2936 * @param $fname string
2938 final public function begin( $fname = 'DatabaseBase::begin' ) {
2939 global $wgDebugDBTransactions;
2941 if ( $this->mTrxLevel
) { // implicit commit
2942 if ( !$this->mTrxAutomatic
) {
2943 // We want to warn about inadvertently nested begin/commit pairs, but not about auto-committing
2944 // implicit transactions that were started by query() because DBO_TRX was set.
2946 wfWarn( "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
2947 " performing implicit commit!" );
2949 // if the transaction was automatic and has done write operations,
2950 // log it if $wgDebugDBTransactions is enabled.
2952 if ( $this->mTrxDoneWrites
&& $wgDebugDBTransactions ) {
2953 wfDebug( "$fname: Automatic transaction with writes in progress (from {$this->mTrxFname}), " .
2954 " performing implicit commit!\n" );
2958 $this->doCommit( $fname );
2959 $this->runOnTransactionIdleCallbacks();
2962 $this->doBegin( $fname );
2963 $this->mTrxFname
= $fname;
2964 $this->mTrxDoneWrites
= false;
2965 $this->mTrxAutomatic
= false;
2969 * Issues the BEGIN command to the database server.
2971 * @see DatabaseBase::begin()
2972 * @param type $fname
2974 protected function doBegin( $fname ) {
2975 $this->query( 'BEGIN', $fname );
2976 $this->mTrxLevel
= 1;
2980 * Commits a transaction previously started using begin().
2981 * If no transaction is in progress, a warning is issued.
2983 * Nesting of transactions is not supported.
2985 * @param $fname string
2987 final public function commit( $fname = 'DatabaseBase::commit' ) {
2988 if ( !$this->mTrxLevel
) {
2989 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
2990 } elseif( $this->mTrxAutomatic
) {
2991 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
2994 $this->doCommit( $fname );
2995 $this->runOnTransactionIdleCallbacks();
2999 * Issues the COMMIT command to the database server.
3001 * @see DatabaseBase::commit()
3002 * @param type $fname
3004 protected function doCommit( $fname ) {
3005 if ( $this->mTrxLevel
) {
3006 $this->query( 'COMMIT', $fname );
3007 $this->mTrxLevel
= 0;
3012 * Rollback a transaction previously started using begin().
3013 * If no transaction is in progress, a warning is issued.
3015 * No-op on non-transactional databases.
3017 * @param $fname string
3019 final public function rollback( $fname = 'DatabaseBase::rollback' ) {
3020 if ( !$this->mTrxLevel
) {
3021 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3023 $this->doRollback( $fname );
3024 $this->trxIdleCallbacks
= array(); // cancel
3028 * Issues the ROLLBACK command to the database server.
3030 * @see DatabaseBase::rollback()
3031 * @param type $fname
3033 protected function doRollback( $fname ) {
3034 if ( $this->mTrxLevel
) {
3035 $this->query( 'ROLLBACK', $fname, true );
3036 $this->mTrxLevel
= 0;
3041 * Creates a new table with structure copied from existing table
3042 * Note that unlike most database abstraction functions, this function does not
3043 * automatically append database prefix, because it works at a lower
3044 * abstraction level.
3045 * The table names passed to this function shall not be quoted (this
3046 * function calls addIdentifierQuotes when needed).
3048 * @param $oldName String: name of table whose structure should be copied
3049 * @param $newName String: name of table to be created
3050 * @param $temporary Boolean: whether the new table should be temporary
3051 * @param $fname String: calling function name
3052 * @throws MWException
3053 * @return Boolean: true if operation was successful
3055 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3056 $fname = 'DatabaseBase::duplicateTableStructure' )
3058 throw new MWException(
3059 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3063 * List all tables on the database
3065 * @param $prefix string Only show tables with this prefix, e.g. mw_
3066 * @param $fname String: calling function name
3067 * @throws MWException
3069 function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
3070 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3074 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3075 * to the format used for inserting into timestamp fields in this DBMS.
3077 * The result is unquoted, and needs to be passed through addQuotes()
3078 * before it can be included in raw SQL.
3080 * @param $ts string|int
3084 public function timestamp( $ts = 0 ) {
3085 return wfTimestamp( TS_MW
, $ts );
3089 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3090 * to the format used for inserting into timestamp fields in this DBMS. If
3091 * NULL is input, it is passed through, allowing NULL values to be inserted
3092 * into timestamp fields.
3094 * The result is unquoted, and needs to be passed through addQuotes()
3095 * before it can be included in raw SQL.
3097 * @param $ts string|int
3101 public function timestampOrNull( $ts = null ) {
3102 if ( is_null( $ts ) ) {
3105 return $this->timestamp( $ts );
3110 * Take the result from a query, and wrap it in a ResultWrapper if
3111 * necessary. Boolean values are passed through as is, to indicate success
3112 * of write queries or failure.
3114 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3115 * resource, and it was necessary to call this function to convert it to
3116 * a wrapper. Nowadays, raw database objects are never exposed to external
3117 * callers, so this is unnecessary in external code. For compatibility with
3118 * old code, ResultWrapper objects are passed through unaltered.
3120 * @param $result bool|ResultWrapper
3122 * @return bool|ResultWrapper
3124 public function resultObject( $result ) {
3125 if ( empty( $result ) ) {
3127 } elseif ( $result instanceof ResultWrapper
) {
3129 } elseif ( $result === true ) {
3130 // Successful write query
3133 return new ResultWrapper( $this, $result );
3138 * Ping the server and try to reconnect if it there is no connection
3140 * @return bool Success or failure
3142 public function ping() {
3143 # Stub. Not essential to override.
3148 * Get slave lag. Currently supported only by MySQL.
3150 * Note that this function will generate a fatal error on many
3151 * installations. Most callers should use LoadBalancer::safeGetLag()
3154 * @return int Database replication lag in seconds
3156 public function getLag() {
3157 return intval( $this->mFakeSlaveLag
);
3161 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3165 function maxListLen() {
3170 * Some DBMSs have a special format for inserting into blob fields, they
3171 * don't allow simple quoted strings to be inserted. To insert into such
3172 * a field, pass the data through this function before passing it to
3173 * DatabaseBase::insert().
3177 public function encodeBlob( $b ) {
3182 * Some DBMSs return a special placeholder object representing blob fields
3183 * in result objects. Pass the object through this function to return the
3188 public function decodeBlob( $b ) {
3193 * Override database's default behavior. $options include:
3194 * 'connTimeout' : Set the connection timeout value in seconds.
3195 * May be useful for very long batch queries such as
3196 * full-wiki dumps, where a single query reads out over
3199 * @param $options Array
3202 public function setSessionOptions( array $options ) {}
3205 * Read and execute SQL commands from a file.
3207 * Returns true on success, error string or exception on failure (depending
3208 * on object's error ignore settings).
3210 * @param $filename String: File name to open
3211 * @param bool|callable $lineCallback Optional function called before reading each line
3212 * @param bool|callable $resultCallback Optional function called for each MySQL result
3213 * @param bool|string $fname Calling function name or false if name should be
3214 * generated dynamically using $filename
3215 * @throws MWException
3216 * @return bool|string
3218 public function sourceFile(
3219 $filename, $lineCallback = false, $resultCallback = false, $fname = false
3221 wfSuppressWarnings();
3222 $fp = fopen( $filename, 'r' );
3223 wfRestoreWarnings();
3225 if ( false === $fp ) {
3226 throw new MWException( "Could not open \"{$filename}\".\n" );
3230 $fname = __METHOD__
. "( $filename )";
3234 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
3236 catch ( MWException
$e ) {
3247 * Get the full path of a patch file. Originally based on archive()
3248 * from updaters.inc. Keep in mind this always returns a patch, as
3249 * it fails back to MySQL if no DB-specific patch can be found
3251 * @param $patch String The name of the patch, like patch-something.sql
3252 * @return String Full path to patch file
3254 public function patchPath( $patch ) {
3257 $dbType = $this->getType();
3258 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3259 return "$IP/maintenance/$dbType/archives/$patch";
3261 return "$IP/maintenance/archives/$patch";
3266 * Set variables to be used in sourceFile/sourceStream, in preference to the
3267 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3268 * all. If it's set to false, $GLOBALS will be used.
3270 * @param $vars bool|array mapping variable name to value.
3272 public function setSchemaVars( $vars ) {
3273 $this->mSchemaVars
= $vars;
3277 * Read and execute commands from an open file handle.
3279 * Returns true on success, error string or exception on failure (depending
3280 * on object's error ignore settings).
3282 * @param $fp Resource: File handle
3283 * @param $lineCallback Callback: Optional function called before reading each line
3284 * @param $resultCallback Callback: Optional function called for each MySQL result
3285 * @param $fname String: Calling function name
3286 * @param $inputCallback Callback: Optional function called for each complete line (ended with ;) sent
3287 * @return bool|string
3289 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3290 $fname = 'DatabaseBase::sourceStream', $inputCallback = false )
3294 while ( !feof( $fp ) ) {
3295 if ( $lineCallback ) {
3296 call_user_func( $lineCallback );
3299 $line = trim( fgets( $fp ) );
3301 if ( $line == '' ) {
3305 if ( '-' == $line[0] && '-' == $line[1] ) {
3313 $done = $this->streamStatementEnd( $cmd, $line );
3317 if ( $done ||
feof( $fp ) ) {
3318 $cmd = $this->replaceVars( $cmd );
3319 if ( $inputCallback ) {
3320 call_user_func( $inputCallback, $cmd );
3322 $res = $this->query( $cmd, $fname );
3324 if ( $resultCallback ) {
3325 call_user_func( $resultCallback, $res, $this );
3328 if ( false === $res ) {
3329 $err = $this->lastError();
3330 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3341 * Called by sourceStream() to check if we've reached a statement end
3343 * @param $sql String SQL assembled so far
3344 * @param $newLine String New line about to be added to $sql
3345 * @return Bool Whether $newLine contains end of the statement
3347 public function streamStatementEnd( &$sql, &$newLine ) {
3348 if ( $this->delimiter
) {
3350 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3351 if ( $newLine != $prev ) {
3359 * Database independent variable replacement. Replaces a set of variables
3360 * in an SQL statement with their contents as given by $this->getSchemaVars().
3362 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3364 * - '{$var}' should be used for text and is passed through the database's
3366 * - `{$var}` should be used for identifiers (eg: table and database names),
3367 * it is passed through the database's addIdentifierQuotes method which
3368 * can be overridden if the database uses something other than backticks.
3369 * - / *$var* / is just encoded, besides traditional table prefix and
3370 * table options its use should be avoided.
3372 * @param $ins String: SQL statement to replace variables in
3373 * @return String The new SQL statement with variables replaced
3375 protected function replaceSchemaVars( $ins ) {
3376 $vars = $this->getSchemaVars();
3377 foreach ( $vars as $var => $value ) {
3379 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
3381 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
3383 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
3389 * Replace variables in sourced SQL
3391 * @param $ins string
3395 protected function replaceVars( $ins ) {
3396 $ins = $this->replaceSchemaVars( $ins );
3399 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3400 array( $this, 'tableNameCallback' ), $ins );
3403 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
3404 array( $this, 'indexNameCallback' ), $ins );
3410 * Get schema variables. If none have been set via setSchemaVars(), then
3411 * use some defaults from the current object.
3415 protected function getSchemaVars() {
3416 if ( $this->mSchemaVars
) {
3417 return $this->mSchemaVars
;
3419 return $this->getDefaultSchemaVars();
3424 * Get schema variables to use if none have been set via setSchemaVars().
3426 * Override this in derived classes to provide variables for tables.sql
3427 * and SQL patch files.
3431 protected function getDefaultSchemaVars() {
3436 * Table name callback
3438 * @param $matches array
3442 protected function tableNameCallback( $matches ) {
3443 return $this->tableName( $matches[1] );
3447 * Index name callback
3449 * @param $matches array
3453 protected function indexNameCallback( $matches ) {
3454 return $this->indexName( $matches[1] );
3458 * Check to see if a named lock is available. This is non-blocking.
3460 * @param $lockName String: name of lock to poll
3461 * @param $method String: name of method calling us
3465 public function lockIsFree( $lockName, $method ) {
3470 * Acquire a named lock
3472 * Abstracted from Filestore::lock() so child classes can implement for
3475 * @param $lockName String: name of lock to aquire
3476 * @param $method String: name of method calling us
3477 * @param $timeout Integer: timeout
3480 public function lock( $lockName, $method, $timeout = 5 ) {
3487 * @param $lockName String: Name of lock to release
3488 * @param $method String: Name of method calling us
3490 * @return int Returns 1 if the lock was released, 0 if the lock was not established
3491 * by this thread (in which case the lock is not released), and NULL if the named
3492 * lock did not exist
3494 public function unlock( $lockName, $method ) {
3499 * Lock specific tables
3501 * @param $read Array of tables to lock for read access
3502 * @param $write Array of tables to lock for write access
3503 * @param $method String name of caller
3504 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
3508 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3513 * Unlock specific tables
3515 * @param $method String the caller
3519 public function unlockTables( $method ) {
3525 * @param $tableName string
3526 * @param $fName string
3527 * @return bool|ResultWrapper
3530 public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
3531 if( !$this->tableExists( $tableName, $fName ) ) {
3534 $sql = "DROP TABLE " . $this->tableName( $tableName );
3535 if( $this->cascadingDeletes() ) {
3538 return $this->query( $sql, $fName );
3542 * Get search engine class. All subclasses of this need to implement this
3543 * if they wish to use searching.
3547 public function getSearchEngine() {
3548 return 'SearchEngineDummy';
3552 * Find out when 'infinity' is. Most DBMSes support this. This is a special
3553 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
3554 * because "i" sorts after all numbers.
3558 public function getInfinity() {
3563 * Encode an expiry time into the DBMS dependent format
3565 * @param $expiry String: timestamp for expiry, or the 'infinity' string
3568 public function encodeExpiry( $expiry ) {
3569 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3570 ?
$this->getInfinity()
3571 : $this->timestamp( $expiry );
3575 * Decode an expiry time into a DBMS independent format
3577 * @param $expiry String: DB timestamp field value for expiry
3578 * @param $format integer: TS_* constant, defaults to TS_MW
3581 public function decodeExpiry( $expiry, $format = TS_MW
) {
3582 return ( $expiry == '' ||
$expiry == $this->getInfinity() )
3584 : wfTimestamp( $format, $expiry );
3588 * Allow or deny "big selects" for this session only. This is done by setting
3589 * the sql_big_selects session variable.
3591 * This is a MySQL-specific feature.
3593 * @param $value Mixed: true for allow, false for deny, or "default" to
3594 * restore the initial value
3596 public function setBigSelects( $value = true ) {
3603 public function __toString() {
3604 return (string)$this->mConn
;