8dc2a76397659edeaca799674955b4138df19925
3 * @defgroup Database Database
7 * This file deals with database interface functions
8 * and query specifics/optimisations
11 /** Number of times to re-try an operation in case of deadlock */
12 define( 'DEADLOCK_TRIES', 4 );
13 /** Minimum time to wait before retry, in microseconds */
14 define( 'DEADLOCK_DELAY_MIN', 500000 );
15 /** Maximum time to wait before retry */
16 define( 'DEADLOCK_DELAY_MAX', 1500000 );
19 * Base interface for all DBMS-specific code. At a bare minimum, all of the
20 * following must be implemented to support MediaWiki
25 interface DatabaseType
{
27 * Get the type of the DBMS, as it appears in $wgDBtype.
34 * Open a connection to the database. Usually aborts on failure
36 * @param $server String: database server host
37 * @param $user String: database user name
38 * @param $password String: database user password
39 * @param $dbName String: database name
41 * @throws DBConnectionError
43 function open( $server, $user, $password, $dbName );
46 * The DBMS-dependent part of query()
47 * @todo FIXME: Make this private someday
49 * @param $sql String: SQL query.
50 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
53 function doQuery( $sql );
56 * Fetch the next row from the given result object, in object form.
57 * Fields can be retrieved with $row->fieldname, with fields acting like
60 * @param $res SQL result object as returned from DatabaseBase::query(), etc.
62 * @throws DBUnexpectedError Thrown if the database returns an error
64 function fetchObject( $res );
67 * Fetch the next row from the given result object, in associative array
68 * form. Fields are retrieved with $row['fieldname'].
70 * @param $res ResultWrapper result object as returned from DatabaseBase::query(), etc.
72 * @throws DBUnexpectedError Thrown if the database returns an error
74 function fetchRow( $res );
77 * Get the number of rows in a result object
79 * @param $res Mixed: A SQL result
82 function numRows( $res );
85 * Get the number of fields in a result object
86 * @see http://www.php.net/mysql_num_fields
88 * @param $res Mixed: A SQL result
91 function numFields( $res );
94 * Get a field name in a result object
95 * @see http://www.php.net/mysql_field_name
97 * @param $res Mixed: A SQL result
101 function fieldName( $res, $n );
104 * Get the inserted value of an auto-increment row
106 * The value inserted should be fetched from nextSequenceValue()
109 * $id = $dbw->nextSequenceValue('page_page_id_seq');
110 * $dbw->insert('page',array('page_id' => $id));
111 * $id = $dbw->insertId();
118 * Change the position of the cursor in a result object
119 * @see http://www.php.net/mysql_data_seek
121 * @param $res Mixed: A SQL result
122 * @param $row Mixed: Either MySQL row or ResultWrapper
124 function dataSeek( $res, $row );
127 * Get the last error number
128 * @see http://www.php.net/mysql_errno
132 function lastErrno();
135 * Get a description of the last error
136 * @see http://www.php.net/mysql_error
140 function lastError();
143 * mysql_fetch_field() wrapper
144 * Returns false if the field doesn't exist
146 * @param $table string: table name
147 * @param $field string: field name
151 function fieldInfo( $table, $field );
154 * Get information about an index into an object
155 * @param $table string: Table name
156 * @param $index string: Index name
157 * @param $fname string: Calling function name
158 * @return Mixed: Database-specific index description class or false if the index does not exist
160 function indexInfo( $table, $index, $fname = 'Database::indexInfo' );
163 * Get the number of rows affected by the last write query
164 * @see http://www.php.net/mysql_affected_rows
168 function affectedRows();
171 * Wrapper for addslashes()
173 * @param $s string: to be slashed.
174 * @return string: slashed string.
176 function strencode( $s );
179 * Returns a wikitext link to the DB's website, e.g.,
180 * return "[http://www.mysql.com/ MySQL]";
181 * Should at least contain plain text, if for some reason
182 * your database has no website.
184 * @return string: wikitext of a link to the server software's web site
186 static function getSoftwareLink();
189 * A string describing the current software version, like from
190 * mysql_get_server_info().
192 * @return string: Version information from the database server.
194 function getServerVersion();
197 * A string describing the current software version, and possibly
198 * other details in a user-friendly way. Will be listed on Special:Version, etc.
199 * Use getServerVersion() to get machine-friendly information.
201 * @return string: Version information from the database server
203 function getServerInfo();
207 * Database abstraction object
210 abstract class DatabaseBase
implements DatabaseType
{
212 # ------------------------------------------------------------------------------
214 # ------------------------------------------------------------------------------
216 protected $mLastQuery = '';
217 protected $mDoneWrites = false;
218 protected $mPHPError = false;
220 protected $mServer, $mUser, $mPassword, $mDBname;
225 protected $mConn = null;
226 protected $mOpened = false;
228 protected $mTablePrefix;
230 protected $mTrxLevel = 0;
231 protected $mErrorCount = 0;
232 protected $mLBInfo = array();
233 protected $mFakeSlaveLag = null, $mFakeMaster = false;
234 protected $mDefaultBigSelects = null;
235 protected $mSchemaVars = false;
237 # ------------------------------------------------------------------------------
239 # ------------------------------------------------------------------------------
240 # These optionally set a variable and return the previous state
243 * A string describing the current software version, and possibly
244 * other details in a user-friendly way. Will be listed on Special:Version, etc.
245 * Use getServerVersion() to get machine-friendly information.
247 * @return string: Version information from the database server
249 public function getServerInfo() {
250 return $this->getServerVersion();
254 * Boolean, controls output of large amounts of debug information
256 function debug( $debug = null ) {
257 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
261 * Turns buffering of SQL result sets on (true) or off (false).
262 * Default is "on" and it should not be changed without good reasons.
266 function bufferResults( $buffer = null ) {
267 if ( is_null( $buffer ) ) {
268 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
270 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
275 * Turns on (false) or off (true) the automatic generation and sending
276 * of a "we're sorry, but there has been a database error" page on
277 * database errors. Default is on (false). When turned off, the
278 * code should use lastErrno() and lastError() to handle the
279 * situation as appropriate.
281 function ignoreErrors( $ignoreErrors = null ) {
282 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
286 * The current depth of nested transactions
287 * @param $level Integer: , default NULL.
289 function trxLevel( $level = null ) {
290 return wfSetVar( $this->mTrxLevel
, $level );
294 * Number of errors logged, only useful when errors are ignored
296 function errorCount( $count = null ) {
297 return wfSetVar( $this->mErrorCount
, $count );
300 function tablePrefix( $prefix = null ) {
301 return wfSetVar( $this->mTablePrefix
, $prefix, true );
305 * Properties passed down from the server info array of the load balancer
307 function getLBInfo( $name = null ) {
308 if ( is_null( $name ) ) {
309 return $this->mLBInfo
;
311 if ( array_key_exists( $name, $this->mLBInfo
) ) {
312 return $this->mLBInfo
[$name];
324 function setLBInfo( $name, $value = null ) {
325 if ( is_null( $value ) ) {
326 $this->mLBInfo
= $name;
328 $this->mLBInfo
[$name] = $value;
333 * Set lag time in seconds for a fake slave
335 function setFakeSlaveLag( $lag ) {
336 $this->mFakeSlaveLag
= $lag;
340 * Make this connection a fake master
342 function setFakeMaster( $enabled = true ) {
343 $this->mFakeMaster
= $enabled;
347 * Returns true if this database supports (and uses) cascading deletes
349 function cascadingDeletes() {
354 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
356 function cleanupTriggers() {
361 * Returns true if this database is strict about what can be put into an IP field.
362 * Specifically, it uses a NULL value instead of an empty string.
364 function strictIPs() {
369 * Returns true if this database uses timestamps rather than integers
371 function realTimestamps() {
376 * Returns true if this database does an implicit sort when doing GROUP BY
378 function implicitGroupby() {
383 * Returns true if this database does an implicit order by when the column has an index
384 * For example: SELECT page_title FROM page LIMIT 1
386 function implicitOrderby() {
391 * Returns true if this database requires that SELECT DISTINCT queries require that all
392 ORDER BY expressions occur in the SELECT list per the SQL92 standard
394 function standardSelectDistinct() {
399 * Returns true if this database can do a native search on IP columns
400 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
402 function searchableIPs() {
407 * Returns true if this database can use functional indexes
409 function functionalIndexes() {
414 * Return the last query that went through DatabaseBase::query()
417 function lastQuery() {
418 return $this->mLastQuery
;
423 * Returns true if the connection may have been used for write queries.
424 * Should return true if unsure.
428 function doneWrites() {
429 return $this->mDoneWrites
;
433 * Is a connection to the database open?
437 return $this->mOpened
;
441 * Set a flag for this connection
443 * @param $flag Integer: DBO_* constants from Defines.php:
444 * - DBO_DEBUG: output some debug info (same as debug())
445 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
446 * - DBO_IGNORE: ignore errors (same as ignoreErrors())
447 * - DBO_TRX: automatically start transactions
448 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
449 * and removes it in command line mode
450 * - DBO_PERSISTENT: use persistant database connection
452 function setFlag( $flag ) {
453 $this->mFlags |
= $flag;
457 * Clear a flag for this connection
459 * @param $flag: same as setFlag()'s $flag param
461 function clearFlag( $flag ) {
462 $this->mFlags
&= ~
$flag;
466 * Returns a boolean whether the flag $flag is set for this connection
468 * @param $flag: same as setFlag()'s $flag param
471 function getFlag( $flag ) {
472 return !!( $this->mFlags
& $flag );
476 * General read-only accessor
478 function getProperty( $name ) {
485 function getWikiID() {
486 if ( $this->mTablePrefix
) {
487 return "{$this->mDBname}-{$this->mTablePrefix}";
489 return $this->mDBname
;
494 * Return a path to the DBMS-specific schema, otherwise default to tables.sql
498 public function getSchema() {
500 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
501 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
503 return "$IP/maintenance/tables.sql";
507 # ------------------------------------------------------------------------------
509 # ------------------------------------------------------------------------------
513 * @param $server String: database server host
514 * @param $user String: database user name
515 * @param $password String: database user password
516 * @param $dbName String: database name
518 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
520 function __construct( $server = false, $user = false, $password = false, $dbName = false,
521 $flags = 0, $tablePrefix = 'get from global'
523 global $wgDBprefix, $wgCommandLineMode;
525 $this->mFlags
= $flags;
527 if ( $this->mFlags
& DBO_DEFAULT
) {
528 if ( $wgCommandLineMode ) {
529 $this->mFlags
&= ~DBO_TRX
;
531 $this->mFlags |
= DBO_TRX
;
535 /** Get the default table prefix*/
536 if ( $tablePrefix == 'get from global' ) {
537 $this->mTablePrefix
= $wgDBprefix;
539 $this->mTablePrefix
= $tablePrefix;
543 $this->open( $server, $user, $password, $dbName );
548 * Same as new DatabaseMysql( ... ), kept for backward compatibility
549 * @deprecated since 1.17
551 * @return DatabaseMysql
553 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
554 wfDeprecated( __METHOD__
);
555 return new DatabaseMysql( $server, $user, $password, $dbName, $flags );
559 * Given a DB type, construct the name of the appropriate child class of
560 * DatabaseBase. This is designed to replace all of the manual stuff like:
561 * $class = 'Database' . ucfirst( strtolower( $type ) );
562 * as well as validate against the canonical list of DB types we have
564 * This factory function is mostly useful for when you need to connect to a
565 * database other than the MediaWiki default (such as for external auth,
566 * an extension, et cetera). Do not use this to connect to the MediaWiki
567 * database. Example uses in core:
568 * @see LoadBalancer::reallyOpenConnection()
569 * @see ExternalUser_MediaWiki::initFromCond()
570 * @see ForeignDBRepo::getMasterDB()
571 * @see WebInstaller_DBConnect::execute()
573 * @param $dbType String A possible DB type
574 * @param $p Array An array of options to pass to the constructor.
575 * Valid options are: host, user, password, dbname, flags, tableprefix
576 * @return DatabaseBase subclass or null
578 public final static function newFromType( $dbType, $p = array() ) {
579 $canonicalDBTypes = array(
580 'mysql', 'postgres', 'sqlite', 'oracle', 'mssql', 'ibm_db2'
582 $dbType = strtolower( $dbType );
584 if( in_array( $dbType, $canonicalDBTypes ) ) {
585 $class = 'Database' . ucfirst( $dbType );
587 isset( $p['host'] ) ?
$p['host'] : false,
588 isset( $p['user'] ) ?
$p['user'] : false,
589 isset( $p['password'] ) ?
$p['password'] : false,
590 isset( $p['dbname'] ) ?
$p['dbname'] : false,
591 isset( $p['flags'] ) ?
$p['flags'] : 0,
592 isset( $p['tableprefix'] ) ?
$p['tableprefix'] : 'get from global'
599 protected function installErrorHandler() {
600 $this->mPHPError
= false;
601 $this->htmlErrors
= ini_set( 'html_errors', '0' );
602 set_error_handler( array( $this, 'connectionErrorHandler' ) );
605 protected function restoreErrorHandler() {
606 restore_error_handler();
607 if ( $this->htmlErrors
!== false ) {
608 ini_set( 'html_errors', $this->htmlErrors
);
610 if ( $this->mPHPError
) {
611 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
612 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
619 protected function connectionErrorHandler( $errno, $errstr ) {
620 $this->mPHPError
= $errstr;
624 * Closes a database connection.
625 * if it is open : commits any open transactions
627 * @return Bool operation success. true if already closed.
630 # Stub, should probably be overridden
635 * @param $error String: fallback error message, used if none is given by DB
637 function reportConnectionError( $error = 'Unknown error' ) {
638 $myError = $this->lastError();
644 throw new DBConnectionError( $this, $error );
648 * Determine whether a query writes to the DB.
649 * Should return true if unsure.
653 function isWriteQuery( $sql ) {
654 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
658 * Usually aborts on failure. If errors are explicitly ignored, returns success.
660 * @param $sql String: SQL query
661 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
662 * comment (you can use __METHOD__ or add some extra info)
663 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
664 * maybe best to catch the exception instead?
665 * @return boolean or ResultWrapper. true for a successful write query, ResultWrapper object for a successful read query,
666 * or false on failure if $tempIgnore set
667 * @throws DBQueryError Thrown when the database returns an error of any kind
669 public function query( $sql, $fname = '', $tempIgnore = false ) {
670 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
671 if ( !Profiler
::instance()->isStub() ) {
672 # generalizeSQL will probably cut down the query to reasonable
673 # logging size most of the time. The substr is really just a sanity check.
675 # Who's been wasting my precious column space? -- TS
676 # $profName = 'query: ' . $fname . ' ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
679 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
680 $totalProf = 'DatabaseBase::query-master';
682 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
683 $totalProf = 'DatabaseBase::query';
686 wfProfileIn( $totalProf );
687 wfProfileIn( $queryProf );
690 $this->mLastQuery
= $sql;
691 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
692 // Set a flag indicating that writes have been done
693 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
694 $this->mDoneWrites
= true;
697 # Add a comment for easy SHOW PROCESSLIST interpretation
700 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
701 $userName = $wgUser->getName();
702 if ( mb_strlen( $userName ) > 15 ) {
703 $userName = mb_substr( $userName, 0, 15 ) . '...';
705 $userName = str_replace( '/', '', $userName );
709 $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
711 # $commentedSql = $sql;
714 # If DBO_TRX is set, start a transaction
715 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
716 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
717 // avoid establishing transactions for SHOW and SET statements too -
718 // that would delay transaction initializations to once connection
719 // is really used by application
720 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
721 if ( strpos( $sqlstart, "SHOW " ) !== 0 and strpos( $sqlstart, "SET " ) !== 0 )
725 if ( $this->debug() ) {
729 $sqlx = substr( $commentedSql, 0, 500 );
730 $sqlx = strtr( $sqlx, "\t\n", ' ' );
733 wfDebug( "Query $cnt (master): $sqlx\n" );
735 wfDebug( "Query $cnt (slave): $sqlx\n" );
739 if ( istainted( $sql ) & TC_MYSQL
) {
740 throw new MWException( 'Tainted query found' );
743 # Do the query and handle errors
744 $ret = $this->doQuery( $commentedSql );
746 # Try reconnecting if the connection was lost
747 if ( false === $ret && $this->wasErrorReissuable() ) {
748 # Transaction is gone, like it or not
749 $this->mTrxLevel
= 0;
750 wfDebug( "Connection lost, reconnecting...\n" );
752 if ( $this->ping() ) {
753 wfDebug( "Reconnected\n" );
754 $sqlx = substr( $commentedSql, 0, 500 );
755 $sqlx = strtr( $sqlx, "\t\n", ' ' );
756 global $wgRequestTime;
757 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
758 if ( $elapsed < 300 ) {
759 # Not a database error to lose a transaction after a minute or two
760 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
762 $ret = $this->doQuery( $commentedSql );
764 wfDebug( "Failed\n" );
768 if ( false === $ret ) {
769 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
772 if ( !Profiler
::instance()->isStub() ) {
773 wfProfileOut( $queryProf );
774 wfProfileOut( $totalProf );
777 return $this->resultObject( $ret );
781 * @param $error String
782 * @param $errno Integer
784 * @param $fname String
785 * @param $tempIgnore Boolean
787 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
788 # Ignore errors during error handling to avoid infinite recursion
789 $ignore = $this->ignoreErrors( true );
790 ++
$this->mErrorCount
;
792 if ( $ignore ||
$tempIgnore ) {
793 wfDebug( "SQL ERROR (ignored): $error\n" );
794 $this->ignoreErrors( $ignore );
796 $sql1line = str_replace( "\n", "\\n", $sql );
797 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
798 wfDebug( "SQL ERROR: " . $error . "\n" );
799 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
805 * Intended to be compatible with the PEAR::DB wrapper functions.
806 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
808 * ? = scalar value, quoted as necessary
809 * ! = raw SQL bit (a function for instance)
810 * & = filename; reads the file and inserts as a blob
811 * (we don't use this though...)
815 function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
816 /* MySQL doesn't support prepared statements (yet), so just
817 pack up the query for reference. We'll manually replace
819 return array( 'query' => $sql, 'func' => $func );
822 function freePrepared( $prepared ) {
823 /* No-op by default */
827 * Execute a prepared query with the various arguments
828 * @param $prepared String: the prepared sql
829 * @param $args Mixed: Either an array here, or put scalars as varargs
831 * @return ResultWrapper
833 function execute( $prepared, $args = null ) {
834 if ( !is_array( $args ) ) {
836 $args = func_get_args();
837 array_shift( $args );
840 $sql = $this->fillPrepared( $prepared['query'], $args );
842 return $this->query( $sql, $prepared['func'] );
846 * Prepare & execute an SQL statement, quoting and inserting arguments
847 * in the appropriate places.
848 * @param $query String
851 * @return ResultWrapper
853 function safeQuery( $query, $args = null ) {
854 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
856 if ( !is_array( $args ) ) {
858 $args = func_get_args();
859 array_shift( $args );
862 $retval = $this->execute( $prepared, $args );
863 $this->freePrepared( $prepared );
869 * For faking prepared SQL statements on DBs that don't support
871 * @param $preparedQuery String: a 'preparable' SQL statement
872 * @param $args Array of arguments to fill it with
873 * @return string executable SQL
875 function fillPrepared( $preparedQuery, $args ) {
877 $this->preparedArgs
=& $args;
879 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
880 array( &$this, 'fillPreparedArg' ), $preparedQuery );
884 * preg_callback func for fillPrepared()
885 * The arguments should be in $this->preparedArgs and must not be touched
886 * while we're doing this.
888 * @param $matches Array
892 function fillPreparedArg( $matches ) {
893 switch( $matches[1] ) {
894 case '\\?': return '?';
895 case '\\!': return '!';
896 case '\\&': return '&';
899 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
901 switch( $matches[1] ) {
902 case '?': return $this->addQuotes( $arg );
903 case '!': return $arg;
905 # return $this->addQuotes( file_get_contents( $arg ) );
906 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
908 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
913 * Free a result object
914 * @param $res Mixed: A SQL result
916 function freeResult( $res ) {
917 # Stub. Might not really need to be overridden, since results should
918 # be freed by PHP when the variable goes out of scope anyway.
922 * Simple UPDATE wrapper
923 * Usually aborts on failure
924 * If errors are explicitly ignored, returns success
926 * This function exists for historical reasons, DatabaseBase::update() has a more standard
927 * calling convention and feature set
931 function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
932 $table = $this->tableName( $table );
933 $sql = "UPDATE $table SET $var = '" .
934 $this->strencode( $value ) . "' WHERE ($cond)";
936 return (bool)$this->query( $sql, $fname );
940 * Simple SELECT wrapper, returns a single field, input must be encoded
941 * Usually aborts on failure
942 * If errors are explicitly ignored, returns FALSE on failure
944 function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField', $options = array() ) {
945 if ( !is_array( $options ) ) {
946 $options = array( $options );
949 $options['LIMIT'] = 1;
951 $res = $this->select( $table, $var, $cond, $fname, $options );
953 if ( $res === false ||
!$this->numRows( $res ) ) {
957 $row = $this->fetchRow( $res );
959 if ( $row !== false ) {
960 return reset( $row );
967 * Returns an optional USE INDEX clause to go after the table, and a
968 * string to go at the end of the query
972 * @param $options Array: associative array of options to be turned into
973 * an SQL query, valid keys are listed in the function.
976 function makeSelectOptions( $options ) {
977 $preLimitTail = $postLimitTail = '';
980 $noKeyOptions = array();
982 foreach ( $options as $key => $option ) {
983 if ( is_numeric( $key ) ) {
984 $noKeyOptions[$option] = true;
988 if ( isset( $options['GROUP BY'] ) ) {
989 $gb = is_array( $options['GROUP BY'] )
990 ?
implode( ',', $options['GROUP BY'] )
991 : $options['GROUP BY'];
992 $preLimitTail .= " GROUP BY {$gb}";
995 if ( isset( $options['HAVING'] ) ) {
996 $preLimitTail .= " HAVING {$options['HAVING']}";
999 if ( isset( $options['ORDER BY'] ) ) {
1000 $ob = is_array( $options['ORDER BY'] )
1001 ?
implode( ',', $options['ORDER BY'] )
1002 : $options['ORDER BY'];
1003 $preLimitTail .= " ORDER BY {$ob}";
1006 // if (isset($options['LIMIT'])) {
1007 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1008 // isset($options['OFFSET']) ? $options['OFFSET']
1012 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1013 $postLimitTail .= ' FOR UPDATE';
1016 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1017 $postLimitTail .= ' LOCK IN SHARE MODE';
1020 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1021 $startOpts .= 'DISTINCT';
1024 # Various MySQL extensions
1025 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1026 $startOpts .= ' /*! STRAIGHT_JOIN */';
1029 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1030 $startOpts .= ' HIGH_PRIORITY';
1033 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1034 $startOpts .= ' SQL_BIG_RESULT';
1037 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1038 $startOpts .= ' SQL_BUFFER_RESULT';
1041 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1042 $startOpts .= ' SQL_SMALL_RESULT';
1045 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1046 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1049 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1050 $startOpts .= ' SQL_CACHE';
1053 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1054 $startOpts .= ' SQL_NO_CACHE';
1057 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1058 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1063 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1069 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
1070 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1071 * @param $conds Mixed: Array or string, condition(s) for WHERE
1072 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1073 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1074 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1075 * @param $join_conds Array: Associative array of table join conditions (optional)
1076 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1077 * @return ResultWrapper|Bool Database result resource (feed to DatabaseBase::fetchObject
1078 * or whatever), or false on failure
1080 function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1081 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1083 return $this->query( $sql, $fname );
1089 * @param $table Mixed: Array or string, table name(s) (prefix auto-added). Array keys are table aliases (optional)
1090 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1091 * @param $conds Mixed: Array or string, condition(s) for WHERE
1092 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1093 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1094 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1095 * @param $join_conds Array: Associative array of table join conditions (optional)
1096 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1097 * @return string, the SQL text
1099 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1100 if ( is_array( $vars ) ) {
1101 $vars = implode( ',', $vars );
1104 if ( !is_array( $options ) ) {
1105 $options = array( $options );
1108 if ( is_array( $table ) ) {
1109 if ( !empty( $join_conds ) ||
( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) ) {
1110 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1112 $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
1114 } elseif ( $table != '' ) {
1115 if ( $table { 0 } == ' ' ) {
1116 $from = ' FROM ' . $table;
1118 $from = ' FROM ' . $this->tableName( $table );
1124 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1126 if ( !empty( $conds ) ) {
1127 if ( is_array( $conds ) ) {
1128 $conds = $this->makeList( $conds, LIST_AND
);
1130 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1132 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1135 if ( isset( $options['LIMIT'] ) )
1136 $sql = $this->limitResult( $sql, $options['LIMIT'],
1137 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1138 $sql = "$sql $postLimitTail";
1140 if ( isset( $options['EXPLAIN'] ) ) {
1141 $sql = 'EXPLAIN ' . $sql;
1148 * Single row SELECT wrapper
1149 * Aborts or returns FALSE on error
1151 * @param $table String: table name
1152 * @param $vars String: the selected variables
1153 * @param $conds Array: a condition map, terms are ANDed together.
1154 * Items with numeric keys are taken to be literal conditions
1155 * Takes an array of selected variables, and a condition map, which is ANDed
1156 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1157 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1158 * $obj- >page_id is the ID of the Astronomy article
1159 * @param $fname String: Calling function name
1160 * @param $options Array
1161 * @param $join_conds Array
1163 * @return ResultWrapper|Bool
1165 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow', $options = array(), $join_conds = array() ) {
1166 $options['LIMIT'] = 1;
1167 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1169 if ( $res === false ) {
1173 if ( !$this->numRows( $res ) ) {
1177 $obj = $this->fetchObject( $res );
1183 * Estimate rows in dataset
1184 * Returns estimated count - not necessarily an accurate estimate across different databases,
1186 * Takes same arguments as DatabaseBase::select()
1188 * @param $table String: table name
1189 * @param $vars Array: unused
1190 * @param $conds Array: filters on the table
1191 * @param $fname String: function name for profiling
1192 * @param $options Array: options for select
1193 * @return Integer: row count
1195 public function estimateRowCount( $table, $vars = '*', $conds = '', $fname = 'DatabaseBase::estimateRowCount', $options = array() ) {
1197 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1200 $row = $this->fetchRow( $res );
1201 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1208 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1209 * It's only slightly flawed. Don't use for anything important.
1211 * @param $sql String: A SQL Query
1213 static function generalizeSQL( $sql ) {
1214 # This does the same as the regexp below would do, but in such a way
1215 # as to avoid crashing php on some large strings.
1216 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1218 $sql = str_replace ( "\\\\", '', $sql );
1219 $sql = str_replace ( "\\'", '', $sql );
1220 $sql = str_replace ( "\\\"", '', $sql );
1221 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1222 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1224 # All newlines, tabs, etc replaced by single space
1225 $sql = preg_replace ( '/\s+/', ' ', $sql );
1228 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1234 * Determines whether a field exists in a table
1236 * @param $table String: table name
1237 * @param $field String: filed to check on that table
1238 * @param $fname String: calling function name (optional)
1239 * @return Boolean: whether $table has filed $field
1241 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1242 $info = $this->fieldInfo( $table, $field );
1248 * Determines whether an index exists
1249 * Usually aborts on failure
1250 * If errors are explicitly ignored, returns NULL on failure
1254 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1255 $info = $this->indexInfo( $table, $index, $fname );
1256 if ( is_null( $info ) ) {
1259 return $info !== false;
1264 * Query whether a given table exists
1270 function tableExists( $table ) {
1271 $table = $this->tableName( $table );
1272 $old = $this->ignoreErrors( true );
1273 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", __METHOD__
);
1274 $this->ignoreErrors( $old );
1280 * mysql_field_type() wrapper
1282 function fieldType( $res, $index ) {
1283 if ( $res instanceof ResultWrapper
) {
1284 $res = $res->result
;
1287 return mysql_field_type( $res, $index );
1291 * Determines if a given index is unique
1293 * @param $table string
1294 * @param $index string
1298 function indexUnique( $table, $index ) {
1299 $indexInfo = $this->indexInfo( $table, $index );
1301 if ( !$indexInfo ) {
1305 return !$indexInfo[0]->Non_unique
;
1309 * @param $options array
1312 function makeInsertOptions( $options ) {
1313 return implode( ' ', $options );
1317 * INSERT wrapper, inserts an array into a table
1319 * $a may be a single associative array, or an array of these with numeric keys, for
1322 * Usually aborts on failure
1323 * If errors are explicitly ignored, returns success
1325 * @param $table String: table name (prefix auto-added)
1326 * @param $a Array: Array of rows to insert
1327 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1328 * @param $options Mixed: Associative array of options
1332 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1333 # No rows to insert, easy just return now
1334 if ( !count( $a ) ) {
1338 $table = $this->tableName( $table );
1340 if ( !is_array( $options ) ) {
1341 $options = array( $options );
1344 $options = $this->makeInsertOptions( $options );
1346 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1348 $keys = array_keys( $a[0] );
1351 $keys = array_keys( $a );
1354 $sql = 'INSERT ' . $options .
1355 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1359 foreach ( $a as $row ) {
1365 $sql .= '(' . $this->makeList( $row ) . ')';
1368 $sql .= '(' . $this->makeList( $a ) . ')';
1371 return (bool)$this->query( $sql, $fname );
1375 * Make UPDATE options for the DatabaseBase::update function
1378 * @param $options Array: The options passed to DatabaseBase::update
1381 function makeUpdateOptions( $options ) {
1382 if ( !is_array( $options ) ) {
1383 $options = array( $options );
1388 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1389 $opts[] = $this->lowPriorityOption();
1392 if ( in_array( 'IGNORE', $options ) ) {
1396 return implode( ' ', $opts );
1400 * UPDATE wrapper, takes a condition array and a SET array
1402 * @param $table String: The table to UPDATE
1403 * @param $values Array: An array of values to SET
1404 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1405 * @param $fname String: The Class::Function calling this function
1407 * @param $options Array: An array of UPDATE options, can be one or
1408 * more of IGNORE, LOW_PRIORITY
1411 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1412 $table = $this->tableName( $table );
1413 $opts = $this->makeUpdateOptions( $options );
1414 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1416 if ( $conds != '*' ) {
1417 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1420 return $this->query( $sql, $fname );
1424 * Makes an encoded list of strings from an array
1427 * LIST_COMMA - comma separated, no field names
1428 * LIST_AND - ANDed WHERE clause (without the WHERE)
1429 * LIST_OR - ORed WHERE clause (without the WHERE)
1430 * LIST_SET - comma separated with field names, like a SET clause
1431 * LIST_NAMES - comma separated field names
1433 * In LIST_AND or LIST_OR modes, you can suffix a field with an exclamation
1434 * mark to generate a 'NOT IN' structure.
1436 * $db->makeList( array( 'field!' => array( 1,2,3 ) );
1438 * 'field' NOT IN ('1', '2', '3' );
1442 function makeList( $a, $mode = LIST_COMMA
) {
1443 if ( !is_array( $a ) ) {
1444 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1450 foreach ( $a as $field => $value ) {
1452 if ( $mode == LIST_AND
) {
1454 } elseif ( $mode == LIST_OR
) {
1463 // Support 'NOT IN' by suffixing fieldname with an exclamation mark
1465 if( substr($field,-1) == '!' ) {
1467 $field = substr($field, 0, -1 );
1470 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1471 $list .= "($value)";
1472 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1474 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1475 if ( count( $value ) == 0 ) {
1476 throw new MWException( __METHOD__
. ': empty input' );
1477 } elseif ( count( $value ) == 1 ) {
1478 // Special-case single values, as IN isn't terribly efficient
1479 // Don't necessarily assume the single key is 0; we don't
1480 // enforce linear numeric ordering on other arrays here.
1481 $value = array_values( $value );
1483 $operator = $not ?
' != ' : ' = ';
1484 $list .= $field . $operator . $this->addQuotes( $value[0] );
1486 $operator = $not ?
' NOT IN ' : ' IN ';
1487 $list .= $field . $operator . " (" . $this->makeList( $value ) . ") ";
1489 } elseif ( $value === null ) {
1490 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1491 $list .= "$field IS ";
1492 } elseif ( $mode == LIST_SET
) {
1493 $list .= "$field = ";
1497 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1498 $list .= "$field = ";
1500 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1508 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1509 * The keys on each level may be either integers or strings.
1511 * @param $data Array: organized as 2-d array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1512 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1513 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1514 * @return Mixed: string SQL fragment, or false if no items in array.
1516 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1519 foreach ( $data as $base => $sub ) {
1520 if ( count( $sub ) ) {
1521 $conds[] = $this->makeList(
1522 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1528 return $this->makeList( $conds, LIST_OR
);
1530 // Nothing to search for...
1536 * Bitwise operations
1543 function bitNot( $field ) {
1549 * @param $fieldRight
1552 function bitAnd( $fieldLeft, $fieldRight ) {
1553 return "($fieldLeft & $fieldRight)";
1558 * @param $fieldRight
1561 function bitOr( $fieldLeft, $fieldRight ) {
1562 return "($fieldLeft | $fieldRight)";
1566 * Change the current database
1568 * @todo Explain what exactly will fail if this is not overridden.
1569 * @return bool Success or failure
1571 function selectDB( $db ) {
1572 # Stub. Shouldn't cause serious problems if it's not overridden, but
1573 # if your database engine supports a concept similar to MySQL's
1574 # databases you may as well.
1575 $this->mDBname
= $db;
1580 * Get the current DB name
1582 function getDBname() {
1583 return $this->mDBname
;
1587 * Get the server hostname or IP address
1589 function getServer() {
1590 return $this->mServer
;
1594 * Format a table name ready for use in constructing an SQL query
1596 * This does two important things: it quotes the table names to clean them up,
1597 * and it adds a table prefix if only given a table name with no quotes.
1599 * All functions of this object which require a table name call this function
1600 * themselves. Pass the canonical name to such functions. This is only needed
1601 * when calling query() directly.
1603 * @param $name String: database table name
1604 * @param $quoted Boolean: Automatically pass the table name through
1605 * addIdentifierQuotes() so that it can be used in a query.
1606 * @return String: full database name
1608 function tableName( $name, $quoted = true ) {
1609 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1610 # Skip the entire process when we have a string quoted on both ends.
1611 # Note that we check the end so that we will still quote any use of
1612 # use of `database`.table. But won't break things if someone wants
1613 # to query a database table with a dot in the name.
1614 if ( $this->isQuotedIdentifier( $name ) ) {
1618 # Lets test for any bits of text that should never show up in a table
1619 # name. Basically anything like JOIN or ON which are actually part of
1620 # SQL queries, but may end up inside of the table value to combine
1621 # sql. Such as how the API is doing.
1622 # Note that we use a whitespace test rather than a \b test to avoid
1623 # any remote case where a word like on may be inside of a table name
1624 # surrounded by symbols which may be considered word breaks.
1625 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1629 # Split database and table into proper variables.
1630 # We reverse the explode so that database.table and table both output
1631 # the correct table.
1632 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1633 if ( isset( $dbDetails[1] ) ) {
1634 @list
( $table, $database ) = $dbDetails;
1636 @list
( $table ) = $dbDetails;
1638 $prefix = $this->mTablePrefix
; # Default prefix
1640 # Note that we use the long format because php will complain in in_array if
1641 # the input is not an array, and will complain in is_array if it is not set.
1642 if ( !isset( $database ) # Don't use shared database if pre selected.
1643 && isset( $wgSharedDB ) # We have a shared database
1644 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
1645 && isset( $wgSharedTables )
1646 && is_array( $wgSharedTables )
1647 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1648 $database = $wgSharedDB;
1649 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1652 # Quote the $database and $table and apply the prefix if not quoted.
1653 if ( isset( $database ) ) {
1654 $database = ( !$quoted ||
$this->isQuotedIdentifier( $database ) ?
$database : $this->addIdentifierQuotes( $database ) );
1658 $table = "{$prefix}{$table}";
1659 if ( $quoted && !$this->isQuotedIdentifier( $table ) ) {
1660 $table = $this->addIdentifierQuotes( "{$table}" );
1663 # Merge our database and table into our final table name.
1664 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
1670 * Fetch a number of table names into an array
1671 * This is handy when you need to construct SQL for joins
1674 * extract($dbr->tableNames('user','watchlist'));
1675 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1676 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1678 public function tableNames() {
1679 $inArray = func_get_args();
1682 foreach ( $inArray as $name ) {
1683 $retVal[$name] = $this->tableName( $name );
1690 * Fetch a number of table names into an zero-indexed numerical array
1691 * This is handy when you need to construct SQL for joins
1694 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1695 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1696 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1698 public function tableNamesN() {
1699 $inArray = func_get_args();
1702 foreach ( $inArray as $name ) {
1703 $retVal[] = $this->tableName( $name );
1710 * Get an aliased table name
1711 * e.g. tableName AS newTableName
1713 * @param $name string Table name, see tableName()
1714 * @param $alias string Alias (optional)
1715 * @return string SQL name for aliased table. Will not alias a table to its own name
1717 public function tableNameWithAlias( $name, $alias = false ) {
1718 if ( !$alias ||
$alias == $name ) {
1719 return $this->tableName( $name );
1721 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1726 * Gets an array of aliased table names
1728 * @param $tables array( [alias] => table )
1729 * @return array of strings, see tableNameWithAlias()
1731 public function tableNamesWithAlias( $tables ) {
1733 foreach ( $tables as $alias => $table ) {
1734 if ( is_numeric( $alias ) ) {
1737 $retval[] = $this->tableNameWithAlias( $table, $alias );
1745 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1748 $use_index_safe = is_array( $use_index ) ?
$use_index : array();
1749 $join_conds_safe = is_array( $join_conds ) ?
$join_conds : array();
1751 foreach ( $tables as $alias => $table ) {
1752 if ( !is_string( $alias ) ) {
1753 // No alias? Set it equal to the table name
1756 // Is there a JOIN and INDEX clause for this table?
1757 if ( isset( $join_conds_safe[$alias] ) && isset( $use_index_safe[$alias] ) ) {
1758 $tableClause = $join_conds_safe[$alias][0] . ' ' . $this->tableNameWithAlias( $table, $alias );
1759 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$alias] ) );
1760 $on = $this->makeList( (array)$join_conds_safe[$alias][1], LIST_AND
);
1762 $tableClause .= ' ON (' . $on . ')';
1765 $retJOIN[] = $tableClause;
1766 // Is there an INDEX clause?
1767 } else if ( isset( $use_index_safe[$alias] ) ) {
1768 $tableClause = $this->tableNameWithAlias( $table, $alias );
1769 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$alias] ) );
1770 $ret[] = $tableClause;
1771 // Is there a JOIN clause?
1772 } else if ( isset( $join_conds_safe[$alias] ) ) {
1773 $tableClause = $join_conds_safe[$alias][0] . ' ' . $this->tableNameWithAlias( $table, $alias );
1774 $on = $this->makeList( (array)$join_conds_safe[$alias][1], LIST_AND
);
1776 $tableClause .= ' ON (' . $on . ')';
1779 $retJOIN[] = $tableClause;
1781 $tableClause = $this->tableNameWithAlias( $table, $alias );
1782 $ret[] = $tableClause;
1786 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1787 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1788 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1790 // Compile our final table clause
1791 return implode( ' ', array( $straightJoins, $otherJoins ) );
1795 * Get the name of an index in a given table
1801 function indexName( $index ) {
1802 // Backwards-compatibility hack
1804 'ar_usertext_timestamp' => 'usertext_timestamp',
1805 'un_user_id' => 'user_id',
1806 'un_user_ip' => 'user_ip',
1809 if ( isset( $renamed[$index] ) ) {
1810 return $renamed[$index];
1817 * If it's a string, adds quotes and backslashes
1818 * Otherwise returns as-is
1824 function addQuotes( $s ) {
1825 if ( $s === null ) {
1828 # This will also quote numeric values. This should be harmless,
1829 # and protects against weird problems that occur when they really
1830 # _are_ strings such as article titles and string->number->string
1831 # conversion is not 1:1.
1832 return "'" . $this->strencode( $s ) . "'";
1837 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1838 * MySQL uses `backticks` while basically everything else uses double quotes.
1839 * Since MySQL is the odd one out here the double quotes are our generic
1840 * and we implement backticks in DatabaseMysql.
1844 public function addIdentifierQuotes( $s ) {
1845 return '"' . str_replace( '"', '""', $s ) . '"';
1849 * Returns if the given identifier looks quoted or not according to
1850 * the database convention for quoting identifiers .
1852 * @param $name string
1856 public function isQuotedIdentifier( $name ) {
1857 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
1861 * Backwards compatibility, identifier quoting originated in DatabasePostgres
1862 * which used quote_ident which does not follow our naming conventions
1863 * was renamed to addIdentifierQuotes.
1864 * @deprecated since 1.18 use addIdentifierQuotes
1868 function quote_ident( $s ) {
1869 wfDeprecated( __METHOD__
);
1870 return $this->addIdentifierQuotes( $s );
1874 * Escape string for safe LIKE usage.
1875 * WARNING: you should almost never use this function directly,
1876 * instead use buildLike() that escapes everything automatically
1877 * @deprecated since 1.17, warnings in 1.17, removed in ???
1879 public function escapeLike( $s ) {
1880 wfDeprecated( __METHOD__
);
1881 return $this->escapeLikeInternal( $s );
1884 protected function escapeLikeInternal( $s ) {
1885 $s = str_replace( '\\', '\\\\', $s );
1886 $s = $this->strencode( $s );
1887 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
1893 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
1894 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
1895 * Alternatively, the function could be provided with an array of aforementioned parameters.
1897 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
1898 * for subpages of 'My page title'.
1899 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
1902 * @return String: fully built LIKE statement
1904 function buildLike() {
1905 $params = func_get_args();
1907 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1908 $params = $params[0];
1913 foreach ( $params as $value ) {
1914 if ( $value instanceof LikeMatch
) {
1915 $s .= $value->toString();
1917 $s .= $this->escapeLikeInternal( $value );
1921 return " LIKE '" . $s . "' ";
1925 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1929 function anyChar() {
1930 return new LikeMatch( '_' );
1934 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1936 * @rerturn LikeMatch
1938 function anyString() {
1939 return new LikeMatch( '%' );
1943 * Returns an appropriately quoted sequence value for inserting a new row.
1944 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1945 * subclass will return an integer, and save the value for insertId()
1947 function nextSequenceValue( $seqName ) {
1952 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1953 * is only needed because a) MySQL must be as efficient as possible due to
1954 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1955 * which index to pick. Anyway, other databases might have different
1956 * indexes on a given table. So don't bother overriding this unless you're
1959 function useIndexClause( $index ) {
1964 * REPLACE query wrapper
1965 * PostgreSQL simulates this with a DELETE followed by INSERT
1966 * $row is the row to insert, an associative array
1967 * $uniqueIndexes is an array of indexes. Each element may be either a
1968 * field name or an array of field names
1970 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1971 * However if you do this, you run the risk of encountering errors which wouldn't have
1974 * @param $table String: The table to replace the row(s) in.
1975 * @param $uniqueIndexes Array: An associative array of indexes
1976 * @param $rows Array: Array of rows to replace
1977 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1979 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
1980 $table = $this->tableName( $table );
1983 if ( !is_array( reset( $rows ) ) ) {
1984 $rows = array( $rows );
1987 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
1990 foreach ( $rows as $row ) {
1997 $sql .= '(' . $this->makeList( $row ) . ')';
2000 return $this->query( $sql, $fname );
2004 * DELETE where the condition is a join
2005 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
2007 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
2008 * join condition matches, set $conds='*'
2010 * DO NOT put the join condition in $conds
2012 * @param $delTable String: The table to delete from.
2013 * @param $joinTable String: The other table.
2014 * @param $delVar String: The variable to join on, in the first table.
2015 * @param $joinVar String: The variable to join on, in the second table.
2016 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
2017 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
2019 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
2021 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
2024 $delTable = $this->tableName( $delTable );
2025 $joinTable = $this->tableName( $joinTable );
2026 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
2028 if ( $conds != '*' ) {
2029 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
2032 return $this->query( $sql, $fname );
2036 * Returns the size of a text field, or -1 for "unlimited"
2038 function textFieldSize( $table, $field ) {
2039 $table = $this->tableName( $table );
2040 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2041 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2042 $row = $this->fetchObject( $res );
2046 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2056 * A string to insert into queries to show that they're low-priority, like
2057 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2058 * string and nothing bad should happen.
2060 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
2062 function lowPriorityOption() {
2067 * DELETE query wrapper
2069 * Use $conds == "*" to delete all rows
2071 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
2073 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2076 $table = $this->tableName( $table );
2077 $sql = "DELETE FROM $table";
2079 if ( $conds != '*' ) {
2080 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2083 return $this->query( $sql, $fname );
2087 * INSERT SELECT wrapper
2088 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
2089 * Source items may be literals rather than field names, but strings should be quoted with DatabaseBase::addQuotes()
2090 * $conds may be "*" to copy the whole table
2091 * srcTable may be an array of tables.
2093 * @return ResultWrapper
2095 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseBase::insertSelect',
2096 $insertOptions = array(), $selectOptions = array() )
2098 $destTable = $this->tableName( $destTable );
2100 if ( is_array( $insertOptions ) ) {
2101 $insertOptions = implode( ' ', $insertOptions );
2104 if ( !is_array( $selectOptions ) ) {
2105 $selectOptions = array( $selectOptions );
2108 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2110 if ( is_array( $srcTable ) ) {
2111 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2113 $srcTable = $this->tableName( $srcTable );
2116 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2117 " SELECT $startOpts " . implode( ',', $varMap ) .
2118 " FROM $srcTable $useIndex ";
2120 if ( $conds != '*' ) {
2121 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2124 $sql .= " $tailOpts";
2126 return $this->query( $sql, $fname );
2130 * Construct a LIMIT query with optional offset. This is used for query
2131 * pages. The SQL should be adjusted so that only the first $limit rows
2132 * are returned. If $offset is provided as well, then the first $offset
2133 * rows should be discarded, and the next $limit rows should be returned.
2134 * If the result of the query is not ordered, then the rows to be returned
2135 * are theoretically arbitrary.
2137 * $sql is expected to be a SELECT, if that makes a difference. For
2138 * UPDATE, limitResultForUpdate should be used.
2140 * The version provided by default works in MySQL and SQLite. It will very
2141 * likely need to be overridden for most other DBMSes.
2143 * @param $sql String: SQL query we will append the limit too
2144 * @param $limit Integer: the SQL limit
2145 * @param $offset Integer the SQL offset (default false)
2149 function limitResult( $sql, $limit, $offset = false ) {
2150 if ( !is_numeric( $limit ) ) {
2151 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2154 return "$sql LIMIT "
2155 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2159 function limitResultForUpdate( $sql, $num ) {
2160 return $this->limitResult( $sql, $num, 0 );
2164 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2165 * within the UNION construct.
2168 function unionSupportsOrderAndLimit() {
2169 return true; // True for almost every DB supported
2173 * Construct a UNION query
2174 * This is used for providing overload point for other DB abstractions
2175 * not compatible with the MySQL syntax.
2176 * @param $sqls Array: SQL statements to combine
2177 * @param $all Boolean: use UNION ALL
2178 * @return String: SQL fragment
2180 function unionQueries( $sqls, $all ) {
2181 $glue = $all ?
') UNION ALL (' : ') UNION (';
2182 return '(' . implode( $glue, $sqls ) . ')';
2186 * Returns an SQL expression for a simple conditional. This doesn't need
2187 * to be overridden unless CASE isn't supported in your DBMS.
2189 * @param $cond String: SQL expression which will result in a boolean value
2190 * @param $trueVal String: SQL expression to return if true
2191 * @param $falseVal String: SQL expression to return if false
2192 * @return String: SQL fragment
2194 function conditional( $cond, $trueVal, $falseVal ) {
2195 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2199 * Returns a comand for str_replace function in SQL query.
2200 * Uses REPLACE() in MySQL
2202 * @param $orig String: column to modify
2203 * @param $old String: column to seek
2204 * @param $new String: column to replace with
2208 function strreplace( $orig, $old, $new ) {
2209 return "REPLACE({$orig}, {$old}, {$new})";
2213 * Determines if the last failure was due to a deadlock
2218 function wasDeadlock() {
2223 * Determines if the last query error was something that should be dealt
2224 * with by pinging the connection and reissuing the query.
2229 function wasErrorReissuable() {
2234 * Determines if the last failure was due to the database being read-only.
2239 function wasReadOnlyError() {
2244 * Perform a deadlock-prone transaction.
2246 * This function invokes a callback function to perform a set of write
2247 * queries. If a deadlock occurs during the processing, the transaction
2248 * will be rolled back and the callback function will be called again.
2251 * $dbw->deadlockLoop( callback, ... );
2253 * Extra arguments are passed through to the specified callback function.
2255 * Returns whatever the callback function returned on its successful,
2256 * iteration, or false on error, for example if the retry limit was
2259 function deadlockLoop() {
2260 $myFname = 'DatabaseBase::deadlockLoop';
2263 $args = func_get_args();
2264 $function = array_shift( $args );
2265 $oldIgnore = $this->ignoreErrors( true );
2266 $tries = DEADLOCK_TRIES
;
2268 if ( is_array( $function ) ) {
2269 $fname = $function[0];
2275 $retVal = call_user_func_array( $function, $args );
2276 $error = $this->lastError();
2277 $errno = $this->lastErrno();
2278 $sql = $this->lastQuery();
2281 if ( $this->wasDeadlock() ) {
2283 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
2285 $this->reportQueryError( $error, $errno, $sql, $fname );
2288 } while ( $this->wasDeadlock() && --$tries > 0 );
2290 $this->ignoreErrors( $oldIgnore );
2292 if ( $tries <= 0 ) {
2293 $this->rollback( $myFname );
2294 $this->reportQueryError( $error, $errno, $sql, $fname );
2297 $this->commit( $myFname );
2303 * Do a SELECT MASTER_POS_WAIT()
2305 * @param $pos MySQLMasterPos object
2306 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
2308 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
2309 $fname = 'DatabaseBase::masterPosWait';
2310 wfProfileIn( $fname );
2312 # Commit any open transactions
2313 if ( $this->mTrxLevel
) {
2317 if ( !is_null( $this->mFakeSlaveLag
) ) {
2318 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
2320 if ( $wait > $timeout * 1e6
) {
2321 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2322 wfProfileOut( $fname );
2324 } elseif ( $wait > 0 ) {
2325 wfDebug( "Fake slave waiting $wait us\n" );
2327 wfProfileOut( $fname );
2330 wfDebug( "Fake slave up to date ($wait us)\n" );
2331 wfProfileOut( $fname );
2336 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
2337 $encFile = $this->addQuotes( $pos->file
);
2338 $encPos = intval( $pos->pos
);
2339 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
2340 $res = $this->doQuery( $sql );
2342 if ( $res && $row = $this->fetchRow( $res ) ) {
2343 wfProfileOut( $fname );
2346 wfProfileOut( $fname );
2352 * Get the position of the master from SHOW SLAVE STATUS
2354 * @return MySQLMasterPos|false
2356 function getSlavePos() {
2357 if ( !is_null( $this->mFakeSlaveLag
) ) {
2358 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
2359 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
2363 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
2364 $row = $this->fetchObject( $res );
2367 $pos = isset( $row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
2368 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
2375 * Get the position of the master from SHOW MASTER STATUS
2377 * @return MySQLMasterPos|false
2379 function getMasterPos() {
2380 if ( $this->mFakeMaster
) {
2381 return new MySQLMasterPos( 'fake', microtime( true ) );
2384 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
2385 $row = $this->fetchObject( $res );
2388 return new MySQLMasterPos( $row->File
, $row->Position
);
2395 * Begin a transaction, committing any previously open transaction
2397 function begin( $fname = 'DatabaseBase::begin' ) {
2398 $this->query( 'BEGIN', $fname );
2399 $this->mTrxLevel
= 1;
2405 function commit( $fname = 'DatabaseBase::commit' ) {
2406 if ( $this->mTrxLevel
) {
2407 $this->query( 'COMMIT', $fname );
2408 $this->mTrxLevel
= 0;
2413 * Rollback a transaction.
2414 * No-op on non-transactional databases.
2416 function rollback( $fname = 'DatabaseBase::rollback' ) {
2417 if ( $this->mTrxLevel
) {
2418 $this->query( 'ROLLBACK', $fname, true );
2419 $this->mTrxLevel
= 0;
2424 * Creates a new table with structure copied from existing table
2425 * Note that unlike most database abstraction functions, this function does not
2426 * automatically append database prefix, because it works at a lower
2427 * abstraction level.
2428 * The table names passed to this function shall not be quoted (this
2429 * function calls addIdentifierQuotes when needed).
2431 * @param $oldName String: name of table whose structure should be copied
2432 * @param $newName String: name of table to be created
2433 * @param $temporary Boolean: whether the new table should be temporary
2434 * @param $fname String: calling function name
2435 * @return Boolean: true if operation was successful
2437 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseBase::duplicateTableStructure' ) {
2438 throw new MWException( 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2442 * List all tables on the database
2444 * @param $prefix Only show tables with this prefix, e.g. mw_
2445 * @param $fname String: calling function name
2447 function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
2448 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2452 * Return MW-style timestamp used for MySQL schema
2456 function timestamp( $ts = 0 ) {
2457 return wfTimestamp( TS_MW
, $ts );
2461 * Local database timestamp format or null
2465 function timestampOrNull( $ts = null ) {
2466 if ( is_null( $ts ) ) {
2469 return $this->timestamp( $ts );
2476 * @return ResultWrapper
2478 function resultObject( $result ) {
2479 if ( empty( $result ) ) {
2481 } elseif ( $result instanceof ResultWrapper
) {
2483 } elseif ( $result === true ) {
2484 // Successful write query
2487 return new ResultWrapper( $this, $result );
2492 * Return aggregated value alias
2494 function aggregateValue ( $valuedata, $valuename = 'value' ) {
2499 * Ping the server and try to reconnect if it there is no connection
2501 * @return bool Success or failure
2504 # Stub. Not essential to override.
2510 * Currently supported only by MySQL
2511 * @return Database replication lag in seconds
2514 return intval( $this->mFakeSlaveLag
);
2518 * Get status information from SHOW STATUS in an associative array
2522 function getStatus( $which = "%" ) {
2523 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2526 foreach ( $res as $row ) {
2527 $status[$row->Variable_name
] = $row->Value
;
2534 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2538 function maxListLen() {
2542 function encodeBlob( $b ) {
2546 function decodeBlob( $b ) {
2551 * Override database's default connection timeout. May be useful for very
2552 * long batch queries such as full-wiki dumps, where a single query reads
2553 * out over hours or days. May or may not be necessary for non-MySQL
2554 * databases. For most purposes, leaving it as a no-op should be fine.
2556 * @param $timeout Integer in seconds
2558 public function setTimeout( $timeout ) {}
2561 * Read and execute SQL commands from a file.
2562 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2563 * @param $filename String: File name to open
2564 * @param $lineCallback Callback: Optional function called before reading each line
2565 * @param $resultCallback Callback: Optional function called for each MySQL result
2566 * @param $fname String: Calling function name or false if name should be generated dynamically
2569 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
2570 wfSuppressWarnings();
2571 $fp = fopen( $filename, 'r' );
2572 wfRestoreWarnings();
2574 if ( false === $fp ) {
2575 throw new MWException( "Could not open \"{$filename}\".\n" );
2579 $fname = __METHOD__
. "( $filename )";
2583 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
2585 catch ( MWException
$e ) {
2596 * Get the full path of a patch file. Originally based on archive()
2597 * from updaters.inc. Keep in mind this always returns a patch, as
2598 * it fails back to MySQL if no DB-specific patch can be found
2600 * @param $patch String The name of the patch, like patch-something.sql
2601 * @return String Full path to patch file
2603 public function patchPath( $patch ) {
2606 $dbType = $this->getType();
2607 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
2608 return "$IP/maintenance/$dbType/archives/$patch";
2610 return "$IP/maintenance/archives/$patch";
2615 * Set variables to be used in sourceFile/sourceStream, in preference to the
2616 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
2617 * all. If it's set to false, $GLOBALS will be used.
2619 * @param $vars False, or array mapping variable name to value.
2621 function setSchemaVars( $vars ) {
2622 $this->mSchemaVars
= $vars;
2626 * Read and execute commands from an open file handle
2627 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2628 * @param $fp Resource: File handle
2629 * @param $lineCallback Callback: Optional function called before reading each line
2630 * @param $resultCallback Callback: Optional function called for each MySQL result
2631 * @param $fname String: Calling function name
2633 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseBase::sourceStream' ) {
2636 $dollarquote = false;
2638 while ( ! feof( $fp ) ) {
2639 if ( $lineCallback ) {
2640 call_user_func( $lineCallback );
2643 $line = trim( fgets( $fp ) );
2644 $sl = strlen( $line ) - 1;
2650 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
2654 # # Allow dollar quoting for function declarations
2655 if ( substr( $line, 0, 4 ) == '$mw$' ) {
2656 if ( $dollarquote ) {
2657 $dollarquote = false;
2661 $dollarquote = true;
2664 else if ( !$dollarquote ) {
2665 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
2667 $line = substr( $line, 0, $sl );
2678 $cmd = str_replace( ';;', ";", $cmd );
2679 $cmd = $this->replaceVars( $cmd );
2680 $res = $this->query( $cmd, $fname );
2682 if ( $resultCallback ) {
2683 call_user_func( $resultCallback, $res, $this );
2686 if ( false === $res ) {
2687 $err = $this->lastError();
2688 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2700 * Database independent variable replacement, replaces a set of variables
2701 * in a sql statement with their contents as given by $this->getSchemaVars().
2702 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables
2704 * '{$var}' should be used for text and is passed through the database's addQuotes method
2705 * `{$var}` should be used for identifiers (eg: table and database names), it is passed through
2706 * the database's addIdentifierQuotes method which can be overridden if the database
2707 * uses something other than backticks.
2708 * / *$var* / is just encoded, besides traditional dbprefix and tableoptions it's use should be avoided
2710 * @param $ins String: SQL statement to replace variables in
2711 * @return String The new SQL statement with variables replaced
2713 protected function replaceSchemaVars( $ins ) {
2714 $vars = $this->getSchemaVars();
2715 foreach ( $vars as $var => $value ) {
2717 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
2719 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
2721 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
2727 * Replace variables in sourced SQL
2729 protected function replaceVars( $ins ) {
2730 $ins = $this->replaceSchemaVars( $ins );
2733 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2734 array( $this, 'tableNameCallback' ), $ins );
2737 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2738 array( $this, 'indexNameCallback' ), $ins );
2744 * Get schema variables. If none have been set via setSchemaVars(), then
2745 * use some defaults from the current object.
2747 protected function getSchemaVars() {
2748 if ( $this->mSchemaVars
) {
2749 return $this->mSchemaVars
;
2751 return $this->getDefaultSchemaVars();
2756 * Get schema variables to use if none have been set via setSchemaVars().
2757 * Override this in derived classes to provide variables for tables.sql
2758 * and SQL patch files.
2760 protected function getDefaultSchemaVars() {
2765 * Table name callback
2768 protected function tableNameCallback( $matches ) {
2769 return $this->tableName( $matches[1] );
2773 * Index name callback
2775 protected function indexNameCallback( $matches ) {
2776 return $this->indexName( $matches[1] );
2780 * Build a concatenation list to feed into a SQL query
2781 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2784 function buildConcat( $stringList ) {
2785 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2789 * Acquire a named lock
2791 * Abstracted from Filestore::lock() so child classes can implement for
2794 * @param $lockName String: name of lock to aquire
2795 * @param $method String: name of method calling us
2796 * @param $timeout Integer: timeout
2799 public function lock( $lockName, $method, $timeout = 5 ) {
2806 * @param $lockName String: Name of lock to release
2807 * @param $method String: Name of method calling us
2809 * @return Returns 1 if the lock was released, 0 if the lock was not established
2810 * by this thread (in which case the lock is not released), and NULL if the named
2811 * lock did not exist
2813 public function unlock( $lockName, $method ) {
2818 * Lock specific tables
2820 * @param $read Array of tables to lock for read access
2821 * @param $write Array of tables to lock for write access
2822 * @param $method String name of caller
2823 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2825 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2830 * Unlock specific tables
2832 * @param $method String the caller
2834 public function unlockTables( $method ) {
2841 public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
2842 if( !$this->tableExists( $tableName ) ) {
2845 $sql = "DROP TABLE " . $this->tableName( $tableName );
2846 if( $this->cascadingDeletes() ) {
2849 return $this->query( $sql, $fName );
2853 * Get search engine class. All subclasses of this need to implement this
2854 * if they wish to use searching.
2858 public function getSearchEngine() {
2859 return 'SearchEngineDummy';
2863 * Find out when 'infinity' is. Most DBMSes support this. This is a special
2864 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
2865 * because "i" sorts after all numbers.
2869 public function getInfinity() {
2874 * Encode an expiry time
2876 * @param $expiry String: timestamp for expiry, or the 'infinity' string
2879 public function encodeExpiry( $expiry ) {
2880 if ( $expiry == '' ||
$expiry == $this->getInfinity() ) {
2881 return $this->getInfinity();
2883 return $this->timestamp( $expiry );
2888 * Allow or deny "big selects" for this session only. This is done by setting
2889 * the sql_big_selects session variable.
2891 * This is a MySQL-specific feature.
2893 * @param $value Mixed: true for allow, false for deny, or "default" to restore the initial value
2895 public function setBigSelects( $value = true ) {