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|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 );
804 * Intended to be compatible with the PEAR::DB wrapper functions.
805 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
807 * ? = scalar value, quoted as necessary
808 * ! = raw SQL bit (a function for instance)
809 * & = filename; reads the file and inserts as a blob
810 * (we don't use this though...)
814 function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
815 /* MySQL doesn't support prepared statements (yet), so just
816 pack up the query for reference. We'll manually replace
818 return array( 'query' => $sql, 'func' => $func );
821 function freePrepared( $prepared ) {
822 /* No-op by default */
826 * Execute a prepared query with the various arguments
827 * @param $prepared String: the prepared sql
828 * @param $args Mixed: Either an array here, or put scalars as varargs
830 * @return ResultWrapper
832 function execute( $prepared, $args = null ) {
833 if ( !is_array( $args ) ) {
835 $args = func_get_args();
836 array_shift( $args );
839 $sql = $this->fillPrepared( $prepared['query'], $args );
841 return $this->query( $sql, $prepared['func'] );
845 * Prepare & execute an SQL statement, quoting and inserting arguments
846 * in the appropriate places.
847 * @param $query String
850 * @return ResultWrapper
852 function safeQuery( $query, $args = null ) {
853 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
855 if ( !is_array( $args ) ) {
857 $args = func_get_args();
858 array_shift( $args );
861 $retval = $this->execute( $prepared, $args );
862 $this->freePrepared( $prepared );
868 * For faking prepared SQL statements on DBs that don't support
870 * @param $preparedQuery String: a 'preparable' SQL statement
871 * @param $args Array of arguments to fill it with
872 * @return string executable SQL
874 function fillPrepared( $preparedQuery, $args ) {
876 $this->preparedArgs
=& $args;
878 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
879 array( &$this, 'fillPreparedArg' ), $preparedQuery );
883 * preg_callback func for fillPrepared()
884 * The arguments should be in $this->preparedArgs and must not be touched
885 * while we're doing this.
887 * @param $matches Array
891 function fillPreparedArg( $matches ) {
892 switch( $matches[1] ) {
893 case '\\?': return '?';
894 case '\\!': return '!';
895 case '\\&': return '&';
898 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
900 switch( $matches[1] ) {
901 case '?': return $this->addQuotes( $arg );
902 case '!': return $arg;
904 # return $this->addQuotes( file_get_contents( $arg ) );
905 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
907 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
912 * Free a result object
913 * @param $res Mixed: A SQL result
915 function freeResult( $res ) {
916 # Stub. Might not really need to be overridden, since results should
917 # be freed by PHP when the variable goes out of scope anyway.
921 * Simple UPDATE wrapper
922 * Usually aborts on failure
923 * If errors are explicitly ignored, returns success
925 * This function exists for historical reasons, DatabaseBase::update() has a more standard
926 * calling convention and feature set
930 function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
931 $table = $this->tableName( $table );
932 $sql = "UPDATE $table SET $var = '" .
933 $this->strencode( $value ) . "' WHERE ($cond)";
935 return (bool)$this->query( $sql, $fname );
939 * Simple SELECT wrapper, returns a single field, input must be encoded
940 * Usually aborts on failure
941 * If errors are explicitly ignored, returns FALSE on failure
943 function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField', $options = array() ) {
944 if ( !is_array( $options ) ) {
945 $options = array( $options );
948 $options['LIMIT'] = 1;
950 $res = $this->select( $table, $var, $cond, $fname, $options );
952 if ( $res === false ||
!$this->numRows( $res ) ) {
956 $row = $this->fetchRow( $res );
958 if ( $row !== false ) {
959 return reset( $row );
966 * Returns an optional USE INDEX clause to go after the table, and a
967 * string to go at the end of the query
971 * @param $options Array: associative array of options to be turned into
972 * an SQL query, valid keys are listed in the function.
975 function makeSelectOptions( $options ) {
976 $preLimitTail = $postLimitTail = '';
979 $noKeyOptions = array();
981 foreach ( $options as $key => $option ) {
982 if ( is_numeric( $key ) ) {
983 $noKeyOptions[$option] = true;
987 if ( isset( $options['GROUP BY'] ) ) {
988 $gb = is_array( $options['GROUP BY'] )
989 ?
implode( ',', $options['GROUP BY'] )
990 : $options['GROUP BY'];
991 $preLimitTail .= " GROUP BY {$gb}";
994 if ( isset( $options['HAVING'] ) ) {
995 $preLimitTail .= " HAVING {$options['HAVING']}";
998 if ( isset( $options['ORDER BY'] ) ) {
999 $ob = is_array( $options['ORDER BY'] )
1000 ?
implode( ',', $options['ORDER BY'] )
1001 : $options['ORDER BY'];
1002 $preLimitTail .= " ORDER BY {$ob}";
1005 // if (isset($options['LIMIT'])) {
1006 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1007 // isset($options['OFFSET']) ? $options['OFFSET']
1011 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1012 $postLimitTail .= ' FOR UPDATE';
1015 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1016 $postLimitTail .= ' LOCK IN SHARE MODE';
1019 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1020 $startOpts .= 'DISTINCT';
1023 # Various MySQL extensions
1024 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1025 $startOpts .= ' /*! STRAIGHT_JOIN */';
1028 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1029 $startOpts .= ' HIGH_PRIORITY';
1032 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1033 $startOpts .= ' SQL_BIG_RESULT';
1036 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1037 $startOpts .= ' SQL_BUFFER_RESULT';
1040 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1041 $startOpts .= ' SQL_SMALL_RESULT';
1044 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1045 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1048 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1049 $startOpts .= ' SQL_CACHE';
1052 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1053 $startOpts .= ' SQL_NO_CACHE';
1056 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1057 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1062 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1068 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
1069 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1070 * @param $conds Mixed: Array or string, condition(s) for WHERE
1071 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1072 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1073 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1074 * @param $join_conds Array: Associative array of table join conditions (optional)
1075 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1076 * @return ResultWrapper|Bool Database result resource (feed to DatabaseBase::fetchObject
1077 * or whatever), or false on failure
1079 function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1080 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1082 return $this->query( $sql, $fname );
1088 * @param $table Mixed: Array or string, table name(s) (prefix auto-added). Array keys are table aliases (optional)
1089 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1090 * @param $conds Mixed: Array or string, condition(s) for WHERE
1091 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1092 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1093 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1094 * @param $join_conds Array: Associative array of table join conditions (optional)
1095 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1096 * @return string, the SQL text
1098 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1099 if ( is_array( $vars ) ) {
1100 $vars = implode( ',', $vars );
1103 if ( !is_array( $options ) ) {
1104 $options = array( $options );
1107 if ( is_array( $table ) ) {
1108 if ( !empty( $join_conds ) ||
( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) ) {
1109 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1111 $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
1113 } elseif ( $table != '' ) {
1114 if ( $table { 0 } == ' ' ) {
1115 $from = ' FROM ' . $table;
1117 $from = ' FROM ' . $this->tableName( $table );
1123 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1125 if ( !empty( $conds ) ) {
1126 if ( is_array( $conds ) ) {
1127 $conds = $this->makeList( $conds, LIST_AND
);
1129 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1131 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1134 if ( isset( $options['LIMIT'] ) )
1135 $sql = $this->limitResult( $sql, $options['LIMIT'],
1136 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1137 $sql = "$sql $postLimitTail";
1139 if ( isset( $options['EXPLAIN'] ) ) {
1140 $sql = 'EXPLAIN ' . $sql;
1147 * Single row SELECT wrapper
1148 * Aborts or returns FALSE on error
1150 * @param $table String: table name
1151 * @param $vars String: the selected variables
1152 * @param $conds Array: a condition map, terms are ANDed together.
1153 * Items with numeric keys are taken to be literal conditions
1154 * Takes an array of selected variables, and a condition map, which is ANDed
1155 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1156 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1157 * $obj- >page_id is the ID of the Astronomy article
1158 * @param $fname String: Calling function name
1159 * @param $options Array
1160 * @param $join_conds Array
1162 * @return ResultWrapper|Bool
1164 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow', $options = array(), $join_conds = array() ) {
1165 $options['LIMIT'] = 1;
1166 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1168 if ( $res === false ) {
1172 if ( !$this->numRows( $res ) ) {
1176 $obj = $this->fetchObject( $res );
1182 * Estimate rows in dataset
1183 * Returns estimated count - not necessarily an accurate estimate across different databases,
1185 * Takes same arguments as DatabaseBase::select()
1187 * @param $table String: table name
1188 * @param $vars Array: unused
1189 * @param $conds Array: filters on the table
1190 * @param $fname String: function name for profiling
1191 * @param $options Array: options for select
1192 * @return Integer: row count
1194 public function estimateRowCount( $table, $vars = '*', $conds = '', $fname = 'DatabaseBase::estimateRowCount', $options = array() ) {
1196 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1199 $row = $this->fetchRow( $res );
1200 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1207 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1208 * It's only slightly flawed. Don't use for anything important.
1210 * @param $sql String: A SQL Query
1212 static function generalizeSQL( $sql ) {
1213 # This does the same as the regexp below would do, but in such a way
1214 # as to avoid crashing php on some large strings.
1215 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1217 $sql = str_replace ( "\\\\", '', $sql );
1218 $sql = str_replace ( "\\'", '', $sql );
1219 $sql = str_replace ( "\\\"", '', $sql );
1220 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1221 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1223 # All newlines, tabs, etc replaced by single space
1224 $sql = preg_replace ( '/\s+/', ' ', $sql );
1227 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1233 * Determines whether a field exists in a table
1235 * @param $table String: table name
1236 * @param $field String: filed to check on that table
1237 * @param $fname String: calling function name (optional)
1238 * @return Boolean: whether $table has filed $field
1240 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1241 $info = $this->fieldInfo( $table, $field );
1247 * Determines whether an index exists
1248 * Usually aborts on failure
1249 * If errors are explicitly ignored, returns NULL on failure
1253 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1254 $info = $this->indexInfo( $table, $index, $fname );
1255 if ( is_null( $info ) ) {
1258 return $info !== false;
1263 * Query whether a given table exists
1269 function tableExists( $table ) {
1270 $table = $this->tableName( $table );
1271 $old = $this->ignoreErrors( true );
1272 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", __METHOD__
);
1273 $this->ignoreErrors( $old );
1279 * mysql_field_type() wrapper
1281 function fieldType( $res, $index ) {
1282 if ( $res instanceof ResultWrapper
) {
1283 $res = $res->result
;
1286 return mysql_field_type( $res, $index );
1290 * Determines if a given index is unique
1292 * @param $table string
1293 * @param $index string
1297 function indexUnique( $table, $index ) {
1298 $indexInfo = $this->indexInfo( $table, $index );
1300 if ( !$indexInfo ) {
1304 return !$indexInfo[0]->Non_unique
;
1308 * @param $options array
1311 function makeInsertOptions( $options ) {
1312 return implode( ' ', $options );
1316 * INSERT wrapper, inserts an array into a table
1318 * $a may be a single associative array, or an array of these with numeric keys, for
1321 * Usually aborts on failure
1322 * If errors are explicitly ignored, returns success
1324 * @param $table String: table name (prefix auto-added)
1325 * @param $a Array: Array of rows to insert
1326 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1327 * @param $options Mixed: Associative array of options
1331 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1332 # No rows to insert, easy just return now
1333 if ( !count( $a ) ) {
1337 $table = $this->tableName( $table );
1339 if ( !is_array( $options ) ) {
1340 $options = array( $options );
1343 $options = $this->makeInsertOptions( $options );
1345 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1347 $keys = array_keys( $a[0] );
1350 $keys = array_keys( $a );
1353 $sql = 'INSERT ' . $options .
1354 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1358 foreach ( $a as $row ) {
1364 $sql .= '(' . $this->makeList( $row ) . ')';
1367 $sql .= '(' . $this->makeList( $a ) . ')';
1370 return (bool)$this->query( $sql, $fname );
1374 * Make UPDATE options for the DatabaseBase::update function
1377 * @param $options Array: The options passed to DatabaseBase::update
1380 function makeUpdateOptions( $options ) {
1381 if ( !is_array( $options ) ) {
1382 $options = array( $options );
1387 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1388 $opts[] = $this->lowPriorityOption();
1391 if ( in_array( 'IGNORE', $options ) ) {
1395 return implode( ' ', $opts );
1399 * UPDATE wrapper, takes a condition array and a SET array
1401 * @param $table String: The table to UPDATE
1402 * @param $values Array: An array of values to SET
1403 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1404 * @param $fname String: The Class::Function calling this function
1406 * @param $options Array: An array of UPDATE options, can be one or
1407 * more of IGNORE, LOW_PRIORITY
1410 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1411 $table = $this->tableName( $table );
1412 $opts = $this->makeUpdateOptions( $options );
1413 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1415 if ( $conds != '*' ) {
1416 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1419 return $this->query( $sql, $fname );
1423 * Makes an encoded list of strings from an array
1426 * LIST_COMMA - comma separated, no field names
1427 * LIST_AND - ANDed WHERE clause (without the WHERE)
1428 * LIST_OR - ORed WHERE clause (without the WHERE)
1429 * LIST_SET - comma separated with field names, like a SET clause
1430 * LIST_NAMES - comma separated field names
1432 * In LIST_AND or LIST_OR modes, you can suffix a field with an exclamation
1433 * mark to generate a 'NOT IN' structure.
1435 * $db->makeList( array( 'field!' => array( 1,2,3 ) );
1437 * 'field' NOT IN ('1', '2', '3' );
1441 function makeList( $a, $mode = LIST_COMMA
) {
1442 if ( !is_array( $a ) ) {
1443 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1449 foreach ( $a as $field => $value ) {
1451 if ( $mode == LIST_AND
) {
1453 } elseif ( $mode == LIST_OR
) {
1462 // Support 'NOT IN' by suffixing fieldname with an exclamation mark
1464 if( substr($field,-1) == '!' ) {
1466 $field = substr($field, 0, -1 );
1469 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1470 $list .= "($value)";
1471 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1473 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1474 if ( count( $value ) == 0 ) {
1475 throw new MWException( __METHOD__
. ': empty input' );
1476 } elseif ( count( $value ) == 1 ) {
1477 // Special-case single values, as IN isn't terribly efficient
1478 // Don't necessarily assume the single key is 0; we don't
1479 // enforce linear numeric ordering on other arrays here.
1480 $value = array_values( $value );
1482 $operator = $not ?
' != ' : ' = ';
1483 $list .= $field . $operator . $this->addQuotes( $value[0] );
1485 $operator = $not ?
' NOT IN ' : ' IN ';
1486 $list .= $field . $operator . "(" . $this->makeList( $value ) . ")";
1488 } elseif ( $value === null ) {
1489 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1490 $list .= "$field IS ";
1494 } elseif ( $mode == LIST_SET
) {
1495 $list .= "$field = ";
1499 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1500 $list .= "$field = ";
1502 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1510 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1511 * The keys on each level may be either integers or strings.
1513 * @param $data Array: organized as 2-d array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1514 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1515 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1516 * @return Mixed: string SQL fragment, or false if no items in array.
1518 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1521 foreach ( $data as $base => $sub ) {
1522 if ( count( $sub ) ) {
1523 $conds[] = $this->makeList(
1524 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1530 return $this->makeList( $conds, LIST_OR
);
1532 // Nothing to search for...
1538 * Bitwise operations
1545 function bitNot( $field ) {
1551 * @param $fieldRight
1554 function bitAnd( $fieldLeft, $fieldRight ) {
1555 return "($fieldLeft & $fieldRight)";
1560 * @param $fieldRight
1563 function bitOr( $fieldLeft, $fieldRight ) {
1564 return "($fieldLeft | $fieldRight)";
1568 * Change the current database
1570 * @todo Explain what exactly will fail if this is not overridden.
1571 * @return bool Success or failure
1573 function selectDB( $db ) {
1574 # Stub. Shouldn't cause serious problems if it's not overridden, but
1575 # if your database engine supports a concept similar to MySQL's
1576 # databases you may as well.
1577 $this->mDBname
= $db;
1582 * Get the current DB name
1584 function getDBname() {
1585 return $this->mDBname
;
1589 * Get the server hostname or IP address
1591 function getServer() {
1592 return $this->mServer
;
1596 * Format a table name ready for use in constructing an SQL query
1598 * This does two important things: it quotes the table names to clean them up,
1599 * and it adds a table prefix if only given a table name with no quotes.
1601 * All functions of this object which require a table name call this function
1602 * themselves. Pass the canonical name to such functions. This is only needed
1603 * when calling query() directly.
1605 * @param $name String: database table name
1606 * @param $quoted Boolean: Automatically pass the table name through
1607 * addIdentifierQuotes() so that it can be used in a query.
1608 * @return String: full database name
1610 function tableName( $name, $quoted = true ) {
1611 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1612 # Skip the entire process when we have a string quoted on both ends.
1613 # Note that we check the end so that we will still quote any use of
1614 # use of `database`.table. But won't break things if someone wants
1615 # to query a database table with a dot in the name.
1616 if ( $this->isQuotedIdentifier( $name ) ) {
1620 # Lets test for any bits of text that should never show up in a table
1621 # name. Basically anything like JOIN or ON which are actually part of
1622 # SQL queries, but may end up inside of the table value to combine
1623 # sql. Such as how the API is doing.
1624 # Note that we use a whitespace test rather than a \b test to avoid
1625 # any remote case where a word like on may be inside of a table name
1626 # surrounded by symbols which may be considered word breaks.
1627 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1631 # Split database and table into proper variables.
1632 # We reverse the explode so that database.table and table both output
1633 # the correct table.
1634 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1635 if ( isset( $dbDetails[1] ) ) {
1636 @list
( $table, $database ) = $dbDetails;
1638 @list
( $table ) = $dbDetails;
1640 $prefix = $this->mTablePrefix
; # Default prefix
1642 # Note that we use the long format because php will complain in in_array if
1643 # the input is not an array, and will complain in is_array if it is not set.
1644 if ( !isset( $database ) # Don't use shared database if pre selected.
1645 && isset( $wgSharedDB ) # We have a shared database
1646 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
1647 && isset( $wgSharedTables )
1648 && is_array( $wgSharedTables )
1649 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1650 $database = $wgSharedDB;
1651 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1654 # Quote the $database and $table and apply the prefix if not quoted.
1655 if ( isset( $database ) ) {
1656 $database = ( !$quoted ||
$this->isQuotedIdentifier( $database ) ?
$database : $this->addIdentifierQuotes( $database ) );
1660 $table = "{$prefix}{$table}";
1661 if ( $quoted && !$this->isQuotedIdentifier( $table ) ) {
1662 $table = $this->addIdentifierQuotes( "{$table}" );
1665 # Merge our database and table into our final table name.
1666 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
1672 * Fetch a number of table names into an array
1673 * This is handy when you need to construct SQL for joins
1676 * extract($dbr->tableNames('user','watchlist'));
1677 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1678 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1680 public function tableNames() {
1681 $inArray = func_get_args();
1684 foreach ( $inArray as $name ) {
1685 $retVal[$name] = $this->tableName( $name );
1692 * Fetch a number of table names into an zero-indexed numerical array
1693 * This is handy when you need to construct SQL for joins
1696 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1697 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1698 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1700 public function tableNamesN() {
1701 $inArray = func_get_args();
1704 foreach ( $inArray as $name ) {
1705 $retVal[] = $this->tableName( $name );
1712 * Get an aliased table name
1713 * e.g. tableName AS newTableName
1715 * @param $name string Table name, see tableName()
1716 * @param $alias string Alias (optional)
1717 * @return string SQL name for aliased table. Will not alias a table to its own name
1719 public function tableNameWithAlias( $name, $alias = false ) {
1720 if ( !$alias ||
$alias == $name ) {
1721 return $this->tableName( $name );
1723 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1728 * Gets an array of aliased table names
1730 * @param $tables array( [alias] => table )
1731 * @return array of strings, see tableNameWithAlias()
1733 public function tableNamesWithAlias( $tables ) {
1735 foreach ( $tables as $alias => $table ) {
1736 if ( is_numeric( $alias ) ) {
1739 $retval[] = $this->tableNameWithAlias( $table, $alias );
1747 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1750 $use_index_safe = is_array( $use_index ) ?
$use_index : array();
1751 $join_conds_safe = is_array( $join_conds ) ?
$join_conds : array();
1753 foreach ( $tables as $alias => $table ) {
1754 if ( !is_string( $alias ) ) {
1755 // No alias? Set it equal to the table name
1758 // Is there a JOIN and INDEX clause for this table?
1759 if ( isset( $join_conds_safe[$alias] ) && isset( $use_index_safe[$alias] ) ) {
1760 $tableClause = $join_conds_safe[$alias][0] . ' ' . $this->tableNameWithAlias( $table, $alias );
1761 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$alias] ) );
1762 $on = $this->makeList( (array)$join_conds_safe[$alias][1], LIST_AND
);
1764 $tableClause .= ' ON (' . $on . ')';
1767 $retJOIN[] = $tableClause;
1768 // Is there an INDEX clause?
1769 } else if ( isset( $use_index_safe[$alias] ) ) {
1770 $tableClause = $this->tableNameWithAlias( $table, $alias );
1771 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$alias] ) );
1772 $ret[] = $tableClause;
1773 // Is there a JOIN clause?
1774 } else if ( isset( $join_conds_safe[$alias] ) ) {
1775 $tableClause = $join_conds_safe[$alias][0] . ' ' . $this->tableNameWithAlias( $table, $alias );
1776 $on = $this->makeList( (array)$join_conds_safe[$alias][1], LIST_AND
);
1778 $tableClause .= ' ON (' . $on . ')';
1781 $retJOIN[] = $tableClause;
1783 $tableClause = $this->tableNameWithAlias( $table, $alias );
1784 $ret[] = $tableClause;
1788 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1789 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1790 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1792 // Compile our final table clause
1793 return implode( ' ', array( $straightJoins, $otherJoins ) );
1797 * Get the name of an index in a given table
1803 function indexName( $index ) {
1804 // Backwards-compatibility hack
1806 'ar_usertext_timestamp' => 'usertext_timestamp',
1807 'un_user_id' => 'user_id',
1808 'un_user_ip' => 'user_ip',
1811 if ( isset( $renamed[$index] ) ) {
1812 return $renamed[$index];
1819 * If it's a string, adds quotes and backslashes
1820 * Otherwise returns as-is
1826 function addQuotes( $s ) {
1827 if ( $s === null ) {
1830 # This will also quote numeric values. This should be harmless,
1831 # and protects against weird problems that occur when they really
1832 # _are_ strings such as article titles and string->number->string
1833 # conversion is not 1:1.
1834 return "'" . $this->strencode( $s ) . "'";
1839 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1840 * MySQL uses `backticks` while basically everything else uses double quotes.
1841 * Since MySQL is the odd one out here the double quotes are our generic
1842 * and we implement backticks in DatabaseMysql.
1846 public function addIdentifierQuotes( $s ) {
1847 return '"' . str_replace( '"', '""', $s ) . '"';
1851 * Returns if the given identifier looks quoted or not according to
1852 * the database convention for quoting identifiers .
1854 * @param $name string
1858 public function isQuotedIdentifier( $name ) {
1859 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
1863 * Backwards compatibility, identifier quoting originated in DatabasePostgres
1864 * which used quote_ident which does not follow our naming conventions
1865 * was renamed to addIdentifierQuotes.
1866 * @deprecated since 1.18 use addIdentifierQuotes
1870 function quote_ident( $s ) {
1871 wfDeprecated( __METHOD__
);
1872 return $this->addIdentifierQuotes( $s );
1876 * Escape string for safe LIKE usage.
1877 * WARNING: you should almost never use this function directly,
1878 * instead use buildLike() that escapes everything automatically
1879 * @deprecated since 1.17, warnings in 1.17, removed in ???
1881 public function escapeLike( $s ) {
1882 wfDeprecated( __METHOD__
);
1883 return $this->escapeLikeInternal( $s );
1886 protected function escapeLikeInternal( $s ) {
1887 $s = str_replace( '\\', '\\\\', $s );
1888 $s = $this->strencode( $s );
1889 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
1895 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
1896 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
1897 * Alternatively, the function could be provided with an array of aforementioned parameters.
1899 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
1900 * for subpages of 'My page title'.
1901 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
1904 * @return String: fully built LIKE statement
1906 function buildLike() {
1907 $params = func_get_args();
1909 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1910 $params = $params[0];
1915 foreach ( $params as $value ) {
1916 if ( $value instanceof LikeMatch
) {
1917 $s .= $value->toString();
1919 $s .= $this->escapeLikeInternal( $value );
1923 return " LIKE '" . $s . "' ";
1927 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1931 function anyChar() {
1932 return new LikeMatch( '_' );
1936 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1938 * @rerturn LikeMatch
1940 function anyString() {
1941 return new LikeMatch( '%' );
1945 * Returns an appropriately quoted sequence value for inserting a new row.
1946 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1947 * subclass will return an integer, and save the value for insertId()
1949 function nextSequenceValue( $seqName ) {
1954 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1955 * is only needed because a) MySQL must be as efficient as possible due to
1956 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1957 * which index to pick. Anyway, other databases might have different
1958 * indexes on a given table. So don't bother overriding this unless you're
1961 function useIndexClause( $index ) {
1966 * REPLACE query wrapper
1967 * PostgreSQL simulates this with a DELETE followed by INSERT
1968 * $row is the row to insert, an associative array
1969 * $uniqueIndexes is an array of indexes. Each element may be either a
1970 * field name or an array of field names
1972 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1973 * However if you do this, you run the risk of encountering errors which wouldn't have
1976 * @param $table String: The table to replace the row(s) in.
1977 * @param $uniqueIndexes Array: An associative array of indexes
1978 * @param $rows Array: Array of rows to replace
1979 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1981 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
1982 $table = $this->tableName( $table );
1985 if ( !is_array( reset( $rows ) ) ) {
1986 $rows = array( $rows );
1989 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
1992 foreach ( $rows as $row ) {
1999 $sql .= '(' . $this->makeList( $row ) . ')';
2002 return $this->query( $sql, $fname );
2006 * DELETE where the condition is a join
2007 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
2009 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
2010 * join condition matches, set $conds='*'
2012 * DO NOT put the join condition in $conds
2014 * @param $delTable String: The table to delete from.
2015 * @param $joinTable String: The other table.
2016 * @param $delVar String: The variable to join on, in the first table.
2017 * @param $joinVar String: The variable to join on, in the second table.
2018 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
2019 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
2021 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
2023 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
2026 $delTable = $this->tableName( $delTable );
2027 $joinTable = $this->tableName( $joinTable );
2028 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
2030 if ( $conds != '*' ) {
2031 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
2034 return $this->query( $sql, $fname );
2038 * Returns the size of a text field, or -1 for "unlimited"
2040 function textFieldSize( $table, $field ) {
2041 $table = $this->tableName( $table );
2042 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2043 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2044 $row = $this->fetchObject( $res );
2048 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2058 * A string to insert into queries to show that they're low-priority, like
2059 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2060 * string and nothing bad should happen.
2062 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
2064 function lowPriorityOption() {
2069 * DELETE query wrapper
2071 * Use $conds == "*" to delete all rows
2073 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
2075 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2078 $table = $this->tableName( $table );
2079 $sql = "DELETE FROM $table";
2081 if ( $conds != '*' ) {
2082 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2085 return $this->query( $sql, $fname );
2089 * INSERT SELECT wrapper
2090 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
2091 * Source items may be literals rather than field names, but strings should be quoted with DatabaseBase::addQuotes()
2092 * $conds may be "*" to copy the whole table
2093 * srcTable may be an array of tables.
2095 * @return ResultWrapper
2097 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseBase::insertSelect',
2098 $insertOptions = array(), $selectOptions = array() )
2100 $destTable = $this->tableName( $destTable );
2102 if ( is_array( $insertOptions ) ) {
2103 $insertOptions = implode( ' ', $insertOptions );
2106 if ( !is_array( $selectOptions ) ) {
2107 $selectOptions = array( $selectOptions );
2110 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2112 if ( is_array( $srcTable ) ) {
2113 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2115 $srcTable = $this->tableName( $srcTable );
2118 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2119 " SELECT $startOpts " . implode( ',', $varMap ) .
2120 " FROM $srcTable $useIndex ";
2122 if ( $conds != '*' ) {
2123 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2126 $sql .= " $tailOpts";
2128 return $this->query( $sql, $fname );
2132 * Construct a LIMIT query with optional offset. This is used for query
2133 * pages. The SQL should be adjusted so that only the first $limit rows
2134 * are returned. If $offset is provided as well, then the first $offset
2135 * rows should be discarded, and the next $limit rows should be returned.
2136 * If the result of the query is not ordered, then the rows to be returned
2137 * are theoretically arbitrary.
2139 * $sql is expected to be a SELECT, if that makes a difference. For
2140 * UPDATE, limitResultForUpdate should be used.
2142 * The version provided by default works in MySQL and SQLite. It will very
2143 * likely need to be overridden for most other DBMSes.
2145 * @param $sql String: SQL query we will append the limit too
2146 * @param $limit Integer: the SQL limit
2147 * @param $offset Integer the SQL offset (default false)
2151 function limitResult( $sql, $limit, $offset = false ) {
2152 if ( !is_numeric( $limit ) ) {
2153 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2156 return "$sql LIMIT "
2157 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2161 function limitResultForUpdate( $sql, $num ) {
2162 return $this->limitResult( $sql, $num, 0 );
2166 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2167 * within the UNION construct.
2170 function unionSupportsOrderAndLimit() {
2171 return true; // True for almost every DB supported
2175 * Construct a UNION query
2176 * This is used for providing overload point for other DB abstractions
2177 * not compatible with the MySQL syntax.
2178 * @param $sqls Array: SQL statements to combine
2179 * @param $all Boolean: use UNION ALL
2180 * @return String: SQL fragment
2182 function unionQueries( $sqls, $all ) {
2183 $glue = $all ?
') UNION ALL (' : ') UNION (';
2184 return '(' . implode( $glue, $sqls ) . ')';
2188 * Returns an SQL expression for a simple conditional. This doesn't need
2189 * to be overridden unless CASE isn't supported in your DBMS.
2191 * @param $cond String: SQL expression which will result in a boolean value
2192 * @param $trueVal String: SQL expression to return if true
2193 * @param $falseVal String: SQL expression to return if false
2194 * @return String: SQL fragment
2196 function conditional( $cond, $trueVal, $falseVal ) {
2197 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2201 * Returns a comand for str_replace function in SQL query.
2202 * Uses REPLACE() in MySQL
2204 * @param $orig String: column to modify
2205 * @param $old String: column to seek
2206 * @param $new String: column to replace with
2210 function strreplace( $orig, $old, $new ) {
2211 return "REPLACE({$orig}, {$old}, {$new})";
2215 * Determines if the last failure was due to a deadlock
2220 function wasDeadlock() {
2225 * Determines if the last query error was something that should be dealt
2226 * with by pinging the connection and reissuing the query.
2231 function wasErrorReissuable() {
2236 * Determines if the last failure was due to the database being read-only.
2241 function wasReadOnlyError() {
2246 * Perform a deadlock-prone transaction.
2248 * This function invokes a callback function to perform a set of write
2249 * queries. If a deadlock occurs during the processing, the transaction
2250 * will be rolled back and the callback function will be called again.
2253 * $dbw->deadlockLoop( callback, ... );
2255 * Extra arguments are passed through to the specified callback function.
2257 * Returns whatever the callback function returned on its successful,
2258 * iteration, or false on error, for example if the retry limit was
2261 function deadlockLoop() {
2262 $myFname = 'DatabaseBase::deadlockLoop';
2265 $args = func_get_args();
2266 $function = array_shift( $args );
2267 $oldIgnore = $this->ignoreErrors( true );
2268 $tries = DEADLOCK_TRIES
;
2270 if ( is_array( $function ) ) {
2271 $fname = $function[0];
2277 $retVal = call_user_func_array( $function, $args );
2278 $error = $this->lastError();
2279 $errno = $this->lastErrno();
2280 $sql = $this->lastQuery();
2283 if ( $this->wasDeadlock() ) {
2285 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
2287 $this->reportQueryError( $error, $errno, $sql, $fname );
2290 } while ( $this->wasDeadlock() && --$tries > 0 );
2292 $this->ignoreErrors( $oldIgnore );
2294 if ( $tries <= 0 ) {
2295 $this->rollback( $myFname );
2296 $this->reportQueryError( $error, $errno, $sql, $fname );
2299 $this->commit( $myFname );
2305 * Do a SELECT MASTER_POS_WAIT()
2307 * @param $pos MySQLMasterPos object
2308 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
2310 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
2311 $fname = 'DatabaseBase::masterPosWait';
2312 wfProfileIn( $fname );
2314 # Commit any open transactions
2315 if ( $this->mTrxLevel
) {
2319 if ( !is_null( $this->mFakeSlaveLag
) ) {
2320 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
2322 if ( $wait > $timeout * 1e6
) {
2323 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2324 wfProfileOut( $fname );
2326 } elseif ( $wait > 0 ) {
2327 wfDebug( "Fake slave waiting $wait us\n" );
2329 wfProfileOut( $fname );
2332 wfDebug( "Fake slave up to date ($wait us)\n" );
2333 wfProfileOut( $fname );
2338 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
2339 $encFile = $this->addQuotes( $pos->file
);
2340 $encPos = intval( $pos->pos
);
2341 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
2342 $res = $this->doQuery( $sql );
2344 if ( $res && $row = $this->fetchRow( $res ) ) {
2345 wfProfileOut( $fname );
2348 wfProfileOut( $fname );
2354 * Get the position of the master from SHOW SLAVE STATUS
2356 * @return MySQLMasterPos|false
2358 function getSlavePos() {
2359 if ( !is_null( $this->mFakeSlaveLag
) ) {
2360 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
2361 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
2365 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
2366 $row = $this->fetchObject( $res );
2369 $pos = isset( $row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
2370 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
2377 * Get the position of the master from SHOW MASTER STATUS
2379 * @return MySQLMasterPos|false
2381 function getMasterPos() {
2382 if ( $this->mFakeMaster
) {
2383 return new MySQLMasterPos( 'fake', microtime( true ) );
2386 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
2387 $row = $this->fetchObject( $res );
2390 return new MySQLMasterPos( $row->File
, $row->Position
);
2397 * Begin a transaction, committing any previously open transaction
2399 function begin( $fname = 'DatabaseBase::begin' ) {
2400 $this->query( 'BEGIN', $fname );
2401 $this->mTrxLevel
= 1;
2407 function commit( $fname = 'DatabaseBase::commit' ) {
2408 if ( $this->mTrxLevel
) {
2409 $this->query( 'COMMIT', $fname );
2410 $this->mTrxLevel
= 0;
2415 * Rollback a transaction.
2416 * No-op on non-transactional databases.
2418 function rollback( $fname = 'DatabaseBase::rollback' ) {
2419 if ( $this->mTrxLevel
) {
2420 $this->query( 'ROLLBACK', $fname, true );
2421 $this->mTrxLevel
= 0;
2426 * Creates a new table with structure copied from existing table
2427 * Note that unlike most database abstraction functions, this function does not
2428 * automatically append database prefix, because it works at a lower
2429 * abstraction level.
2430 * The table names passed to this function shall not be quoted (this
2431 * function calls addIdentifierQuotes when needed).
2433 * @param $oldName String: name of table whose structure should be copied
2434 * @param $newName String: name of table to be created
2435 * @param $temporary Boolean: whether the new table should be temporary
2436 * @param $fname String: calling function name
2437 * @return Boolean: true if operation was successful
2439 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseBase::duplicateTableStructure' ) {
2440 throw new MWException( 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2444 * List all tables on the database
2446 * @param $prefix Only show tables with this prefix, e.g. mw_
2447 * @param $fname String: calling function name
2449 function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
2450 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2454 * Return MW-style timestamp used for MySQL schema
2458 function timestamp( $ts = 0 ) {
2459 return wfTimestamp( TS_MW
, $ts );
2463 * Local database timestamp format or null
2467 function timestampOrNull( $ts = null ) {
2468 if ( is_null( $ts ) ) {
2471 return $this->timestamp( $ts );
2478 * @return ResultWrapper
2480 function resultObject( $result ) {
2481 if ( empty( $result ) ) {
2483 } elseif ( $result instanceof ResultWrapper
) {
2485 } elseif ( $result === true ) {
2486 // Successful write query
2489 return new ResultWrapper( $this, $result );
2494 * Return aggregated value alias
2496 function aggregateValue ( $valuedata, $valuename = 'value' ) {
2501 * Ping the server and try to reconnect if it there is no connection
2503 * @return bool Success or failure
2506 # Stub. Not essential to override.
2512 * Currently supported only by MySQL
2513 * @return Database replication lag in seconds
2516 return intval( $this->mFakeSlaveLag
);
2520 * Get status information from SHOW STATUS in an associative array
2524 function getStatus( $which = "%" ) {
2525 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2528 foreach ( $res as $row ) {
2529 $status[$row->Variable_name
] = $row->Value
;
2536 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2540 function maxListLen() {
2544 function encodeBlob( $b ) {
2548 function decodeBlob( $b ) {
2553 * Override database's default connection timeout. May be useful for very
2554 * long batch queries such as full-wiki dumps, where a single query reads
2555 * out over hours or days. May or may not be necessary for non-MySQL
2556 * databases. For most purposes, leaving it as a no-op should be fine.
2558 * @param $timeout Integer in seconds
2560 public function setTimeout( $timeout ) {}
2563 * Read and execute SQL commands from a file.
2564 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2565 * @param $filename String: File name to open
2566 * @param $lineCallback Callback: Optional function called before reading each line
2567 * @param $resultCallback Callback: Optional function called for each MySQL result
2568 * @param $fname String: Calling function name or false if name should be generated dynamically
2571 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
2572 wfSuppressWarnings();
2573 $fp = fopen( $filename, 'r' );
2574 wfRestoreWarnings();
2576 if ( false === $fp ) {
2577 throw new MWException( "Could not open \"{$filename}\".\n" );
2581 $fname = __METHOD__
. "( $filename )";
2585 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
2587 catch ( MWException
$e ) {
2598 * Get the full path of a patch file. Originally based on archive()
2599 * from updaters.inc. Keep in mind this always returns a patch, as
2600 * it fails back to MySQL if no DB-specific patch can be found
2602 * @param $patch String The name of the patch, like patch-something.sql
2603 * @return String Full path to patch file
2605 public function patchPath( $patch ) {
2608 $dbType = $this->getType();
2609 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
2610 return "$IP/maintenance/$dbType/archives/$patch";
2612 return "$IP/maintenance/archives/$patch";
2617 * Set variables to be used in sourceFile/sourceStream, in preference to the
2618 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
2619 * all. If it's set to false, $GLOBALS will be used.
2621 * @param $vars False, or array mapping variable name to value.
2623 function setSchemaVars( $vars ) {
2624 $this->mSchemaVars
= $vars;
2628 * Read and execute commands from an open file handle
2629 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2630 * @param $fp Resource: File handle
2631 * @param $lineCallback Callback: Optional function called before reading each line
2632 * @param $resultCallback Callback: Optional function called for each MySQL result
2633 * @param $fname String: Calling function name
2635 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseBase::sourceStream' ) {
2638 $dollarquote = false;
2640 while ( ! feof( $fp ) ) {
2641 if ( $lineCallback ) {
2642 call_user_func( $lineCallback );
2645 $line = trim( fgets( $fp ) );
2646 $sl = strlen( $line ) - 1;
2652 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
2656 # # Allow dollar quoting for function declarations
2657 if ( substr( $line, 0, 4 ) == '$mw$' ) {
2658 if ( $dollarquote ) {
2659 $dollarquote = false;
2663 $dollarquote = true;
2666 else if ( !$dollarquote ) {
2667 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
2669 $line = substr( $line, 0, $sl );
2680 $cmd = str_replace( ';;', ";", $cmd );
2681 $cmd = $this->replaceVars( $cmd );
2682 $res = $this->query( $cmd, $fname );
2684 if ( $resultCallback ) {
2685 call_user_func( $resultCallback, $res, $this );
2688 if ( false === $res ) {
2689 $err = $this->lastError();
2690 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2702 * Database independent variable replacement, replaces a set of variables
2703 * in a sql statement with their contents as given by $this->getSchemaVars().
2704 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables
2706 * '{$var}' should be used for text and is passed through the database's addQuotes method
2707 * `{$var}` should be used for identifiers (eg: table and database names), it is passed through
2708 * the database's addIdentifierQuotes method which can be overridden if the database
2709 * uses something other than backticks.
2710 * / *$var* / is just encoded, besides traditional dbprefix and tableoptions it's use should be avoided
2712 * @param $ins String: SQL statement to replace variables in
2713 * @return String The new SQL statement with variables replaced
2715 protected function replaceSchemaVars( $ins ) {
2716 $vars = $this->getSchemaVars();
2717 foreach ( $vars as $var => $value ) {
2719 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
2721 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
2723 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
2729 * Replace variables in sourced SQL
2731 protected function replaceVars( $ins ) {
2732 $ins = $this->replaceSchemaVars( $ins );
2735 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2736 array( $this, 'tableNameCallback' ), $ins );
2739 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2740 array( $this, 'indexNameCallback' ), $ins );
2746 * Get schema variables. If none have been set via setSchemaVars(), then
2747 * use some defaults from the current object.
2749 protected function getSchemaVars() {
2750 if ( $this->mSchemaVars
) {
2751 return $this->mSchemaVars
;
2753 return $this->getDefaultSchemaVars();
2758 * Get schema variables to use if none have been set via setSchemaVars().
2759 * Override this in derived classes to provide variables for tables.sql
2760 * and SQL patch files.
2762 protected function getDefaultSchemaVars() {
2767 * Table name callback
2770 protected function tableNameCallback( $matches ) {
2771 return $this->tableName( $matches[1] );
2775 * Index name callback
2777 protected function indexNameCallback( $matches ) {
2778 return $this->indexName( $matches[1] );
2782 * Build a concatenation list to feed into a SQL query
2783 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2786 function buildConcat( $stringList ) {
2787 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2791 * Acquire a named lock
2793 * Abstracted from Filestore::lock() so child classes can implement for
2796 * @param $lockName String: name of lock to aquire
2797 * @param $method String: name of method calling us
2798 * @param $timeout Integer: timeout
2801 public function lock( $lockName, $method, $timeout = 5 ) {
2808 * @param $lockName String: Name of lock to release
2809 * @param $method String: Name of method calling us
2811 * @return Returns 1 if the lock was released, 0 if the lock was not established
2812 * by this thread (in which case the lock is not released), and NULL if the named
2813 * lock did not exist
2815 public function unlock( $lockName, $method ) {
2820 * Lock specific tables
2822 * @param $read Array of tables to lock for read access
2823 * @param $write Array of tables to lock for write access
2824 * @param $method String name of caller
2825 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2827 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2832 * Unlock specific tables
2834 * @param $method String the caller
2836 public function unlockTables( $method ) {
2843 public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
2844 if( !$this->tableExists( $tableName ) ) {
2847 $sql = "DROP TABLE " . $this->tableName( $tableName );
2848 if( $this->cascadingDeletes() ) {
2851 return $this->query( $sql, $fName );
2855 * Get search engine class. All subclasses of this need to implement this
2856 * if they wish to use searching.
2860 public function getSearchEngine() {
2861 return 'SearchEngineDummy';
2865 * Find out when 'infinity' is. Most DBMSes support this. This is a special
2866 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
2867 * because "i" sorts after all numbers.
2871 public function getInfinity() {
2876 * Encode an expiry time
2878 * @param $expiry String: timestamp for expiry, or the 'infinity' string
2881 public function encodeExpiry( $expiry ) {
2882 if ( $expiry == '' ||
$expiry == $this->getInfinity() ) {
2883 return $this->getInfinity();
2885 return $this->timestamp( $expiry );
2890 * Allow or deny "big selects" for this session only. This is done by setting
2891 * the sql_big_selects session variable.
2893 * This is a MySQL-specific feature.
2895 * @param $value Mixed: true for allow, false for deny, or "default" to restore the initial value
2897 public function setBigSelects( $value = true ) {