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, $mConn = null, $mDBname;
221 protected $mOpened = false;
223 protected $mTablePrefix;
225 protected $mTrxLevel = 0;
226 protected $mErrorCount = 0;
227 protected $mLBInfo = array();
228 protected $mFakeSlaveLag = null, $mFakeMaster = false;
229 protected $mDefaultBigSelects = null;
230 protected $mSchemaVars = false;
232 # ------------------------------------------------------------------------------
234 # ------------------------------------------------------------------------------
235 # These optionally set a variable and return the previous state
238 * A string describing the current software version, and possibly
239 * other details in a user-friendly way. Will be listed on Special:Version, etc.
240 * Use getServerVersion() to get machine-friendly information.
242 * @return string: Version information from the database server
244 public function getServerInfo() {
245 return $this->getServerVersion();
249 * Boolean, controls output of large amounts of debug information
251 function debug( $debug = null ) {
252 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
256 * Turns buffering of SQL result sets on (true) or off (false).
257 * Default is "on" and it should not be changed without good reasons.
261 function bufferResults( $buffer = null ) {
262 if ( is_null( $buffer ) ) {
263 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
265 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
270 * Turns on (false) or off (true) the automatic generation and sending
271 * of a "we're sorry, but there has been a database error" page on
272 * database errors. Default is on (false). When turned off, the
273 * code should use lastErrno() and lastError() to handle the
274 * situation as appropriate.
276 function ignoreErrors( $ignoreErrors = null ) {
277 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
281 * The current depth of nested transactions
282 * @param $level Integer: , default NULL.
284 function trxLevel( $level = null ) {
285 return wfSetVar( $this->mTrxLevel
, $level );
289 * Number of errors logged, only useful when errors are ignored
291 function errorCount( $count = null ) {
292 return wfSetVar( $this->mErrorCount
, $count );
295 function tablePrefix( $prefix = null ) {
296 return wfSetVar( $this->mTablePrefix
, $prefix, true );
300 * Properties passed down from the server info array of the load balancer
302 function getLBInfo( $name = null ) {
303 if ( is_null( $name ) ) {
304 return $this->mLBInfo
;
306 if ( array_key_exists( $name, $this->mLBInfo
) ) {
307 return $this->mLBInfo
[$name];
319 function setLBInfo( $name, $value = null ) {
320 if ( is_null( $value ) ) {
321 $this->mLBInfo
= $name;
323 $this->mLBInfo
[$name] = $value;
328 * Set lag time in seconds for a fake slave
330 function setFakeSlaveLag( $lag ) {
331 $this->mFakeSlaveLag
= $lag;
335 * Make this connection a fake master
337 function setFakeMaster( $enabled = true ) {
338 $this->mFakeMaster
= $enabled;
342 * Returns true if this database supports (and uses) cascading deletes
344 function cascadingDeletes() {
349 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
351 function cleanupTriggers() {
356 * Returns true if this database is strict about what can be put into an IP field.
357 * Specifically, it uses a NULL value instead of an empty string.
359 function strictIPs() {
364 * Returns true if this database uses timestamps rather than integers
366 function realTimestamps() {
371 * Returns true if this database does an implicit sort when doing GROUP BY
373 function implicitGroupby() {
378 * Returns true if this database does an implicit order by when the column has an index
379 * For example: SELECT page_title FROM page LIMIT 1
381 function implicitOrderby() {
386 * Returns true if this database requires that SELECT DISTINCT queries require that all
387 ORDER BY expressions occur in the SELECT list per the SQL92 standard
389 function standardSelectDistinct() {
394 * Returns true if this database can do a native search on IP columns
395 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
397 function searchableIPs() {
402 * Returns true if this database can use functional indexes
404 function functionalIndexes() {
409 * Return the last query that went through DatabaseBase::query()
412 function lastQuery() {
413 return $this->mLastQuery
;
418 * Returns true if the connection may have been used for write queries.
419 * Should return true if unsure.
423 function doneWrites() {
424 return $this->mDoneWrites
;
428 * Is a connection to the database open?
432 return $this->mOpened
;
436 * Set a flag for this connection
438 * @param $flag Integer: DBO_* constants from Defines.php:
439 * - DBO_DEBUG: output some debug info (same as debug())
440 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
441 * - DBO_IGNORE: ignore errors (same as ignoreErrors())
442 * - DBO_TRX: automatically start transactions
443 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
444 * and removes it in command line mode
445 * - DBO_PERSISTENT: use persistant database connection
447 function setFlag( $flag ) {
448 $this->mFlags |
= $flag;
452 * Clear a flag for this connection
454 * @param $flag: same as setFlag()'s $flag param
456 function clearFlag( $flag ) {
457 $this->mFlags
&= ~
$flag;
461 * Returns a boolean whether the flag $flag is set for this connection
463 * @param $flag: same as setFlag()'s $flag param
466 function getFlag( $flag ) {
467 return !!( $this->mFlags
& $flag );
471 * General read-only accessor
473 function getProperty( $name ) {
480 function getWikiID() {
481 if ( $this->mTablePrefix
) {
482 return "{$this->mDBname}-{$this->mTablePrefix}";
484 return $this->mDBname
;
489 * Return a path to the DBMS-specific schema, otherwise default to tables.sql
493 public function getSchema() {
495 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
496 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
498 return "$IP/maintenance/tables.sql";
502 # ------------------------------------------------------------------------------
504 # ------------------------------------------------------------------------------
508 * @param $server String: database server host
509 * @param $user String: database user name
510 * @param $password String: database user password
511 * @param $dbName String: database name
513 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
515 function __construct( $server = false, $user = false, $password = false, $dbName = false,
516 $flags = 0, $tablePrefix = 'get from global'
518 global $wgDBprefix, $wgCommandLineMode;
520 $this->mFlags
= $flags;
522 if ( $this->mFlags
& DBO_DEFAULT
) {
523 if ( $wgCommandLineMode ) {
524 $this->mFlags
&= ~DBO_TRX
;
526 $this->mFlags |
= DBO_TRX
;
530 /** Get the default table prefix*/
531 if ( $tablePrefix == 'get from global' ) {
532 $this->mTablePrefix
= $wgDBprefix;
534 $this->mTablePrefix
= $tablePrefix;
538 $this->open( $server, $user, $password, $dbName );
543 * Same as new DatabaseMysql( ... ), kept for backward compatibility
544 * @deprecated since 1.17
546 * @return DatabaseMysql
548 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
549 wfDeprecated( __METHOD__
);
550 return new DatabaseMysql( $server, $user, $password, $dbName, $flags );
554 * Given a DB type, construct the name of the appropriate child class of
555 * DatabaseBase. This is designed to replace all of the manual stuff like:
556 * $class = 'Database' . ucfirst( strtolower( $type ) );
557 * as well as validate against the canonical list of DB types we have
559 * This factory function is mostly useful for when you need to connect to a
560 * database other than the MediaWiki default (such as for external auth,
561 * an extension, et cetera). Do not use this to connect to the MediaWiki
562 * database. Example uses in core:
563 * @see LoadBalancer::reallyOpenConnection()
564 * @see ExternalUser_MediaWiki::initFromCond()
565 * @see ForeignDBRepo::getMasterDB()
566 * @see WebInstaller_DBConnect::execute()
568 * @param $dbType String A possible DB type
569 * @param $p Array An array of options to pass to the constructor.
570 * Valid options are: host, user, password, dbname, flags, tableprefix
571 * @return DatabaseBase subclass or null
573 public final static function newFromType( $dbType, $p = array() ) {
574 $canonicalDBTypes = array(
575 'mysql', 'postgres', 'sqlite', 'oracle', 'mssql', 'ibm_db2'
577 $dbType = strtolower( $dbType );
579 if( in_array( $dbType, $canonicalDBTypes ) ) {
580 $class = 'Database' . ucfirst( $dbType );
582 isset( $p['host'] ) ?
$p['host'] : false,
583 isset( $p['user'] ) ?
$p['user'] : false,
584 isset( $p['password'] ) ?
$p['password'] : false,
585 isset( $p['dbname'] ) ?
$p['dbname'] : false,
586 isset( $p['flags'] ) ?
$p['flags'] : 0,
587 isset( $p['tableprefix'] ) ?
$p['tableprefix'] : 'get from global'
594 protected function installErrorHandler() {
595 $this->mPHPError
= false;
596 $this->htmlErrors
= ini_set( 'html_errors', '0' );
597 set_error_handler( array( $this, 'connectionErrorHandler' ) );
600 protected function restoreErrorHandler() {
601 restore_error_handler();
602 if ( $this->htmlErrors
!== false ) {
603 ini_set( 'html_errors', $this->htmlErrors
);
605 if ( $this->mPHPError
) {
606 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
607 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
614 protected function connectionErrorHandler( $errno, $errstr ) {
615 $this->mPHPError
= $errstr;
619 * Closes a database connection.
620 * if it is open : commits any open transactions
622 * @return Bool operation success. true if already closed.
625 # Stub, should probably be overridden
630 * @param $error String: fallback error message, used if none is given by DB
632 function reportConnectionError( $error = 'Unknown error' ) {
633 $myError = $this->lastError();
639 throw new DBConnectionError( $this, $error );
643 * Determine whether a query writes to the DB.
644 * Should return true if unsure.
648 function isWriteQuery( $sql ) {
649 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
653 * Usually aborts on failure. If errors are explicitly ignored, returns success.
655 * @param $sql String: SQL query
656 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
657 * comment (you can use __METHOD__ or add some extra info)
658 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
659 * maybe best to catch the exception instead?
660 * @return boolean or ResultWrapper. true for a successful write query, ResultWrapper object for a successful read query,
661 * or false on failure if $tempIgnore set
662 * @throws DBQueryError Thrown when the database returns an error of any kind
664 public function query( $sql, $fname = '', $tempIgnore = false ) {
665 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
666 if ( !Profiler
::instance()->isStub() ) {
667 # generalizeSQL will probably cut down the query to reasonable
668 # logging size most of the time. The substr is really just a sanity check.
670 # Who's been wasting my precious column space? -- TS
671 # $profName = 'query: ' . $fname . ' ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
674 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
675 $totalProf = 'DatabaseBase::query-master';
677 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
678 $totalProf = 'DatabaseBase::query';
681 wfProfileIn( $totalProf );
682 wfProfileIn( $queryProf );
685 $this->mLastQuery
= $sql;
686 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
687 // Set a flag indicating that writes have been done
688 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
689 $this->mDoneWrites
= true;
692 # Add a comment for easy SHOW PROCESSLIST interpretation
695 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
696 $userName = $wgUser->getName();
697 if ( mb_strlen( $userName ) > 15 ) {
698 $userName = mb_substr( $userName, 0, 15 ) . '...';
700 $userName = str_replace( '/', '', $userName );
704 $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
706 # $commentedSql = $sql;
709 # If DBO_TRX is set, start a transaction
710 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
711 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
712 // avoid establishing transactions for SHOW and SET statements too -
713 // that would delay transaction initializations to once connection
714 // is really used by application
715 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
716 if ( strpos( $sqlstart, "SHOW " ) !== 0 and strpos( $sqlstart, "SET " ) !== 0 )
720 if ( $this->debug() ) {
724 $sqlx = substr( $commentedSql, 0, 500 );
725 $sqlx = strtr( $sqlx, "\t\n", ' ' );
728 wfDebug( "Query $cnt (master): $sqlx\n" );
730 wfDebug( "Query $cnt (slave): $sqlx\n" );
734 if ( istainted( $sql ) & TC_MYSQL
) {
735 throw new MWException( 'Tainted query found' );
738 # Do the query and handle errors
739 $ret = $this->doQuery( $commentedSql );
741 # Try reconnecting if the connection was lost
742 if ( false === $ret && $this->wasErrorReissuable() ) {
743 # Transaction is gone, like it or not
744 $this->mTrxLevel
= 0;
745 wfDebug( "Connection lost, reconnecting...\n" );
747 if ( $this->ping() ) {
748 wfDebug( "Reconnected\n" );
749 $sqlx = substr( $commentedSql, 0, 500 );
750 $sqlx = strtr( $sqlx, "\t\n", ' ' );
751 global $wgRequestTime;
752 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
753 if ( $elapsed < 300 ) {
754 # Not a database error to lose a transaction after a minute or two
755 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
757 $ret = $this->doQuery( $commentedSql );
759 wfDebug( "Failed\n" );
763 if ( false === $ret ) {
764 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
767 if ( !Profiler
::instance()->isStub() ) {
768 wfProfileOut( $queryProf );
769 wfProfileOut( $totalProf );
772 return $this->resultObject( $ret );
776 * @param $error String
777 * @param $errno Integer
779 * @param $fname String
780 * @param $tempIgnore Boolean
782 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
783 # Ignore errors during error handling to avoid infinite recursion
784 $ignore = $this->ignoreErrors( true );
785 ++
$this->mErrorCount
;
787 if ( $ignore ||
$tempIgnore ) {
788 wfDebug( "SQL ERROR (ignored): $error\n" );
789 $this->ignoreErrors( $ignore );
791 $sql1line = str_replace( "\n", "\\n", $sql );
792 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
793 wfDebug( "SQL ERROR: " . $error . "\n" );
794 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
800 * Intended to be compatible with the PEAR::DB wrapper functions.
801 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
803 * ? = scalar value, quoted as necessary
804 * ! = raw SQL bit (a function for instance)
805 * & = filename; reads the file and inserts as a blob
806 * (we don't use this though...)
810 function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
811 /* MySQL doesn't support prepared statements (yet), so just
812 pack up the query for reference. We'll manually replace
814 return array( 'query' => $sql, 'func' => $func );
817 function freePrepared( $prepared ) {
818 /* No-op by default */
822 * Execute a prepared query with the various arguments
823 * @param $prepared String: the prepared sql
824 * @param $args Mixed: Either an array here, or put scalars as varargs
826 * @return ResultWrapper
828 function execute( $prepared, $args = null ) {
829 if ( !is_array( $args ) ) {
831 $args = func_get_args();
832 array_shift( $args );
835 $sql = $this->fillPrepared( $prepared['query'], $args );
837 return $this->query( $sql, $prepared['func'] );
841 * Prepare & execute an SQL statement, quoting and inserting arguments
842 * in the appropriate places.
843 * @param $query String
846 * @return ResultWrapper
848 function safeQuery( $query, $args = null ) {
849 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
851 if ( !is_array( $args ) ) {
853 $args = func_get_args();
854 array_shift( $args );
857 $retval = $this->execute( $prepared, $args );
858 $this->freePrepared( $prepared );
864 * For faking prepared SQL statements on DBs that don't support
866 * @param $preparedQuery String: a 'preparable' SQL statement
867 * @param $args Array of arguments to fill it with
868 * @return string executable SQL
870 function fillPrepared( $preparedQuery, $args ) {
872 $this->preparedArgs
=& $args;
874 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
875 array( &$this, 'fillPreparedArg' ), $preparedQuery );
879 * preg_callback func for fillPrepared()
880 * The arguments should be in $this->preparedArgs and must not be touched
881 * while we're doing this.
883 * @param $matches Array
887 function fillPreparedArg( $matches ) {
888 switch( $matches[1] ) {
889 case '\\?': return '?';
890 case '\\!': return '!';
891 case '\\&': return '&';
894 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
896 switch( $matches[1] ) {
897 case '?': return $this->addQuotes( $arg );
898 case '!': return $arg;
900 # return $this->addQuotes( file_get_contents( $arg ) );
901 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
903 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
908 * Free a result object
909 * @param $res Mixed: A SQL result
911 function freeResult( $res ) {
912 # Stub. Might not really need to be overridden, since results should
913 # be freed by PHP when the variable goes out of scope anyway.
917 * Simple UPDATE wrapper
918 * Usually aborts on failure
919 * If errors are explicitly ignored, returns success
921 * This function exists for historical reasons, DatabaseBase::update() has a more standard
922 * calling convention and feature set
926 function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
927 $table = $this->tableName( $table );
928 $sql = "UPDATE $table SET $var = '" .
929 $this->strencode( $value ) . "' WHERE ($cond)";
931 return (bool)$this->query( $sql, $fname );
935 * Simple SELECT wrapper, returns a single field, input must be encoded
936 * Usually aborts on failure
937 * If errors are explicitly ignored, returns FALSE on failure
939 function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField', $options = array() ) {
940 if ( !is_array( $options ) ) {
941 $options = array( $options );
944 $options['LIMIT'] = 1;
946 $res = $this->select( $table, $var, $cond, $fname, $options );
948 if ( $res === false ||
!$this->numRows( $res ) ) {
952 $row = $this->fetchRow( $res );
954 if ( $row !== false ) {
955 return reset( $row );
962 * Returns an optional USE INDEX clause to go after the table, and a
963 * string to go at the end of the query
967 * @param $options Array: associative array of options to be turned into
968 * an SQL query, valid keys are listed in the function.
971 function makeSelectOptions( $options ) {
972 $preLimitTail = $postLimitTail = '';
975 $noKeyOptions = array();
977 foreach ( $options as $key => $option ) {
978 if ( is_numeric( $key ) ) {
979 $noKeyOptions[$option] = true;
983 if ( isset( $options['GROUP BY'] ) ) {
984 $gb = is_array( $options['GROUP BY'] )
985 ?
implode( ',', $options['GROUP BY'] )
986 : $options['GROUP BY'];
987 $preLimitTail .= " GROUP BY {$gb}";
990 if ( isset( $options['HAVING'] ) ) {
991 $preLimitTail .= " HAVING {$options['HAVING']}";
994 if ( isset( $options['ORDER BY'] ) ) {
995 $ob = is_array( $options['ORDER BY'] )
996 ?
implode( ',', $options['ORDER BY'] )
997 : $options['ORDER BY'];
998 $preLimitTail .= " ORDER BY {$ob}";
1001 // if (isset($options['LIMIT'])) {
1002 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1003 // isset($options['OFFSET']) ? $options['OFFSET']
1007 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1008 $postLimitTail .= ' FOR UPDATE';
1011 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1012 $postLimitTail .= ' LOCK IN SHARE MODE';
1015 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1016 $startOpts .= 'DISTINCT';
1019 # Various MySQL extensions
1020 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1021 $startOpts .= ' /*! STRAIGHT_JOIN */';
1024 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1025 $startOpts .= ' HIGH_PRIORITY';
1028 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1029 $startOpts .= ' SQL_BIG_RESULT';
1032 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1033 $startOpts .= ' SQL_BUFFER_RESULT';
1036 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1037 $startOpts .= ' SQL_SMALL_RESULT';
1040 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1041 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1044 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1045 $startOpts .= ' SQL_CACHE';
1048 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1049 $startOpts .= ' SQL_NO_CACHE';
1052 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1053 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1058 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1064 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
1065 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1066 * @param $conds Mixed: Array or string, condition(s) for WHERE
1067 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1068 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1069 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1070 * @param $join_conds Array: Associative array of table join conditions (optional)
1071 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1072 * @return ResultWrapper|Bool Database result resource (feed to DatabaseBase::fetchObject
1073 * or whatever), or false on failure
1075 function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1076 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1078 return $this->query( $sql, $fname );
1084 * @param $table Mixed: Array or string, table name(s) (prefix auto-added). Array keys are table aliases (optional)
1085 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1086 * @param $conds Mixed: Array or string, condition(s) for WHERE
1087 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1088 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1089 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1090 * @param $join_conds Array: Associative array of table join conditions (optional)
1091 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1092 * @return string, the SQL text
1094 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1095 if ( is_array( $vars ) ) {
1096 $vars = implode( ',', $vars );
1099 if ( !is_array( $options ) ) {
1100 $options = array( $options );
1103 if ( is_array( $table ) ) {
1104 if ( !empty( $join_conds ) ||
( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) ) {
1105 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1107 $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
1109 } elseif ( $table != '' ) {
1110 if ( $table { 0 } == ' ' ) {
1111 $from = ' FROM ' . $table;
1113 $from = ' FROM ' . $this->tableName( $table );
1119 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1121 if ( !empty( $conds ) ) {
1122 if ( is_array( $conds ) ) {
1123 $conds = $this->makeList( $conds, LIST_AND
);
1125 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1127 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1130 if ( isset( $options['LIMIT'] ) )
1131 $sql = $this->limitResult( $sql, $options['LIMIT'],
1132 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1133 $sql = "$sql $postLimitTail";
1135 if ( isset( $options['EXPLAIN'] ) ) {
1136 $sql = 'EXPLAIN ' . $sql;
1143 * Single row SELECT wrapper
1144 * Aborts or returns FALSE on error
1146 * @param $table String: table name
1147 * @param $vars String: the selected variables
1148 * @param $conds Array: a condition map, terms are ANDed together.
1149 * Items with numeric keys are taken to be literal conditions
1150 * Takes an array of selected variables, and a condition map, which is ANDed
1151 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1152 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1153 * $obj- >page_id is the ID of the Astronomy article
1154 * @param $fname String: Calling function name
1155 * @param $options Array
1156 * @param $join_conds Array
1158 * @return ResultWrapper|Bool
1160 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow', $options = array(), $join_conds = array() ) {
1161 $options['LIMIT'] = 1;
1162 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1164 if ( $res === false ) {
1168 if ( !$this->numRows( $res ) ) {
1172 $obj = $this->fetchObject( $res );
1178 * Estimate rows in dataset
1179 * Returns estimated count - not necessarily an accurate estimate across different databases,
1181 * Takes same arguments as DatabaseBase::select()
1183 * @param $table String: table name
1184 * @param $vars Array: unused
1185 * @param $conds Array: filters on the table
1186 * @param $fname String: function name for profiling
1187 * @param $options Array: options for select
1188 * @return Integer: row count
1190 public function estimateRowCount( $table, $vars = '*', $conds = '', $fname = 'DatabaseBase::estimateRowCount', $options = array() ) {
1192 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1195 $row = $this->fetchRow( $res );
1196 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1203 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1204 * It's only slightly flawed. Don't use for anything important.
1206 * @param $sql String: A SQL Query
1208 static function generalizeSQL( $sql ) {
1209 # This does the same as the regexp below would do, but in such a way
1210 # as to avoid crashing php on some large strings.
1211 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1213 $sql = str_replace ( "\\\\", '', $sql );
1214 $sql = str_replace ( "\\'", '', $sql );
1215 $sql = str_replace ( "\\\"", '', $sql );
1216 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1217 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1219 # All newlines, tabs, etc replaced by single space
1220 $sql = preg_replace ( '/\s+/', ' ', $sql );
1223 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1229 * Determines whether a field exists in a table
1231 * @param $table String: table name
1232 * @param $field String: filed to check on that table
1233 * @param $fname String: calling function name (optional)
1234 * @return Boolean: whether $table has filed $field
1236 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1237 $info = $this->fieldInfo( $table, $field );
1243 * Determines whether an index exists
1244 * Usually aborts on failure
1245 * If errors are explicitly ignored, returns NULL on failure
1249 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1250 $info = $this->indexInfo( $table, $index, $fname );
1251 if ( is_null( $info ) ) {
1254 return $info !== false;
1259 * Query whether a given table exists
1265 function tableExists( $table ) {
1266 $table = $this->tableName( $table );
1267 $old = $this->ignoreErrors( true );
1268 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", __METHOD__
);
1269 $this->ignoreErrors( $old );
1275 * mysql_field_type() wrapper
1277 function fieldType( $res, $index ) {
1278 if ( $res instanceof ResultWrapper
) {
1279 $res = $res->result
;
1282 return mysql_field_type( $res, $index );
1286 * Determines if a given index is unique
1288 * @param $table string
1289 * @param $index string
1293 function indexUnique( $table, $index ) {
1294 $indexInfo = $this->indexInfo( $table, $index );
1296 if ( !$indexInfo ) {
1300 return !$indexInfo[0]->Non_unique
;
1304 * @param $options array
1307 function makeInsertOptions( $options ) {
1308 return implode( ' ', $options );
1312 * INSERT wrapper, inserts an array into a table
1314 * $a may be a single associative array, or an array of these with numeric keys, for
1317 * Usually aborts on failure
1318 * If errors are explicitly ignored, returns success
1320 * @param $table String: table name (prefix auto-added)
1321 * @param $a Array: Array of rows to insert
1322 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1323 * @param $options Mixed: Associative array of options
1327 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1328 # No rows to insert, easy just return now
1329 if ( !count( $a ) ) {
1333 $table = $this->tableName( $table );
1335 if ( !is_array( $options ) ) {
1336 $options = array( $options );
1339 $options = $this->makeInsertOptions( $options );
1341 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1343 $keys = array_keys( $a[0] );
1346 $keys = array_keys( $a );
1349 $sql = 'INSERT ' . $options .
1350 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1354 foreach ( $a as $row ) {
1360 $sql .= '(' . $this->makeList( $row ) . ')';
1363 $sql .= '(' . $this->makeList( $a ) . ')';
1366 return (bool)$this->query( $sql, $fname );
1370 * Make UPDATE options for the DatabaseBase::update function
1373 * @param $options Array: The options passed to DatabaseBase::update
1376 function makeUpdateOptions( $options ) {
1377 if ( !is_array( $options ) ) {
1378 $options = array( $options );
1383 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1384 $opts[] = $this->lowPriorityOption();
1387 if ( in_array( 'IGNORE', $options ) ) {
1391 return implode( ' ', $opts );
1395 * UPDATE wrapper, takes a condition array and a SET array
1397 * @param $table String: The table to UPDATE
1398 * @param $values Array: An array of values to SET
1399 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1400 * @param $fname String: The Class::Function calling this function
1402 * @param $options Array: An array of UPDATE options, can be one or
1403 * more of IGNORE, LOW_PRIORITY
1406 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1407 $table = $this->tableName( $table );
1408 $opts = $this->makeUpdateOptions( $options );
1409 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1411 if ( $conds != '*' ) {
1412 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1415 return $this->query( $sql, $fname );
1419 * Makes an encoded list of strings from an array
1422 * LIST_COMMA - comma separated, no field names
1423 * LIST_AND - ANDed WHERE clause (without the WHERE)
1424 * LIST_OR - ORed WHERE clause (without the WHERE)
1425 * LIST_SET - comma separated with field names, like a SET clause
1426 * LIST_NAMES - comma separated field names
1428 * In LIST_AND or LIST_OR modes, you can suffix a field with an exclamation
1429 * mark to generate a 'NOT IN' structure.
1431 * $db->makeList( array( 'field!' => array( 1,2,3 ) );
1433 * 'field' NOT IN ('1', '2', '3' );
1437 function makeList( $a, $mode = LIST_COMMA
) {
1438 if ( !is_array( $a ) ) {
1439 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1445 foreach ( $a as $field => $value ) {
1447 if ( $mode == LIST_AND
) {
1449 } elseif ( $mode == LIST_OR
) {
1458 // Support 'NOT IN' by suffixing fieldname with an exclamation mark
1460 if( substr($field,-1) == '!' ) {
1462 $field = substr($field, 0, -1 );
1465 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1466 $list .= "($value)";
1467 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1469 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1470 if ( count( $value ) == 0 ) {
1471 throw new MWException( __METHOD__
. ': empty input' );
1472 } elseif ( count( $value ) == 1 ) {
1473 // Special-case single values, as IN isn't terribly efficient
1474 // Don't necessarily assume the single key is 0; we don't
1475 // enforce linear numeric ordering on other arrays here.
1476 $value = array_values( $value );
1478 $operator = $not ?
' != ' : ' = ';
1479 $list .= $field . $operator . $this->addQuotes( $value[0] );
1481 $operator = $not ?
' NOT IN ' : ' IN ';
1482 $list .= $field . $operator . " (" . $this->makeList( $value ) . ") ";
1484 } elseif ( $value === null ) {
1485 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1486 $list .= "$field IS ";
1487 } elseif ( $mode == LIST_SET
) {
1488 $list .= "$field = ";
1492 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1493 $list .= "$field = ";
1495 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1503 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1504 * The keys on each level may be either integers or strings.
1506 * @param $data Array: organized as 2-d array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1507 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1508 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1509 * @return Mixed: string SQL fragment, or false if no items in array.
1511 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1514 foreach ( $data as $base => $sub ) {
1515 if ( count( $sub ) ) {
1516 $conds[] = $this->makeList(
1517 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1523 return $this->makeList( $conds, LIST_OR
);
1525 // Nothing to search for...
1531 * Bitwise operations
1538 function bitNot( $field ) {
1544 * @param $fieldRight
1547 function bitAnd( $fieldLeft, $fieldRight ) {
1548 return "($fieldLeft & $fieldRight)";
1553 * @param $fieldRight
1556 function bitOr( $fieldLeft, $fieldRight ) {
1557 return "($fieldLeft | $fieldRight)";
1561 * Change the current database
1563 * @todo Explain what exactly will fail if this is not overridden.
1564 * @return bool Success or failure
1566 function selectDB( $db ) {
1567 # Stub. Shouldn't cause serious problems if it's not overridden, but
1568 # if your database engine supports a concept similar to MySQL's
1569 # databases you may as well.
1570 $this->mDBname
= $db;
1575 * Get the current DB name
1577 function getDBname() {
1578 return $this->mDBname
;
1582 * Get the server hostname or IP address
1584 function getServer() {
1585 return $this->mServer
;
1589 * Format a table name ready for use in constructing an SQL query
1591 * This does two important things: it quotes the table names to clean them up,
1592 * and it adds a table prefix if only given a table name with no quotes.
1594 * All functions of this object which require a table name call this function
1595 * themselves. Pass the canonical name to such functions. This is only needed
1596 * when calling query() directly.
1598 * @param $name String: database table name
1599 * @param $quoted Boolean: Automatically pass the table name through
1600 * addIdentifierQuotes() so that it can be used in a query.
1601 * @return String: full database name
1603 function tableName( $name, $quoted = true ) {
1604 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1605 # Skip the entire process when we have a string quoted on both ends.
1606 # Note that we check the end so that we will still quote any use of
1607 # use of `database`.table. But won't break things if someone wants
1608 # to query a database table with a dot in the name.
1609 if ( $this->isQuotedIdentifier( $name ) ) {
1613 # Lets test for any bits of text that should never show up in a table
1614 # name. Basically anything like JOIN or ON which are actually part of
1615 # SQL queries, but may end up inside of the table value to combine
1616 # sql. Such as how the API is doing.
1617 # Note that we use a whitespace test rather than a \b test to avoid
1618 # any remote case where a word like on may be inside of a table name
1619 # surrounded by symbols which may be considered word breaks.
1620 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1624 # Split database and table into proper variables.
1625 # We reverse the explode so that database.table and table both output
1626 # the correct table.
1627 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1628 if ( isset( $dbDetails[1] ) ) {
1629 @list
( $table, $database ) = $dbDetails;
1631 @list
( $table ) = $dbDetails;
1633 $prefix = $this->mTablePrefix
; # Default prefix
1635 # Note that we use the long format because php will complain in in_array if
1636 # the input is not an array, and will complain in is_array if it is not set.
1637 if ( !isset( $database ) # Don't use shared database if pre selected.
1638 && isset( $wgSharedDB ) # We have a shared database
1639 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
1640 && isset( $wgSharedTables )
1641 && is_array( $wgSharedTables )
1642 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1643 $database = $wgSharedDB;
1644 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1647 # Quote the $database and $table and apply the prefix if not quoted.
1648 if ( isset( $database ) ) {
1649 $database = ( !$quoted ||
$this->isQuotedIdentifier( $database ) ?
$database : $this->addIdentifierQuotes( $database ) );
1653 $table = "{$prefix}{$table}";
1654 if ( $quoted && !$this->isQuotedIdentifier( $table ) ) {
1655 $table = $this->addIdentifierQuotes( "{$table}" );
1658 # Merge our database and table into our final table name.
1659 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
1665 * Fetch a number of table names into an array
1666 * This is handy when you need to construct SQL for joins
1669 * extract($dbr->tableNames('user','watchlist'));
1670 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1671 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1673 public function tableNames() {
1674 $inArray = func_get_args();
1677 foreach ( $inArray as $name ) {
1678 $retVal[$name] = $this->tableName( $name );
1685 * Fetch a number of table names into an zero-indexed numerical array
1686 * This is handy when you need to construct SQL for joins
1689 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1690 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1691 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1693 public function tableNamesN() {
1694 $inArray = func_get_args();
1697 foreach ( $inArray as $name ) {
1698 $retVal[] = $this->tableName( $name );
1705 * Get an aliased table name
1706 * e.g. tableName AS newTableName
1708 * @param $name string Table name, see tableName()
1709 * @param $alias string Alias (optional)
1710 * @return string SQL name for aliased table. Will not alias a table to its own name
1712 public function tableNameWithAlias( $name, $alias = false ) {
1713 if ( !$alias ||
$alias == $name ) {
1714 return $this->tableName( $name );
1716 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1721 * Gets an array of aliased table names
1723 * @param $tables array( [alias] => table )
1724 * @return array of strings, see tableNameWithAlias()
1726 public function tableNamesWithAlias( $tables ) {
1728 foreach ( $tables as $alias => $table ) {
1729 if ( is_numeric( $alias ) ) {
1732 $retval[] = $this->tableNameWithAlias( $table, $alias );
1740 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1743 $use_index_safe = is_array( $use_index ) ?
$use_index : array();
1744 $join_conds_safe = is_array( $join_conds ) ?
$join_conds : array();
1746 foreach ( $tables as $alias => $table ) {
1747 if ( !is_string( $alias ) ) {
1748 // No alias? Set it equal to the table name
1751 // Is there a JOIN and INDEX clause for this table?
1752 if ( isset( $join_conds_safe[$alias] ) && isset( $use_index_safe[$alias] ) ) {
1753 $tableClause = $join_conds_safe[$alias][0] . ' ' . $this->tableNameWithAlias( $table, $alias );
1754 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$alias] ) );
1755 $on = $this->makeList( (array)$join_conds_safe[$alias][1], LIST_AND
);
1757 $tableClause .= ' ON (' . $on . ')';
1760 $retJOIN[] = $tableClause;
1761 // Is there an INDEX clause?
1762 } else if ( isset( $use_index_safe[$alias] ) ) {
1763 $tableClause = $this->tableNameWithAlias( $table, $alias );
1764 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$alias] ) );
1765 $ret[] = $tableClause;
1766 // Is there a JOIN clause?
1767 } else if ( isset( $join_conds_safe[$alias] ) ) {
1768 $tableClause = $join_conds_safe[$alias][0] . ' ' . $this->tableNameWithAlias( $table, $alias );
1769 $on = $this->makeList( (array)$join_conds_safe[$alias][1], LIST_AND
);
1771 $tableClause .= ' ON (' . $on . ')';
1774 $retJOIN[] = $tableClause;
1776 $tableClause = $this->tableNameWithAlias( $table, $alias );
1777 $ret[] = $tableClause;
1781 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1782 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1783 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1785 // Compile our final table clause
1786 return implode( ' ', array( $straightJoins, $otherJoins ) );
1790 * Get the name of an index in a given table
1796 function indexName( $index ) {
1797 // Backwards-compatibility hack
1799 'ar_usertext_timestamp' => 'usertext_timestamp',
1800 'un_user_id' => 'user_id',
1801 'un_user_ip' => 'user_ip',
1804 if ( isset( $renamed[$index] ) ) {
1805 return $renamed[$index];
1812 * If it's a string, adds quotes and backslashes
1813 * Otherwise returns as-is
1819 function addQuotes( $s ) {
1820 if ( $s === null ) {
1823 # This will also quote numeric values. This should be harmless,
1824 # and protects against weird problems that occur when they really
1825 # _are_ strings such as article titles and string->number->string
1826 # conversion is not 1:1.
1827 return "'" . $this->strencode( $s ) . "'";
1832 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1833 * MySQL uses `backticks` while basically everything else uses double quotes.
1834 * Since MySQL is the odd one out here the double quotes are our generic
1835 * and we implement backticks in DatabaseMysql.
1839 public function addIdentifierQuotes( $s ) {
1840 return '"' . str_replace( '"', '""', $s ) . '"';
1844 * Returns if the given identifier looks quoted or not according to
1845 * the database convention for quoting identifiers .
1847 * @param $name string
1851 public function isQuotedIdentifier( $name ) {
1852 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
1856 * Backwards compatibility, identifier quoting originated in DatabasePostgres
1857 * which used quote_ident which does not follow our naming conventions
1858 * was renamed to addIdentifierQuotes.
1859 * @deprecated since 1.18 use addIdentifierQuotes
1863 function quote_ident( $s ) {
1864 wfDeprecated( __METHOD__
);
1865 return $this->addIdentifierQuotes( $s );
1869 * Escape string for safe LIKE usage.
1870 * WARNING: you should almost never use this function directly,
1871 * instead use buildLike() that escapes everything automatically
1872 * @deprecated since 1.17, warnings in 1.17, removed in ???
1874 public function escapeLike( $s ) {
1875 wfDeprecated( __METHOD__
);
1876 return $this->escapeLikeInternal( $s );
1879 protected function escapeLikeInternal( $s ) {
1880 $s = str_replace( '\\', '\\\\', $s );
1881 $s = $this->strencode( $s );
1882 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
1888 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
1889 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
1890 * Alternatively, the function could be provided with an array of aforementioned parameters.
1892 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
1893 * for subpages of 'My page title'.
1894 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
1897 * @return String: fully built LIKE statement
1899 function buildLike() {
1900 $params = func_get_args();
1902 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1903 $params = $params[0];
1908 foreach ( $params as $value ) {
1909 if ( $value instanceof LikeMatch
) {
1910 $s .= $value->toString();
1912 $s .= $this->escapeLikeInternal( $value );
1916 return " LIKE '" . $s . "' ";
1920 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1924 function anyChar() {
1925 return new LikeMatch( '_' );
1929 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1931 * @rerturn LikeMatch
1933 function anyString() {
1934 return new LikeMatch( '%' );
1938 * Returns an appropriately quoted sequence value for inserting a new row.
1939 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1940 * subclass will return an integer, and save the value for insertId()
1942 function nextSequenceValue( $seqName ) {
1947 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1948 * is only needed because a) MySQL must be as efficient as possible due to
1949 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1950 * which index to pick. Anyway, other databases might have different
1951 * indexes on a given table. So don't bother overriding this unless you're
1954 function useIndexClause( $index ) {
1959 * REPLACE query wrapper
1960 * PostgreSQL simulates this with a DELETE followed by INSERT
1961 * $row is the row to insert, an associative array
1962 * $uniqueIndexes is an array of indexes. Each element may be either a
1963 * field name or an array of field names
1965 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1966 * However if you do this, you run the risk of encountering errors which wouldn't have
1969 * @param $table String: The table to replace the row(s) in.
1970 * @param $uniqueIndexes Array: An associative array of indexes
1971 * @param $rows Array: Array of rows to replace
1972 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1974 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
1975 $table = $this->tableName( $table );
1978 if ( !is_array( reset( $rows ) ) ) {
1979 $rows = array( $rows );
1982 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
1985 foreach ( $rows as $row ) {
1992 $sql .= '(' . $this->makeList( $row ) . ')';
1995 return $this->query( $sql, $fname );
1999 * DELETE where the condition is a join
2000 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
2002 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
2003 * join condition matches, set $conds='*'
2005 * DO NOT put the join condition in $conds
2007 * @param $delTable String: The table to delete from.
2008 * @param $joinTable String: The other table.
2009 * @param $delVar String: The variable to join on, in the first table.
2010 * @param $joinVar String: The variable to join on, in the second table.
2011 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
2012 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
2014 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
2016 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
2019 $delTable = $this->tableName( $delTable );
2020 $joinTable = $this->tableName( $joinTable );
2021 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
2023 if ( $conds != '*' ) {
2024 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
2027 return $this->query( $sql, $fname );
2031 * Returns the size of a text field, or -1 for "unlimited"
2033 function textFieldSize( $table, $field ) {
2034 $table = $this->tableName( $table );
2035 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2036 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2037 $row = $this->fetchObject( $res );
2041 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2051 * A string to insert into queries to show that they're low-priority, like
2052 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2053 * string and nothing bad should happen.
2055 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
2057 function lowPriorityOption() {
2062 * DELETE query wrapper
2064 * Use $conds == "*" to delete all rows
2066 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
2068 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2071 $table = $this->tableName( $table );
2072 $sql = "DELETE FROM $table";
2074 if ( $conds != '*' ) {
2075 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2078 return $this->query( $sql, $fname );
2082 * INSERT SELECT wrapper
2083 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
2084 * Source items may be literals rather than field names, but strings should be quoted with DatabaseBase::addQuotes()
2085 * $conds may be "*" to copy the whole table
2086 * srcTable may be an array of tables.
2088 * @return ResultWrapper
2090 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseBase::insertSelect',
2091 $insertOptions = array(), $selectOptions = array() )
2093 $destTable = $this->tableName( $destTable );
2095 if ( is_array( $insertOptions ) ) {
2096 $insertOptions = implode( ' ', $insertOptions );
2099 if ( !is_array( $selectOptions ) ) {
2100 $selectOptions = array( $selectOptions );
2103 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2105 if ( is_array( $srcTable ) ) {
2106 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2108 $srcTable = $this->tableName( $srcTable );
2111 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2112 " SELECT $startOpts " . implode( ',', $varMap ) .
2113 " FROM $srcTable $useIndex ";
2115 if ( $conds != '*' ) {
2116 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2119 $sql .= " $tailOpts";
2121 return $this->query( $sql, $fname );
2125 * Construct a LIMIT query with optional offset. This is used for query
2126 * pages. The SQL should be adjusted so that only the first $limit rows
2127 * are returned. If $offset is provided as well, then the first $offset
2128 * rows should be discarded, and the next $limit rows should be returned.
2129 * If the result of the query is not ordered, then the rows to be returned
2130 * are theoretically arbitrary.
2132 * $sql is expected to be a SELECT, if that makes a difference. For
2133 * UPDATE, limitResultForUpdate should be used.
2135 * The version provided by default works in MySQL and SQLite. It will very
2136 * likely need to be overridden for most other DBMSes.
2138 * @param $sql String: SQL query we will append the limit too
2139 * @param $limit Integer: the SQL limit
2140 * @param $offset Integer the SQL offset (default false)
2144 function limitResult( $sql, $limit, $offset = false ) {
2145 if ( !is_numeric( $limit ) ) {
2146 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2149 return "$sql LIMIT "
2150 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2154 function limitResultForUpdate( $sql, $num ) {
2155 return $this->limitResult( $sql, $num, 0 );
2159 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2160 * within the UNION construct.
2163 function unionSupportsOrderAndLimit() {
2164 return true; // True for almost every DB supported
2168 * Construct a UNION query
2169 * This is used for providing overload point for other DB abstractions
2170 * not compatible with the MySQL syntax.
2171 * @param $sqls Array: SQL statements to combine
2172 * @param $all Boolean: use UNION ALL
2173 * @return String: SQL fragment
2175 function unionQueries( $sqls, $all ) {
2176 $glue = $all ?
') UNION ALL (' : ') UNION (';
2177 return '(' . implode( $glue, $sqls ) . ')';
2181 * Returns an SQL expression for a simple conditional. This doesn't need
2182 * to be overridden unless CASE isn't supported in your DBMS.
2184 * @param $cond String: SQL expression which will result in a boolean value
2185 * @param $trueVal String: SQL expression to return if true
2186 * @param $falseVal String: SQL expression to return if false
2187 * @return String: SQL fragment
2189 function conditional( $cond, $trueVal, $falseVal ) {
2190 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2194 * Returns a comand for str_replace function in SQL query.
2195 * Uses REPLACE() in MySQL
2197 * @param $orig String: column to modify
2198 * @param $old String: column to seek
2199 * @param $new String: column to replace with
2203 function strreplace( $orig, $old, $new ) {
2204 return "REPLACE({$orig}, {$old}, {$new})";
2208 * Determines if the last failure was due to a deadlock
2213 function wasDeadlock() {
2218 * Determines if the last query error was something that should be dealt
2219 * with by pinging the connection and reissuing the query.
2224 function wasErrorReissuable() {
2229 * Determines if the last failure was due to the database being read-only.
2234 function wasReadOnlyError() {
2239 * Perform a deadlock-prone transaction.
2241 * This function invokes a callback function to perform a set of write
2242 * queries. If a deadlock occurs during the processing, the transaction
2243 * will be rolled back and the callback function will be called again.
2246 * $dbw->deadlockLoop( callback, ... );
2248 * Extra arguments are passed through to the specified callback function.
2250 * Returns whatever the callback function returned on its successful,
2251 * iteration, or false on error, for example if the retry limit was
2254 function deadlockLoop() {
2255 $myFname = 'DatabaseBase::deadlockLoop';
2258 $args = func_get_args();
2259 $function = array_shift( $args );
2260 $oldIgnore = $this->ignoreErrors( true );
2261 $tries = DEADLOCK_TRIES
;
2263 if ( is_array( $function ) ) {
2264 $fname = $function[0];
2270 $retVal = call_user_func_array( $function, $args );
2271 $error = $this->lastError();
2272 $errno = $this->lastErrno();
2273 $sql = $this->lastQuery();
2276 if ( $this->wasDeadlock() ) {
2278 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
2280 $this->reportQueryError( $error, $errno, $sql, $fname );
2283 } while ( $this->wasDeadlock() && --$tries > 0 );
2285 $this->ignoreErrors( $oldIgnore );
2287 if ( $tries <= 0 ) {
2288 $this->rollback( $myFname );
2289 $this->reportQueryError( $error, $errno, $sql, $fname );
2292 $this->commit( $myFname );
2298 * Do a SELECT MASTER_POS_WAIT()
2300 * @param $pos MySQLMasterPos object
2301 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
2303 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
2304 $fname = 'DatabaseBase::masterPosWait';
2305 wfProfileIn( $fname );
2307 # Commit any open transactions
2308 if ( $this->mTrxLevel
) {
2312 if ( !is_null( $this->mFakeSlaveLag
) ) {
2313 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
2315 if ( $wait > $timeout * 1e6
) {
2316 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2317 wfProfileOut( $fname );
2319 } elseif ( $wait > 0 ) {
2320 wfDebug( "Fake slave waiting $wait us\n" );
2322 wfProfileOut( $fname );
2325 wfDebug( "Fake slave up to date ($wait us)\n" );
2326 wfProfileOut( $fname );
2331 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
2332 $encFile = $this->addQuotes( $pos->file
);
2333 $encPos = intval( $pos->pos
);
2334 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
2335 $res = $this->doQuery( $sql );
2337 if ( $res && $row = $this->fetchRow( $res ) ) {
2338 wfProfileOut( $fname );
2341 wfProfileOut( $fname );
2347 * Get the position of the master from SHOW SLAVE STATUS
2349 * @return MySQLMasterPos|false
2351 function getSlavePos() {
2352 if ( !is_null( $this->mFakeSlaveLag
) ) {
2353 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
2354 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
2358 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
2359 $row = $this->fetchObject( $res );
2362 $pos = isset( $row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
2363 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
2370 * Get the position of the master from SHOW MASTER STATUS
2372 * @return MySQLMasterPos|false
2374 function getMasterPos() {
2375 if ( $this->mFakeMaster
) {
2376 return new MySQLMasterPos( 'fake', microtime( true ) );
2379 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
2380 $row = $this->fetchObject( $res );
2383 return new MySQLMasterPos( $row->File
, $row->Position
);
2390 * Begin a transaction, committing any previously open transaction
2392 function begin( $fname = 'DatabaseBase::begin' ) {
2393 $this->query( 'BEGIN', $fname );
2394 $this->mTrxLevel
= 1;
2400 function commit( $fname = 'DatabaseBase::commit' ) {
2401 if ( $this->mTrxLevel
) {
2402 $this->query( 'COMMIT', $fname );
2403 $this->mTrxLevel
= 0;
2408 * Rollback a transaction.
2409 * No-op on non-transactional databases.
2411 function rollback( $fname = 'DatabaseBase::rollback' ) {
2412 if ( $this->mTrxLevel
) {
2413 $this->query( 'ROLLBACK', $fname, true );
2414 $this->mTrxLevel
= 0;
2419 * Creates a new table with structure copied from existing table
2420 * Note that unlike most database abstraction functions, this function does not
2421 * automatically append database prefix, because it works at a lower
2422 * abstraction level.
2423 * The table names passed to this function shall not be quoted (this
2424 * function calls addIdentifierQuotes when needed).
2426 * @param $oldName String: name of table whose structure should be copied
2427 * @param $newName String: name of table to be created
2428 * @param $temporary Boolean: whether the new table should be temporary
2429 * @param $fname String: calling function name
2430 * @return Boolean: true if operation was successful
2432 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseBase::duplicateTableStructure' ) {
2433 throw new MWException( 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2437 * List all tables on the database
2439 * @param $prefix Only show tables with this prefix, e.g. mw_
2440 * @param $fname String: calling function name
2442 function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
2443 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2447 * Return MW-style timestamp used for MySQL schema
2451 function timestamp( $ts = 0 ) {
2452 return wfTimestamp( TS_MW
, $ts );
2456 * Local database timestamp format or null
2460 function timestampOrNull( $ts = null ) {
2461 if ( is_null( $ts ) ) {
2464 return $this->timestamp( $ts );
2471 * @return ResultWrapper
2473 function resultObject( $result ) {
2474 if ( empty( $result ) ) {
2476 } elseif ( $result instanceof ResultWrapper
) {
2478 } elseif ( $result === true ) {
2479 // Successful write query
2482 return new ResultWrapper( $this, $result );
2487 * Return aggregated value alias
2489 function aggregateValue ( $valuedata, $valuename = 'value' ) {
2494 * Ping the server and try to reconnect if it there is no connection
2496 * @return bool Success or failure
2499 # Stub. Not essential to override.
2505 * Currently supported only by MySQL
2506 * @return Database replication lag in seconds
2509 return intval( $this->mFakeSlaveLag
);
2513 * Get status information from SHOW STATUS in an associative array
2517 function getStatus( $which = "%" ) {
2518 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2521 foreach ( $res as $row ) {
2522 $status[$row->Variable_name
] = $row->Value
;
2529 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2533 function maxListLen() {
2537 function encodeBlob( $b ) {
2541 function decodeBlob( $b ) {
2546 * Override database's default connection timeout. May be useful for very
2547 * long batch queries such as full-wiki dumps, where a single query reads
2548 * out over hours or days. May or may not be necessary for non-MySQL
2549 * databases. For most purposes, leaving it as a no-op should be fine.
2551 * @param $timeout Integer in seconds
2553 public function setTimeout( $timeout ) {}
2556 * Read and execute SQL commands from a file.
2557 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2558 * @param $filename String: File name to open
2559 * @param $lineCallback Callback: Optional function called before reading each line
2560 * @param $resultCallback Callback: Optional function called for each MySQL result
2561 * @param $fname String: Calling function name or false if name should be generated dynamically
2564 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
2565 wfSuppressWarnings();
2566 $fp = fopen( $filename, 'r' );
2567 wfRestoreWarnings();
2569 if ( false === $fp ) {
2570 throw new MWException( "Could not open \"{$filename}\".\n" );
2574 $fname = __METHOD__
. "( $filename )";
2578 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
2580 catch ( MWException
$e ) {
2591 * Get the full path of a patch file. Originally based on archive()
2592 * from updaters.inc. Keep in mind this always returns a patch, as
2593 * it fails back to MySQL if no DB-specific patch can be found
2595 * @param $patch String The name of the patch, like patch-something.sql
2596 * @return String Full path to patch file
2598 public function patchPath( $patch ) {
2601 $dbType = $this->getType();
2602 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
2603 return "$IP/maintenance/$dbType/archives/$patch";
2605 return "$IP/maintenance/archives/$patch";
2610 * Set variables to be used in sourceFile/sourceStream, in preference to the
2611 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
2612 * all. If it's set to false, $GLOBALS will be used.
2614 * @param $vars False, or array mapping variable name to value.
2616 function setSchemaVars( $vars ) {
2617 $this->mSchemaVars
= $vars;
2621 * Read and execute commands from an open file handle
2622 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2623 * @param $fp Resource: File handle
2624 * @param $lineCallback Callback: Optional function called before reading each line
2625 * @param $resultCallback Callback: Optional function called for each MySQL result
2626 * @param $fname String: Calling function name
2628 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseBase::sourceStream' ) {
2631 $dollarquote = false;
2633 while ( ! feof( $fp ) ) {
2634 if ( $lineCallback ) {
2635 call_user_func( $lineCallback );
2638 $line = trim( fgets( $fp ) );
2639 $sl = strlen( $line ) - 1;
2645 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
2649 # # Allow dollar quoting for function declarations
2650 if ( substr( $line, 0, 4 ) == '$mw$' ) {
2651 if ( $dollarquote ) {
2652 $dollarquote = false;
2656 $dollarquote = true;
2659 else if ( !$dollarquote ) {
2660 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
2662 $line = substr( $line, 0, $sl );
2673 $cmd = str_replace( ';;', ";", $cmd );
2674 $cmd = $this->replaceVars( $cmd );
2675 $res = $this->query( $cmd, $fname );
2677 if ( $resultCallback ) {
2678 call_user_func( $resultCallback, $res, $this );
2681 if ( false === $res ) {
2682 $err = $this->lastError();
2683 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2695 * Database independent variable replacement, replaces a set of variables
2696 * in a sql statement with their contents as given by $this->getSchemaVars().
2697 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables
2699 * '{$var}' should be used for text and is passed through the database's addQuotes method
2700 * `{$var}` should be used for identifiers (eg: table and database names), it is passed through
2701 * the database's addIdentifierQuotes method which can be overridden if the database
2702 * uses something other than backticks.
2703 * / *$var* / is just encoded, besides traditional dbprefix and tableoptions it's use should be avoided
2705 * @param $ins String: SQL statement to replace variables in
2706 * @return String The new SQL statement with variables replaced
2708 protected function replaceSchemaVars( $ins ) {
2709 $vars = $this->getSchemaVars();
2710 foreach ( $vars as $var => $value ) {
2712 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
2714 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
2716 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
2722 * Replace variables in sourced SQL
2724 protected function replaceVars( $ins ) {
2725 $ins = $this->replaceSchemaVars( $ins );
2728 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2729 array( $this, 'tableNameCallback' ), $ins );
2732 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2733 array( $this, 'indexNameCallback' ), $ins );
2739 * Get schema variables. If none have been set via setSchemaVars(), then
2740 * use some defaults from the current object.
2742 protected function getSchemaVars() {
2743 if ( $this->mSchemaVars
) {
2744 return $this->mSchemaVars
;
2746 return $this->getDefaultSchemaVars();
2751 * Get schema variables to use if none have been set via setSchemaVars().
2752 * Override this in derived classes to provide variables for tables.sql
2753 * and SQL patch files.
2755 protected function getDefaultSchemaVars() {
2760 * Table name callback
2763 protected function tableNameCallback( $matches ) {
2764 return $this->tableName( $matches[1] );
2768 * Index name callback
2770 protected function indexNameCallback( $matches ) {
2771 return $this->indexName( $matches[1] );
2775 * Build a concatenation list to feed into a SQL query
2776 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2779 function buildConcat( $stringList ) {
2780 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2784 * Acquire a named lock
2786 * Abstracted from Filestore::lock() so child classes can implement for
2789 * @param $lockName String: name of lock to aquire
2790 * @param $method String: name of method calling us
2791 * @param $timeout Integer: timeout
2794 public function lock( $lockName, $method, $timeout = 5 ) {
2801 * @param $lockName String: Name of lock to release
2802 * @param $method String: Name of method calling us
2804 * @return Returns 1 if the lock was released, 0 if the lock was not established
2805 * by this thread (in which case the lock is not released), and NULL if the named
2806 * lock did not exist
2808 public function unlock( $lockName, $method ) {
2813 * Lock specific tables
2815 * @param $read Array of tables to lock for read access
2816 * @param $write Array of tables to lock for write access
2817 * @param $method String name of caller
2818 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2820 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2825 * Unlock specific tables
2827 * @param $method String the caller
2829 public function unlockTables( $method ) {
2836 public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
2837 if( !$this->tableExists( $tableName ) ) {
2840 $sql = "DROP TABLE " . $this->tableName( $tableName );
2841 if( $this->cascadingDeletes() ) {
2844 return $this->query( $sql, $fName );
2848 * Get search engine class. All subclasses of this need to implement this
2849 * if they wish to use searching.
2853 public function getSearchEngine() {
2854 return 'SearchEngineDummy';
2858 * Find out when 'infinity' is. Most DBMSes support this. This is a special
2859 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
2860 * because "i" sorts after all numbers.
2864 public function getInfinity() {
2869 * Encode an expiry time
2871 * @param $expiry String: timestamp for expiry, or the 'infinity' string
2874 public function encodeExpiry( $expiry ) {
2875 if ( $expiry == '' ||
$expiry == $this->getInfinity() ) {
2876 return $this->getInfinity();
2878 return $this->timestamp( $expiry );
2883 * Allow or deny "big selects" for this session only. This is done by setting
2884 * the sql_big_selects session variable.
2886 * This is a MySQL-specific feature.
2888 * @param $value Mixed: true for allow, false for deny, or "default" to restore the initial value
2890 public function setBigSelects( $value = true ) {