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 SQL 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
149 function fieldInfo( $table, $field );
152 * Get information about an index into an object
153 * @param $table string: Table name
154 * @param $index string: Index name
155 * @param $fname string: Calling function name
156 * @return Mixed: Database-specific index description class or false if the index does not exist
158 function indexInfo( $table, $index, $fname = 'Database::indexInfo' );
161 * Get the number of rows affected by the last write query
162 * @see http://www.php.net/mysql_affected_rows
166 function affectedRows();
169 * Wrapper for addslashes()
171 * @param $s string: to be slashed.
172 * @return string: slashed string.
174 function strencode( $s );
177 * Returns a wikitext link to the DB's website, e.g.,
178 * return "[http://www.mysql.com/ MySQL]";
179 * Should at least contain plain text, if for some reason
180 * your database has no website.
182 * @return string: wikitext of a link to the server software's web site
184 static function getSoftwareLink();
187 * A string describing the current software version, like from
188 * mysql_get_server_info().
190 * @return string: Version information from the database server.
192 function getServerVersion();
195 * A string describing the current software version, and possibly
196 * other details in a user-friendly way. Will be listed on Special:Version, etc.
197 * Use getServerVersion() to get machine-friendly information.
199 * @return string: Version information from the database server
201 function getServerInfo();
205 * Database abstraction object
208 abstract class DatabaseBase
implements DatabaseType
{
210 # ------------------------------------------------------------------------------
212 # ------------------------------------------------------------------------------
214 protected $mLastQuery = '';
215 protected $mDoneWrites = false;
216 protected $mPHPError = false;
218 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
219 protected $mOpened = false;
221 protected $mTablePrefix;
223 protected $mTrxLevel = 0;
224 protected $mErrorCount = 0;
225 protected $mLBInfo = array();
226 protected $mFakeSlaveLag = null, $mFakeMaster = false;
227 protected $mDefaultBigSelects = null;
229 # ------------------------------------------------------------------------------
231 # ------------------------------------------------------------------------------
232 # These optionally set a variable and return the previous state
235 * A string describing the current software version, and possibly
236 * other details in a user-friendly way. Will be listed on Special:Version, etc.
237 * Use getServerVersion() to get machine-friendly information.
239 * @return string: Version information from the database server
241 public function getServerInfo() {
242 return $this->getServerVersion();
246 * Boolean, controls output of large amounts of debug information
248 function debug( $debug = null ) {
249 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
253 * Turns buffering of SQL result sets on (true) or off (false).
254 * Default is "on" and it should not be changed without good reasons.
256 function bufferResults( $buffer = null ) {
257 if ( is_null( $buffer ) ) {
258 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
260 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
265 * Turns on (false) or off (true) the automatic generation and sending
266 * of a "we're sorry, but there has been a database error" page on
267 * database errors. Default is on (false). When turned off, the
268 * code should use lastErrno() and lastError() to handle the
269 * situation as appropriate.
271 function ignoreErrors( $ignoreErrors = null ) {
272 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
276 * The current depth of nested transactions
277 * @param $level Integer: , default NULL.
279 function trxLevel( $level = null ) {
280 return wfSetVar( $this->mTrxLevel
, $level );
284 * Number of errors logged, only useful when errors are ignored
286 function errorCount( $count = null ) {
287 return wfSetVar( $this->mErrorCount
, $count );
290 function tablePrefix( $prefix = null ) {
291 return wfSetVar( $this->mTablePrefix
, $prefix, true );
295 * Properties passed down from the server info array of the load balancer
297 function getLBInfo( $name = null ) {
298 if ( is_null( $name ) ) {
299 return $this->mLBInfo
;
301 if ( array_key_exists( $name, $this->mLBInfo
) ) {
302 return $this->mLBInfo
[$name];
309 function setLBInfo( $name, $value = null ) {
310 if ( is_null( $value ) ) {
311 $this->mLBInfo
= $name;
313 $this->mLBInfo
[$name] = $value;
318 * Set lag time in seconds for a fake slave
320 function setFakeSlaveLag( $lag ) {
321 $this->mFakeSlaveLag
= $lag;
325 * Make this connection a fake master
327 function setFakeMaster( $enabled = true ) {
328 $this->mFakeMaster
= $enabled;
332 * Returns true if this database supports (and uses) cascading deletes
334 function cascadingDeletes() {
339 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
341 function cleanupTriggers() {
346 * Returns true if this database is strict about what can be put into an IP field.
347 * Specifically, it uses a NULL value instead of an empty string.
349 function strictIPs() {
354 * Returns true if this database uses timestamps rather than integers
356 function realTimestamps() {
361 * Returns true if this database does an implicit sort when doing GROUP BY
363 function implicitGroupby() {
368 * Returns true if this database does an implicit order by when the column has an index
369 * For example: SELECT page_title FROM page LIMIT 1
371 function implicitOrderby() {
376 * Returns true if this database requires that SELECT DISTINCT queries require that all
377 ORDER BY expressions occur in the SELECT list per the SQL92 standard
379 function standardSelectDistinct() {
384 * Returns true if this database can do a native search on IP columns
385 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
387 function searchableIPs() {
392 * Returns true if this database can use functional indexes
394 function functionalIndexes() {
399 * Return the last query that went through DatabaseBase::query()
402 function lastQuery() { return $this->mLastQuery
; }
406 * Returns true if the connection may have been used for write queries.
407 * Should return true if unsure.
409 function doneWrites() { return $this->mDoneWrites
; }
412 * Is a connection to the database open?
415 function isOpen() { return $this->mOpened
; }
418 * Set a flag for this connection
420 * @param $flag Integer: DBO_* constants from Defines.php:
421 * - DBO_DEBUG: output some debug info (same as debug())
422 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
423 * - DBO_IGNORE: ignore errors (same as ignoreErrors())
424 * - DBO_TRX: automatically start transactions
425 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
426 * and removes it in command line mode
427 * - DBO_PERSISTENT: use persistant database connection
429 function setFlag( $flag ) {
430 $this->mFlags |
= $flag;
434 * Clear a flag for this connection
436 * @param $flag: same as setFlag()'s $flag param
438 function clearFlag( $flag ) {
439 $this->mFlags
&= ~
$flag;
443 * Returns a boolean whether the flag $flag is set for this connection
445 * @param $flag: same as setFlag()'s $flag param
448 function getFlag( $flag ) {
449 return !!( $this->mFlags
& $flag );
453 * General read-only accessor
455 function getProperty( $name ) {
459 function getWikiID() {
460 if ( $this->mTablePrefix
) {
461 return "{$this->mDBname}-{$this->mTablePrefix}";
463 return $this->mDBname
;
468 * Return a path to the DBMS-specific schema, otherwise default to tables.sql
470 public function getSchema() {
472 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
473 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
475 return "$IP/maintenance/tables.sql";
479 # ------------------------------------------------------------------------------
481 # ------------------------------------------------------------------------------
485 * @param $server String: database server host
486 * @param $user String: database user name
487 * @param $password String: database user password
488 * @param $dbName String: database name
490 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
492 function __construct( $server = false, $user = false, $password = false, $dbName = false,
493 $flags = 0, $tablePrefix = 'get from global'
495 global $wgOut, $wgDBprefix, $wgCommandLineMode;
497 # Can't get a reference if it hasn't been set yet
498 if ( !isset( $wgOut ) ) {
501 $this->mFlags
= $flags;
503 if ( $this->mFlags
& DBO_DEFAULT
) {
504 if ( $wgCommandLineMode ) {
505 $this->mFlags
&= ~DBO_TRX
;
507 $this->mFlags |
= DBO_TRX
;
512 // Faster read-only access
513 if ( wfReadOnly() ) {
514 $this->mFlags |= DBO_PERSISTENT;
515 $this->mFlags &= ~DBO_TRX;
518 /** Get the default table prefix*/
519 if ( $tablePrefix == 'get from global' ) {
520 $this->mTablePrefix
= $wgDBprefix;
522 $this->mTablePrefix
= $tablePrefix;
526 $this->open( $server, $user, $password, $dbName );
531 * Same as new DatabaseMysql( ... ), kept for backward compatibility
532 * @param $server String: database server host
533 * @param $user String: database user name
534 * @param $password String: database user password
535 * @param $dbName String: database name
538 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
539 wfDeprecated( __METHOD__
);
540 return new DatabaseMysql( $server, $user, $password, $dbName, $flags );
544 * Given a DB type, construct the name of the appropriate child class of
545 * DatabaseBase. This is designed to replace all of the manual stuff like:
546 * $class = 'Database' . ucfirst( strtolower( $type ) );
547 * as well as validate against the canonical list of DB types we have
549 * @param $dbType String A possible DB type
550 * @return DatabaseBase subclass or null
552 public final static function classFromType( $dbType ) {
553 $canonicalDBTypes = array(
554 'mysql', 'postgres', 'sqlite', 'oracle', 'mssql', 'ibm_db2'
556 $dbType = strtolower( $dbType );
557 if( in_array( $dbType, $canonicalDBTypes ) ) {
558 return 'Database' . ucfirst( $dbType );
564 protected function installErrorHandler() {
565 $this->mPHPError
= false;
566 $this->htmlErrors
= ini_set( 'html_errors', '0' );
567 set_error_handler( array( $this, 'connectionErrorHandler' ) );
570 protected function restoreErrorHandler() {
571 restore_error_handler();
572 if ( $this->htmlErrors
!== false ) {
573 ini_set( 'html_errors', $this->htmlErrors
);
575 if ( $this->mPHPError
) {
576 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
577 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
584 protected function connectionErrorHandler( $errno, $errstr ) {
585 $this->mPHPError
= $errstr;
589 * Closes a database connection.
590 * if it is open : commits any open transactions
592 * @return Bool operation success. true if already closed.
595 # Stub, should probably be overridden
600 * @param $error String: fallback error message, used if none is given by DB
602 function reportConnectionError( $error = 'Unknown error' ) {
603 $myError = $this->lastError();
609 throw new DBConnectionError( $this, $error );
613 * Determine whether a query writes to the DB.
614 * Should return true if unsure.
616 function isWriteQuery( $sql ) {
617 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
621 * Usually aborts on failure. If errors are explicitly ignored, returns success.
623 * @param $sql String: SQL query
624 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
625 * comment (you can use __METHOD__ or add some extra info)
626 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
627 * maybe best to catch the exception instead?
628 * @return boolean or ResultWrapper. true for a successful write query, ResultWrapper object for a successful read query,
629 * or false on failure if $tempIgnore set
630 * @throws DBQueryError Thrown when the database returns an error of any kind
632 public function query( $sql, $fname = '', $tempIgnore = false ) {
635 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
636 if ( isset( $wgProfiler ) ) {
637 # generalizeSQL will probably cut down the query to reasonable
638 # logging size most of the time. The substr is really just a sanity check.
640 # Who's been wasting my precious column space? -- TS
641 # $profName = 'query: ' . $fname . ' ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
644 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
645 $totalProf = 'DatabaseBase::query-master';
647 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
648 $totalProf = 'DatabaseBase::query';
651 wfProfileIn( $totalProf );
652 wfProfileIn( $queryProf );
655 $this->mLastQuery
= $sql;
656 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
657 // Set a flag indicating that writes have been done
658 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
659 $this->mDoneWrites
= true;
662 # Add a comment for easy SHOW PROCESSLIST interpretation
665 if ( is_object( $wgUser ) && $wgUser->mDataLoaded
) {
666 $userName = $wgUser->getName();
667 if ( mb_strlen( $userName ) > 15 ) {
668 $userName = mb_substr( $userName, 0, 15 ) . '...';
670 $userName = str_replace( '/', '', $userName );
674 $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
676 # $commentedSql = $sql;
679 # If DBO_TRX is set, start a transaction
680 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
681 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
682 // avoid establishing transactions for SHOW and SET statements too -
683 // that would delay transaction initializations to once connection
684 // is really used by application
685 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
686 if ( strpos( $sqlstart, "SHOW " ) !== 0 and strpos( $sqlstart, "SET " ) !== 0 )
690 if ( $this->debug() ) {
694 $sqlx = substr( $commentedSql, 0, 500 );
695 $sqlx = strtr( $sqlx, "\t\n", ' ' );
698 wfDebug( "Query $cnt (master): $sqlx\n" );
700 wfDebug( "Query $cnt (slave): $sqlx\n" );
704 if ( istainted( $sql ) & TC_MYSQL
) {
705 throw new MWException( 'Tainted query found' );
708 # Do the query and handle errors
709 $ret = $this->doQuery( $commentedSql );
711 # Try reconnecting if the connection was lost
712 if ( false === $ret && $this->wasErrorReissuable() ) {
713 # Transaction is gone, like it or not
714 $this->mTrxLevel
= 0;
715 wfDebug( "Connection lost, reconnecting...\n" );
717 if ( $this->ping() ) {
718 wfDebug( "Reconnected\n" );
719 $sqlx = substr( $commentedSql, 0, 500 );
720 $sqlx = strtr( $sqlx, "\t\n", ' ' );
721 global $wgRequestTime;
722 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
723 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
724 $ret = $this->doQuery( $commentedSql );
726 wfDebug( "Failed\n" );
730 if ( false === $ret ) {
731 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
734 if ( isset( $wgProfiler ) ) {
735 wfProfileOut( $queryProf );
736 wfProfileOut( $totalProf );
739 return $this->resultObject( $ret );
743 * @param $error String
744 * @param $errno Integer
746 * @param $fname String
747 * @param $tempIgnore Boolean
749 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
750 # Ignore errors during error handling to avoid infinite recursion
751 $ignore = $this->ignoreErrors( true );
752 ++
$this->mErrorCount
;
754 if ( $ignore ||
$tempIgnore ) {
755 wfDebug( "SQL ERROR (ignored): $error\n" );
756 $this->ignoreErrors( $ignore );
758 $sql1line = str_replace( "\n", "\\n", $sql );
759 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
760 wfDebug( "SQL ERROR: " . $error . "\n" );
761 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
767 * Intended to be compatible with the PEAR::DB wrapper functions.
768 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
770 * ? = scalar value, quoted as necessary
771 * ! = raw SQL bit (a function for instance)
772 * & = filename; reads the file and inserts as a blob
773 * (we don't use this though...)
775 function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
776 /* MySQL doesn't support prepared statements (yet), so just
777 pack up the query for reference. We'll manually replace
779 return array( 'query' => $sql, 'func' => $func );
782 function freePrepared( $prepared ) {
783 /* No-op by default */
787 * Execute a prepared query with the various arguments
788 * @param $prepared String: the prepared sql
789 * @param $args Mixed: Either an array here, or put scalars as varargs
791 function execute( $prepared, $args = null ) {
792 if ( !is_array( $args ) ) {
794 $args = func_get_args();
795 array_shift( $args );
798 $sql = $this->fillPrepared( $prepared['query'], $args );
800 return $this->query( $sql, $prepared['func'] );
804 * Prepare & execute an SQL statement, quoting and inserting arguments
805 * in the appropriate places.
806 * @param $query String
809 function safeQuery( $query, $args = null ) {
810 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
812 if ( !is_array( $args ) ) {
814 $args = func_get_args();
815 array_shift( $args );
818 $retval = $this->execute( $prepared, $args );
819 $this->freePrepared( $prepared );
825 * For faking prepared SQL statements on DBs that don't support
827 * @param $preparedQuery String: a 'preparable' SQL statement
828 * @param $args Array of arguments to fill it with
829 * @return string executable SQL
831 function fillPrepared( $preparedQuery, $args ) {
833 $this->preparedArgs
=& $args;
835 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
836 array( &$this, 'fillPreparedArg' ), $preparedQuery );
840 * preg_callback func for fillPrepared()
841 * The arguments should be in $this->preparedArgs and must not be touched
842 * while we're doing this.
844 * @param $matches Array
848 function fillPreparedArg( $matches ) {
849 switch( $matches[1] ) {
850 case '\\?': return '?';
851 case '\\!': return '!';
852 case '\\&': return '&';
855 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
857 switch( $matches[1] ) {
858 case '?': return $this->addQuotes( $arg );
859 case '!': return $arg;
861 # return $this->addQuotes( file_get_contents( $arg ) );
862 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
864 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
869 * Free a result object
870 * @param $res Mixed: A SQL result
872 function freeResult( $res ) {
873 # Stub. Might not really need to be overridden, since results should
874 # be freed by PHP when the variable goes out of scope anyway.
878 * Simple UPDATE wrapper
879 * Usually aborts on failure
880 * If errors are explicitly ignored, returns success
882 * This function exists for historical reasons, DatabaseBase::update() has a more standard
883 * calling convention and feature set
885 function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
886 $table = $this->tableName( $table );
887 $sql = "UPDATE $table SET $var = '" .
888 $this->strencode( $value ) . "' WHERE ($cond)";
890 return (bool)$this->query( $sql, $fname );
894 * Simple SELECT wrapper, returns a single field, input must be encoded
895 * Usually aborts on failure
896 * If errors are explicitly ignored, returns FALSE on failure
898 function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField', $options = array() ) {
899 if ( !is_array( $options ) ) {
900 $options = array( $options );
903 $options['LIMIT'] = 1;
905 $res = $this->select( $table, $var, $cond, $fname, $options );
907 if ( $res === false ||
!$this->numRows( $res ) ) {
911 $row = $this->fetchRow( $res );
913 if ( $row !== false ) {
914 return reset( $row );
921 * Returns an optional USE INDEX clause to go after the table, and a
922 * string to go at the end of the query
926 * @param $options Array: associative array of options to be turned into
927 * an SQL query, valid keys are listed in the function.
930 function makeSelectOptions( $options ) {
931 $preLimitTail = $postLimitTail = '';
934 $noKeyOptions = array();
936 foreach ( $options as $key => $option ) {
937 if ( is_numeric( $key ) ) {
938 $noKeyOptions[$option] = true;
942 if ( isset( $options['GROUP BY'] ) ) {
943 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
946 if ( isset( $options['HAVING'] ) ) {
947 $preLimitTail .= " HAVING {$options['HAVING']}";
950 if ( isset( $options['ORDER BY'] ) ) {
951 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
954 // if (isset($options['LIMIT'])) {
955 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
956 // isset($options['OFFSET']) ? $options['OFFSET']
960 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
961 $postLimitTail .= ' FOR UPDATE';
964 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
965 $postLimitTail .= ' LOCK IN SHARE MODE';
968 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
969 $startOpts .= 'DISTINCT';
972 # Various MySQL extensions
973 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
974 $startOpts .= ' /*! STRAIGHT_JOIN */';
977 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
978 $startOpts .= ' HIGH_PRIORITY';
981 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
982 $startOpts .= ' SQL_BIG_RESULT';
985 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
986 $startOpts .= ' SQL_BUFFER_RESULT';
989 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
990 $startOpts .= ' SQL_SMALL_RESULT';
993 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
994 $startOpts .= ' SQL_CALC_FOUND_ROWS';
997 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
998 $startOpts .= ' SQL_CACHE';
1001 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1002 $startOpts .= ' SQL_NO_CACHE';
1005 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1006 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1011 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1017 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
1018 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1019 * @param $conds Mixed: Array or string, condition(s) for WHERE
1020 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1021 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1022 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1023 * @param $join_conds Array: Associative array of table join conditions (optional)
1024 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1025 * @return mixed Database result resource (feed to DatabaseBase::fetchObject or whatever), or false on failure
1027 function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1028 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1030 return $this->query( $sql, $fname );
1036 * @param $table Mixed: Array or string, table name(s) (prefix auto-added). Array keys are table aliases (optional)
1037 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1038 * @param $conds Mixed: Array or string, condition(s) for WHERE
1039 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1040 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1041 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1042 * @param $join_conds Array: Associative array of table join conditions (optional)
1043 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1044 * @return string, the SQL text
1046 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1047 if ( is_array( $vars ) ) {
1048 $vars = implode( ',', $vars );
1051 if ( !is_array( $options ) ) {
1052 $options = array( $options );
1055 if ( is_array( $table ) ) {
1056 if ( !empty( $join_conds ) ||
( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) ) {
1057 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1059 $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
1061 } elseif ( $table != '' ) {
1062 if ( $table { 0 } == ' ' ) {
1063 $from = ' FROM ' . $table;
1065 $from = ' FROM ' . $this->tableName( $table );
1071 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1073 if ( !empty( $conds ) ) {
1074 if ( is_array( $conds ) ) {
1075 $conds = $this->makeList( $conds, LIST_AND
);
1077 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1079 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1082 if ( isset( $options['LIMIT'] ) )
1083 $sql = $this->limitResult( $sql, $options['LIMIT'],
1084 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1085 $sql = "$sql $postLimitTail";
1087 if ( isset( $options['EXPLAIN'] ) ) {
1088 $sql = 'EXPLAIN ' . $sql;
1095 * Single row SELECT wrapper
1096 * Aborts or returns FALSE on error
1098 * @param $table String: table name
1099 * @param $vars String: the selected variables
1100 * @param $conds Array: a condition map, terms are ANDed together.
1101 * Items with numeric keys are taken to be literal conditions
1102 * Takes an array of selected variables, and a condition map, which is ANDed
1103 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1104 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1105 * $obj- >page_id is the ID of the Astronomy article
1106 * @param $fname String: Calling function name
1107 * @param $options Array
1108 * @param $join_conds Array
1110 * @todo migrate documentation to phpdocumentor format
1112 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow', $options = array(), $join_conds = array() ) {
1113 $options['LIMIT'] = 1;
1114 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1116 if ( $res === false ) {
1120 if ( !$this->numRows( $res ) ) {
1124 $obj = $this->fetchObject( $res );
1130 * Estimate rows in dataset
1131 * Returns estimated count - not necessarily an accurate estimate across different databases,
1133 * Takes same arguments as DatabaseBase::select()
1135 * @param $table String: table name
1136 * @param $vars Array: unused
1137 * @param $conds Array: filters on the table
1138 * @param $fname String: function name for profiling
1139 * @param $options Array: options for select
1140 * @return Integer: row count
1142 public function estimateRowCount( $table, $vars = '*', $conds = '', $fname = 'DatabaseBase::estimateRowCount', $options = array() ) {
1144 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1147 $row = $this->fetchRow( $res );
1148 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1155 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1156 * It's only slightly flawed. Don't use for anything important.
1158 * @param $sql String: A SQL Query
1160 static function generalizeSQL( $sql ) {
1161 # This does the same as the regexp below would do, but in such a way
1162 # as to avoid crashing php on some large strings.
1163 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1165 $sql = str_replace ( "\\\\", '', $sql );
1166 $sql = str_replace ( "\\'", '', $sql );
1167 $sql = str_replace ( "\\\"", '', $sql );
1168 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1169 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1171 # All newlines, tabs, etc replaced by single space
1172 $sql = preg_replace ( '/\s+/', ' ', $sql );
1175 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1181 * Determines whether a field exists in a table
1183 * @param $table String: table name
1184 * @param $field String: filed to check on that table
1185 * @param $fname String: calling function name (optional)
1186 * @return Boolean: whether $table has filed $field
1188 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1189 $info = $this->fieldInfo( $table, $field );
1195 * Determines whether an index exists
1196 * Usually aborts on failure
1197 * If errors are explicitly ignored, returns NULL on failure
1199 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1200 $info = $this->indexInfo( $table, $index, $fname );
1201 if ( is_null( $info ) ) {
1204 return $info !== false;
1209 * Query whether a given table exists
1211 function tableExists( $table ) {
1212 $table = $this->tableName( $table );
1213 $old = $this->ignoreErrors( true );
1214 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", __METHOD__
);
1215 $this->ignoreErrors( $old );
1221 * mysql_field_type() wrapper
1223 function fieldType( $res, $index ) {
1224 if ( $res instanceof ResultWrapper
) {
1225 $res = $res->result
;
1228 return mysql_field_type( $res, $index );
1232 * Determines if a given index is unique
1234 function indexUnique( $table, $index ) {
1235 $indexInfo = $this->indexInfo( $table, $index );
1237 if ( !$indexInfo ) {
1241 return !$indexInfo[0]->Non_unique
;
1245 * INSERT wrapper, inserts an array into a table
1247 * $a may be a single associative array, or an array of these with numeric keys, for
1250 * Usually aborts on failure
1251 * If errors are explicitly ignored, returns success
1253 * @param $table String: table name (prefix auto-added)
1254 * @param $a Array: Array of rows to insert
1255 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1256 * @param $options Mixed: Associative array of options
1260 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1261 # No rows to insert, easy just return now
1262 if ( !count( $a ) ) {
1266 $table = $this->tableName( $table );
1268 if ( !is_array( $options ) ) {
1269 $options = array( $options );
1272 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1274 $keys = array_keys( $a[0] );
1277 $keys = array_keys( $a );
1280 $sql = 'INSERT ' . implode( ' ', $options ) .
1281 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1285 foreach ( $a as $row ) {
1291 $sql .= '(' . $this->makeList( $row ) . ')';
1294 $sql .= '(' . $this->makeList( $a ) . ')';
1297 return (bool)$this->query( $sql, $fname );
1301 * Make UPDATE options for the DatabaseBase::update function
1304 * @param $options Array: The options passed to DatabaseBase::update
1307 function makeUpdateOptions( $options ) {
1308 if ( !is_array( $options ) ) {
1309 $options = array( $options );
1314 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1315 $opts[] = $this->lowPriorityOption();
1318 if ( in_array( 'IGNORE', $options ) ) {
1322 return implode( ' ', $opts );
1326 * UPDATE wrapper, takes a condition array and a SET array
1328 * @param $table String: The table to UPDATE
1329 * @param $values Array: An array of values to SET
1330 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1331 * @param $fname String: The Class::Function calling this function
1333 * @param $options Array: An array of UPDATE options, can be one or
1334 * more of IGNORE, LOW_PRIORITY
1337 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1338 $table = $this->tableName( $table );
1339 $opts = $this->makeUpdateOptions( $options );
1340 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1342 if ( $conds != '*' ) {
1343 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1346 return $this->query( $sql, $fname );
1350 * Makes an encoded list of strings from an array
1352 * LIST_COMMA - comma separated, no field names
1353 * LIST_AND - ANDed WHERE clause (without the WHERE)
1354 * LIST_OR - ORed WHERE clause (without the WHERE)
1355 * LIST_SET - comma separated with field names, like a SET clause
1356 * LIST_NAMES - comma separated field names
1358 function makeList( $a, $mode = LIST_COMMA
) {
1359 if ( !is_array( $a ) ) {
1360 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1366 foreach ( $a as $field => $value ) {
1368 if ( $mode == LIST_AND
) {
1370 } elseif ( $mode == LIST_OR
) {
1379 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1380 $list .= "($value)";
1381 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1383 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1384 if ( count( $value ) == 0 ) {
1385 throw new MWException( __METHOD__
. ': empty input' );
1386 } elseif ( count( $value ) == 1 ) {
1387 // Special-case single values, as IN isn't terribly efficient
1388 // Don't necessarily assume the single key is 0; we don't
1389 // enforce linear numeric ordering on other arrays here.
1390 $value = array_values( $value );
1391 $list .= $field . " = " . $this->addQuotes( $value[0] );
1393 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1395 } elseif ( $value === null ) {
1396 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1397 $list .= "$field IS ";
1398 } elseif ( $mode == LIST_SET
) {
1399 $list .= "$field = ";
1403 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1404 $list .= "$field = ";
1406 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1414 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1415 * The keys on each level may be either integers or strings.
1417 * @param $data Array: organized as 2-d array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1418 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1419 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1420 * @return Mixed: string SQL fragment, or false if no items in array.
1422 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1425 foreach ( $data as $base => $sub ) {
1426 if ( count( $sub ) ) {
1427 $conds[] = $this->makeList(
1428 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1434 return $this->makeList( $conds, LIST_OR
);
1436 // Nothing to search for...
1442 * Bitwise operations
1445 function bitNot( $field ) {
1449 function bitAnd( $fieldLeft, $fieldRight ) {
1450 return "($fieldLeft & $fieldRight)";
1453 function bitOr( $fieldLeft, $fieldRight ) {
1454 return "($fieldLeft | $fieldRight)";
1458 * Change the current database
1460 * @todo Explain what exactly will fail if this is not overridden.
1461 * @return bool Success or failure
1463 function selectDB( $db ) {
1464 # Stub. Shouldn't cause serious problems if it's not overridden, but
1465 # if your database engine supports a concept similar to MySQL's
1466 # databases you may as well.
1471 * Get the current DB name
1473 function getDBname() {
1474 return $this->mDBname
;
1478 * Get the server hostname or IP address
1480 function getServer() {
1481 return $this->mServer
;
1485 * Format a table name ready for use in constructing an SQL query
1487 * This does two important things: it quotes the table names to clean them up,
1488 * and it adds a table prefix if only given a table name with no quotes.
1490 * All functions of this object which require a table name call this function
1491 * themselves. Pass the canonical name to such functions. This is only needed
1492 * when calling query() directly.
1494 * @param $name String: database table name
1495 * @return String: full database name
1497 function tableName( $name ) {
1498 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1499 # Skip the entire process when we have a string quoted on both ends.
1500 # Note that we check the end so that we will still quote any use of
1501 # use of `database`.table. But won't break things if someone wants
1502 # to query a database table with a dot in the name.
1503 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) {
1507 # Lets test for any bits of text that should never show up in a table
1508 # name. Basically anything like JOIN or ON which are actually part of
1509 # SQL queries, but may end up inside of the table value to combine
1510 # sql. Such as how the API is doing.
1511 # Note that we use a whitespace test rather than a \b test to avoid
1512 # any remote case where a word like on may be inside of a table name
1513 # surrounded by symbols which may be considered word breaks.
1514 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1518 # Split database and table into proper variables.
1519 # We reverse the explode so that database.table and table both output
1520 # the correct table.
1521 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1522 if ( isset( $dbDetails[1] ) ) {
1523 @list
( $table, $database ) = $dbDetails;
1525 @list
( $table ) = $dbDetails;
1527 $prefix = $this->mTablePrefix
; # Default prefix
1529 # A database name has been specified in input. Quote the table name
1530 # because we don't want any prefixes added.
1531 if ( isset( $database ) ) {
1532 $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
1535 # Note that we use the long format because php will complain in in_array if
1536 # the input is not an array, and will complain in is_array if it is not set.
1537 if ( !isset( $database ) # Don't use shared database if pre selected.
1538 && isset( $wgSharedDB ) # We have a shared database
1539 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1540 && isset( $wgSharedTables )
1541 && is_array( $wgSharedTables )
1542 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1543 $database = $wgSharedDB;
1544 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1547 # Quote the $database and $table and apply the prefix if not quoted.
1548 if ( isset( $database ) ) {
1549 $database = ( $database[0] == '`' ?
$database : "`{$database}`" );
1551 $table = ( $table[0] == '`' ?
$table : "`{$prefix}{$table}`" );
1553 # Merge our database and table into our final table name.
1554 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
1560 * Fetch a number of table names into an array
1561 * This is handy when you need to construct SQL for joins
1564 * extract($dbr->tableNames('user','watchlist'));
1565 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1566 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1568 public function tableNames() {
1569 $inArray = func_get_args();
1572 foreach ( $inArray as $name ) {
1573 $retVal[$name] = $this->tableName( $name );
1580 * Fetch a number of table names into an zero-indexed numerical array
1581 * This is handy when you need to construct SQL for joins
1584 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1585 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1586 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1588 public function tableNamesN() {
1589 $inArray = func_get_args();
1592 foreach ( $inArray as $name ) {
1593 $retVal[] = $this->tableName( $name );
1600 * Get an aliased table name
1601 * e.g. tableName AS newTableName
1603 * @param $name string Table name, see tableName()
1604 * @param $alias string Alias (optional)
1605 * @return string SQL name for aliased table. Will not alias a table to its own name
1607 public function tableNameWithAlias( $name, $alias = false ) {
1608 if ( !$alias ||
$alias == $name ) {
1609 return $this->tableName( $name );
1611 return $this->tableName( $name ) . ' `' . $alias . '`';
1616 * Gets an array of aliased table names
1618 * @param $tables array( [alias] => table )
1619 * @return array of strings, see tableNameWithAlias()
1621 public function tableNamesWithAlias( $tables ) {
1623 foreach ( $tables as $alias => $table ) {
1624 if ( is_numeric( $alias ) ) {
1627 $retval[] = $this->tableNameWithAlias( $table, $alias );
1635 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1638 $use_index_safe = is_array( $use_index ) ?
$use_index : array();
1639 $join_conds_safe = is_array( $join_conds ) ?
$join_conds : array();
1641 foreach ( $tables as $alias => $table ) {
1642 if ( !is_string( $alias ) ) {
1643 // No alias? Set it equal to the table name
1646 // Is there a JOIN and INDEX clause for this table?
1647 if ( isset( $join_conds_safe[$alias] ) && isset( $use_index_safe[$alias] ) ) {
1648 $tableClause = $join_conds_safe[$alias][0] . ' ' . $this->tableNameWithAlias( $table, $alias );
1649 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$alias] ) );
1650 $on = $this->makeList( (array)$join_conds_safe[$alias][1], LIST_AND
);
1652 $tableClause .= ' ON (' . $on . ')';
1655 $retJOIN[] = $tableClause;
1656 // Is there an INDEX clause?
1657 } else if ( isset( $use_index_safe[$alias] ) ) {
1658 $tableClause = $this->tableNameWithAlias( $table, $alias );
1659 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$alias] ) );
1660 $ret[] = $tableClause;
1661 // Is there a JOIN clause?
1662 } else if ( isset( $join_conds_safe[$alias] ) ) {
1663 $tableClause = $join_conds_safe[$alias][0] . ' ' . $this->tableNameWithAlias( $table, $alias );
1664 $on = $this->makeList( (array)$join_conds_safe[$alias][1], LIST_AND
);
1666 $tableClause .= ' ON (' . $on . ')';
1669 $retJOIN[] = $tableClause;
1671 $tableClause = $this->tableNameWithAlias( $table, $alias );
1672 $ret[] = $tableClause;
1676 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1677 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1678 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1680 // Compile our final table clause
1681 return implode( ' ', array( $straightJoins, $otherJoins ) );
1685 * Get the name of an index in a given table
1687 function indexName( $index ) {
1688 // Backwards-compatibility hack
1690 'ar_usertext_timestamp' => 'usertext_timestamp',
1691 'un_user_id' => 'user_id',
1692 'un_user_ip' => 'user_ip',
1695 if ( isset( $renamed[$index] ) ) {
1696 return $renamed[$index];
1703 * If it's a string, adds quotes and backslashes
1704 * Otherwise returns as-is
1706 function addQuotes( $s ) {
1707 if ( $s === null ) {
1710 # This will also quote numeric values. This should be harmless,
1711 # and protects against weird problems that occur when they really
1712 # _are_ strings such as article titles and string->number->string
1713 # conversion is not 1:1.
1714 return "'" . $this->strencode( $s ) . "'";
1719 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1720 * MySQL uses `backticks` while basically everything else uses double quotes.
1721 * Since MySQL is the odd one out here the double quotes are our generic
1722 * and we implement backticks in DatabaseMysql.
1724 public function addIdentifierQuotes( $s ) {
1725 return '"' . str_replace( '"', '""', $s ) . '"';
1729 * Backwards compatibility, identifier quoting originated in DatabasePostgres
1730 * which used quote_ident which does not follow our naming conventions
1731 * was renamed to addIdentifierQuotes.
1732 * @deprecated use addIdentifierQuotes
1734 function quote_ident( $s ) {
1735 wfDeprecated( __METHOD__
);
1736 return $this->addIdentifierQuotes( $s );
1740 * Escape string for safe LIKE usage.
1741 * WARNING: you should almost never use this function directly,
1742 * instead use buildLike() that escapes everything automatically
1743 * Deprecated in 1.17, warnings in 1.17, removed in ???
1745 public function escapeLike( $s ) {
1746 wfDeprecated( __METHOD__
);
1747 return $this->escapeLikeInternal( $s );
1750 protected function escapeLikeInternal( $s ) {
1751 $s = str_replace( '\\', '\\\\', $s );
1752 $s = $this->strencode( $s );
1753 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
1759 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
1760 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
1761 * Alternatively, the function could be provided with an array of aforementioned parameters.
1763 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
1764 * for subpages of 'My page title'.
1765 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
1768 * @return String: fully built LIKE statement
1770 function buildLike() {
1771 $params = func_get_args();
1773 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1774 $params = $params[0];
1779 foreach ( $params as $value ) {
1780 if ( $value instanceof LikeMatch
) {
1781 $s .= $value->toString();
1783 $s .= $this->escapeLikeInternal( $value );
1787 return " LIKE '" . $s . "' ";
1791 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1793 function anyChar() {
1794 return new LikeMatch( '_' );
1798 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1800 function anyString() {
1801 return new LikeMatch( '%' );
1805 * Returns an appropriately quoted sequence value for inserting a new row.
1806 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1807 * subclass will return an integer, and save the value for insertId()
1809 function nextSequenceValue( $seqName ) {
1814 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1815 * is only needed because a) MySQL must be as efficient as possible due to
1816 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1817 * which index to pick. Anyway, other databases might have different
1818 * indexes on a given table. So don't bother overriding this unless you're
1821 function useIndexClause( $index ) {
1826 * REPLACE query wrapper
1827 * PostgreSQL simulates this with a DELETE followed by INSERT
1828 * $row is the row to insert, an associative array
1829 * $uniqueIndexes is an array of indexes. Each element may be either a
1830 * field name or an array of field names
1832 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1833 * However if you do this, you run the risk of encountering errors which wouldn't have
1836 * @param $table String: The table to replace the row(s) in.
1837 * @param $uniqueIndexes Array: An associative array of indexes
1838 * @param $rows Array: Array of rows to replace
1839 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1841 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
1842 $table = $this->tableName( $table );
1845 if ( !is_array( reset( $rows ) ) ) {
1846 $rows = array( $rows );
1849 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
1852 foreach ( $rows as $row ) {
1859 $sql .= '(' . $this->makeList( $row ) . ')';
1862 return $this->query( $sql, $fname );
1866 * DELETE where the condition is a join
1867 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1869 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1870 * join condition matches, set $conds='*'
1872 * DO NOT put the join condition in $conds
1874 * @param $delTable String: The table to delete from.
1875 * @param $joinTable String: The other table.
1876 * @param $delVar String: The variable to join on, in the first table.
1877 * @param $joinVar String: The variable to join on, in the second table.
1878 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1879 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1881 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
1883 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
1886 $delTable = $this->tableName( $delTable );
1887 $joinTable = $this->tableName( $joinTable );
1888 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1890 if ( $conds != '*' ) {
1891 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1894 return $this->query( $sql, $fname );
1898 * Returns the size of a text field, or -1 for "unlimited"
1900 function textFieldSize( $table, $field ) {
1901 $table = $this->tableName( $table );
1902 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1903 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
1904 $row = $this->fetchObject( $res );
1908 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1918 * A string to insert into queries to show that they're low-priority, like
1919 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
1920 * string and nothing bad should happen.
1922 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1924 function lowPriorityOption() {
1929 * DELETE query wrapper
1931 * Use $conds == "*" to delete all rows
1933 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
1935 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
1938 $table = $this->tableName( $table );
1939 $sql = "DELETE FROM $table";
1941 if ( $conds != '*' ) {
1942 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1945 return $this->query( $sql, $fname );
1949 * INSERT SELECT wrapper
1950 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1951 * Source items may be literals rather than field names, but strings should be quoted with DatabaseBase::addQuotes()
1952 * $conds may be "*" to copy the whole table
1953 * srcTable may be an array of tables.
1955 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseBase::insertSelect',
1956 $insertOptions = array(), $selectOptions = array() )
1958 $destTable = $this->tableName( $destTable );
1960 if ( is_array( $insertOptions ) ) {
1961 $insertOptions = implode( ' ', $insertOptions );
1964 if ( !is_array( $selectOptions ) ) {
1965 $selectOptions = array( $selectOptions );
1968 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1970 if ( is_array( $srcTable ) ) {
1971 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1973 $srcTable = $this->tableName( $srcTable );
1976 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1977 " SELECT $startOpts " . implode( ',', $varMap ) .
1978 " FROM $srcTable $useIndex ";
1980 if ( $conds != '*' ) {
1981 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1984 $sql .= " $tailOpts";
1986 return $this->query( $sql, $fname );
1990 * Construct a LIMIT query with optional offset. This is used for query
1991 * pages. The SQL should be adjusted so that only the first $limit rows
1992 * are returned. If $offset is provided as well, then the first $offset
1993 * rows should be discarded, and the next $limit rows should be returned.
1994 * If the result of the query is not ordered, then the rows to be returned
1995 * are theoretically arbitrary.
1997 * $sql is expected to be a SELECT, if that makes a difference. For
1998 * UPDATE, limitResultForUpdate should be used.
2000 * The version provided by default works in MySQL and SQLite. It will very
2001 * likely need to be overridden for most other DBMSes.
2003 * @param $sql String: SQL query we will append the limit too
2004 * @param $limit Integer: the SQL limit
2005 * @param $offset Integer the SQL offset (default false)
2007 function limitResult( $sql, $limit, $offset = false ) {
2008 if ( !is_numeric( $limit ) ) {
2009 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2012 return "$sql LIMIT "
2013 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2017 function limitResultForUpdate( $sql, $num ) {
2018 return $this->limitResult( $sql, $num, 0 );
2022 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2023 * within the UNION construct.
2026 function unionSupportsOrderAndLimit() {
2027 return true; // True for almost every DB supported
2031 * Construct a UNION query
2032 * This is used for providing overload point for other DB abstractions
2033 * not compatible with the MySQL syntax.
2034 * @param $sqls Array: SQL statements to combine
2035 * @param $all Boolean: use UNION ALL
2036 * @return String: SQL fragment
2038 function unionQueries( $sqls, $all ) {
2039 $glue = $all ?
') UNION ALL (' : ') UNION (';
2040 return '(' . implode( $glue, $sqls ) . ')';
2044 * Returns an SQL expression for a simple conditional. This doesn't need
2045 * to be overridden unless CASE isn't supported in your DBMS.
2047 * @param $cond String: SQL expression which will result in a boolean value
2048 * @param $trueVal String: SQL expression to return if true
2049 * @param $falseVal String: SQL expression to return if false
2050 * @return String: SQL fragment
2052 function conditional( $cond, $trueVal, $falseVal ) {
2053 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2057 * Returns a comand for str_replace function in SQL query.
2058 * Uses REPLACE() in MySQL
2060 * @param $orig String: column to modify
2061 * @param $old String: column to seek
2062 * @param $new String: column to replace with
2064 function strreplace( $orig, $old, $new ) {
2065 return "REPLACE({$orig}, {$old}, {$new})";
2069 * Determines if the last failure was due to a deadlock
2072 function wasDeadlock() {
2077 * Determines if the last query error was something that should be dealt
2078 * with by pinging the connection and reissuing the query.
2081 function wasErrorReissuable() {
2086 * Determines if the last failure was due to the database being read-only.
2089 function wasReadOnlyError() {
2094 * Perform a deadlock-prone transaction.
2096 * This function invokes a callback function to perform a set of write
2097 * queries. If a deadlock occurs during the processing, the transaction
2098 * will be rolled back and the callback function will be called again.
2101 * $dbw->deadlockLoop( callback, ... );
2103 * Extra arguments are passed through to the specified callback function.
2105 * Returns whatever the callback function returned on its successful,
2106 * iteration, or false on error, for example if the retry limit was
2109 function deadlockLoop() {
2110 $myFname = 'DatabaseBase::deadlockLoop';
2113 $args = func_get_args();
2114 $function = array_shift( $args );
2115 $oldIgnore = $this->ignoreErrors( true );
2116 $tries = DEADLOCK_TRIES
;
2118 if ( is_array( $function ) ) {
2119 $fname = $function[0];
2125 $retVal = call_user_func_array( $function, $args );
2126 $error = $this->lastError();
2127 $errno = $this->lastErrno();
2128 $sql = $this->lastQuery();
2131 if ( $this->wasDeadlock() ) {
2133 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
2135 $this->reportQueryError( $error, $errno, $sql, $fname );
2138 } while ( $this->wasDeadlock() && --$tries > 0 );
2140 $this->ignoreErrors( $oldIgnore );
2142 if ( $tries <= 0 ) {
2143 $this->rollback( $myFname );
2144 $this->reportQueryError( $error, $errno, $sql, $fname );
2147 $this->commit( $myFname );
2153 * Do a SELECT MASTER_POS_WAIT()
2155 * @param $pos MySQLMasterPos object
2156 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
2158 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
2159 $fname = 'DatabaseBase::masterPosWait';
2160 wfProfileIn( $fname );
2162 # Commit any open transactions
2163 if ( $this->mTrxLevel
) {
2167 if ( !is_null( $this->mFakeSlaveLag
) ) {
2168 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
2170 if ( $wait > $timeout * 1e6
) {
2171 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2172 wfProfileOut( $fname );
2174 } elseif ( $wait > 0 ) {
2175 wfDebug( "Fake slave waiting $wait us\n" );
2177 wfProfileOut( $fname );
2180 wfDebug( "Fake slave up to date ($wait us)\n" );
2181 wfProfileOut( $fname );
2186 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
2187 $encFile = $this->addQuotes( $pos->file
);
2188 $encPos = intval( $pos->pos
);
2189 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
2190 $res = $this->doQuery( $sql );
2192 if ( $res && $row = $this->fetchRow( $res ) ) {
2193 wfProfileOut( $fname );
2196 wfProfileOut( $fname );
2202 * Get the position of the master from SHOW SLAVE STATUS
2204 function getSlavePos() {
2205 if ( !is_null( $this->mFakeSlaveLag
) ) {
2206 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
2207 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
2211 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
2212 $row = $this->fetchObject( $res );
2215 $pos = isset( $row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
2216 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
2223 * Get the position of the master from SHOW MASTER STATUS
2225 function getMasterPos() {
2226 if ( $this->mFakeMaster
) {
2227 return new MySQLMasterPos( 'fake', microtime( true ) );
2230 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
2231 $row = $this->fetchObject( $res );
2234 return new MySQLMasterPos( $row->File
, $row->Position
);
2241 * Begin a transaction, committing any previously open transaction
2243 function begin( $fname = 'DatabaseBase::begin' ) {
2244 $this->query( 'BEGIN', $fname );
2245 $this->mTrxLevel
= 1;
2251 function commit( $fname = 'DatabaseBase::commit' ) {
2252 if ( $this->mTrxLevel
) {
2253 $this->query( 'COMMIT', $fname );
2254 $this->mTrxLevel
= 0;
2259 * Rollback a transaction.
2260 * No-op on non-transactional databases.
2262 function rollback( $fname = 'DatabaseBase::rollback' ) {
2263 if ( $this->mTrxLevel
) {
2264 $this->query( 'ROLLBACK', $fname, true );
2265 $this->mTrxLevel
= 0;
2270 * Begin a transaction, committing any previously open transaction
2271 * @deprecated use begin()
2273 function immediateBegin( $fname = 'DatabaseBase::immediateBegin' ) {
2274 wfDeprecated( __METHOD__
);
2279 * Commit transaction, if one is open
2280 * @deprecated use commit()
2282 function immediateCommit( $fname = 'DatabaseBase::immediateCommit' ) {
2283 wfDeprecated( __METHOD__
);
2288 * Creates a new table with structure copied from existing table
2289 * Note that unlike most database abstraction functions, this function does not
2290 * automatically append database prefix, because it works at a lower
2291 * abstraction level.
2293 * @param $oldName String: name of table whose structure should be copied
2294 * @param $newName String: name of table to be created
2295 * @param $temporary Boolean: whether the new table should be temporary
2296 * @param $fname String: calling function name
2297 * @return Boolean: true if operation was successful
2299 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseBase::duplicateTableStructure' ) {
2300 throw new MWException( 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2304 * List all tables on the database
2306 * @param $prefix Only show tables with this prefix, e.g. mw_
2307 * @param $fname String: calling function name
2309 function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
2310 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2314 * Return MW-style timestamp used for MySQL schema
2316 function timestamp( $ts = 0 ) {
2317 return wfTimestamp( TS_MW
, $ts );
2321 * Local database timestamp format or null
2323 function timestampOrNull( $ts = null ) {
2324 if ( is_null( $ts ) ) {
2327 return $this->timestamp( $ts );
2334 function resultObject( $result ) {
2335 if ( empty( $result ) ) {
2337 } elseif ( $result instanceof ResultWrapper
) {
2339 } elseif ( $result === true ) {
2340 // Successful write query
2343 return new ResultWrapper( $this, $result );
2348 * Return aggregated value alias
2350 function aggregateValue ( $valuedata, $valuename = 'value' ) {
2355 * Ping the server and try to reconnect if it there is no connection
2357 * @return bool Success or failure
2360 # Stub. Not essential to override.
2366 * Currently supported only by MySQL
2367 * @return Database replication lag in seconds
2370 return intval( $this->mFakeSlaveLag
);
2374 * Get status information from SHOW STATUS in an associative array
2376 function getStatus( $which = "%" ) {
2377 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2380 foreach ( $res as $row ) {
2381 $status[$row->Variable_name
] = $row->Value
;
2388 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2390 function maxListLen() {
2394 function encodeBlob( $b ) {
2398 function decodeBlob( $b ) {
2403 * Override database's default connection timeout. May be useful for very
2404 * long batch queries such as full-wiki dumps, where a single query reads
2405 * out over hours or days. May or may not be necessary for non-MySQL
2406 * databases. For most purposes, leaving it as a no-op should be fine.
2408 * @param $timeout Integer in seconds
2410 public function setTimeout( $timeout ) {}
2413 * Read and execute SQL commands from a file.
2414 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2415 * @param $filename String: File name to open
2416 * @param $lineCallback Callback: Optional function called before reading each line
2417 * @param $resultCallback Callback: Optional function called for each MySQL result
2418 * @param $fname String: Calling function name or false if name should be generated dynamically
2421 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
2422 wfSuppressWarnings();
2423 $fp = fopen( $filename, 'r' );
2424 wfRestoreWarnings();
2426 if ( false === $fp ) {
2427 throw new MWException( "Could not open \"{$filename}\".\n" );
2431 $fname = __METHOD__
. "( $filename )";
2435 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
2437 catch ( MWException
$e ) {
2448 * Get the full path of a patch file. Originally based on archive()
2449 * from updaters.inc. Keep in mind this always returns a patch, as
2450 * it fails back to MySQL if no DB-specific patch can be found
2452 * @param $patch String The name of the patch, like patch-something.sql
2453 * @return String Full path to patch file
2455 public function patchPath( $patch ) {
2458 $dbType = $this->getType();
2459 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
2460 return "$IP/maintenance/$dbType/archives/$patch";
2462 return "$IP/maintenance/archives/$patch";
2467 * Read and execute commands from an open file handle
2468 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2469 * @param $fp String: File handle
2470 * @param $lineCallback Callback: Optional function called before reading each line
2471 * @param $resultCallback Callback: Optional function called for each MySQL result
2472 * @param $fname String: Calling function name
2474 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseBase::sourceStream' ) {
2477 $dollarquote = false;
2479 while ( ! feof( $fp ) ) {
2480 if ( $lineCallback ) {
2481 call_user_func( $lineCallback );
2484 $line = trim( fgets( $fp, 1024 ) );
2485 $sl = strlen( $line ) - 1;
2491 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
2495 # # Allow dollar quoting for function declarations
2496 if ( substr( $line, 0, 4 ) == '$mw$' ) {
2497 if ( $dollarquote ) {
2498 $dollarquote = false;
2502 $dollarquote = true;
2505 else if ( !$dollarquote ) {
2506 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
2508 $line = substr( $line, 0, $sl );
2519 $cmd = str_replace( ';;', ";", $cmd );
2520 $cmd = $this->replaceVars( $cmd );
2521 $res = $this->query( $cmd, $fname );
2523 if ( $resultCallback ) {
2524 call_user_func( $resultCallback, $res, $this );
2527 if ( false === $res ) {
2528 $err = $this->lastError();
2529 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2541 * Database independent variable replacement, replaces a set of named variables
2542 * in a sql statement with the contents of their global variables.
2543 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables
2545 * '{$var}' should be used for text and is passed through the database's addQuotes method
2546 * `{$var}` should be used for identifiers (eg: table and database names), it is passed through
2547 * the database's addIdentifierQuotes method which can be overridden if the database
2548 * uses something other than backticks.
2549 * / *$var* / is just encoded, besides traditional dbprefix and tableoptions it's use should be avoided
2551 * @param $ins String: SQL statement to replace variables in
2552 * @param $varnames Array: Array of global variable names to replace
2553 * @return String The new SQL statement with variables replaced
2555 protected function replaceGlobalVars( $ins, $varnames ) {
2556 foreach ( $varnames as $var ) {
2557 if ( isset( $GLOBALS[$var] ) ) {
2558 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $GLOBALS[$var] ), $ins ); // replace '{$var}'
2559 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $GLOBALS[$var] ), $ins ); // replace `{$var}`
2560 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $GLOBALS[$var] ) , $ins ); // replace /*$var*/
2567 * Replace variables in sourced SQL
2569 protected function replaceVars( $ins ) {
2571 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2572 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2573 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2576 $ins = $this->replaceGlobalVars( $ins, $varnames );
2579 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2580 array( $this, 'tableNameCallback' ), $ins );
2583 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2584 array( $this, 'indexNameCallback' ), $ins );
2590 * Table name callback
2593 protected function tableNameCallback( $matches ) {
2594 return $this->tableName( $matches[1] );
2598 * Index name callback
2600 protected function indexNameCallback( $matches ) {
2601 return $this->indexName( $matches[1] );
2605 * Build a concatenation list to feed into a SQL query
2606 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2609 function buildConcat( $stringList ) {
2610 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2614 * Acquire a named lock
2616 * Abstracted from Filestore::lock() so child classes can implement for
2619 * @param $lockName String: name of lock to aquire
2620 * @param $method String: name of method calling us
2621 * @param $timeout Integer: timeout
2624 public function lock( $lockName, $method, $timeout = 5 ) {
2631 * @param $lockName String: Name of lock to release
2632 * @param $method String: Name of method calling us
2634 * @return Returns 1 if the lock was released, 0 if the lock was not established
2635 * by this thread (in which case the lock is not released), and NULL if the named
2636 * lock did not exist
2638 public function unlock( $lockName, $method ) {
2643 * Lock specific tables
2645 * @param $read Array of tables to lock for read access
2646 * @param $write Array of tables to lock for write access
2647 * @param $method String name of caller
2648 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2650 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2655 * Unlock specific tables
2657 * @param $method String the caller
2659 public function unlockTables( $method ) {
2666 public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
2667 if( !$this->tableExists( $tableName ) ) {
2670 $sql = "DROP TABLE " . $this->tableName( $tableName );
2671 if( $this->cascadingDeletes() ) {
2674 return $this->query( $sql, $fName );
2678 * Get search engine class. All subclasses of this need to implement this
2679 * if they wish to use searching.
2683 public function getSearchEngine() {
2684 return 'SearchEngineDummy';
2688 * Find out when 'infinity' is. Most DBMSes support this. This is a special
2689 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
2690 * because "i" sorts after all numbers.
2694 public function getInfinity() {
2699 * Allow or deny "big selects" for this session only. This is done by setting
2700 * the sql_big_selects session variable.
2702 * This is a MySQL-specific feature.
2704 * @param $value Mixed: true for allow, false for deny, or "default" to restore the initial value
2706 public function setBigSelects( $value = true ) {
2711 /******************************************************************************
2713 *****************************************************************************/
2722 function __construct( $data ) {
2723 $this->mData
= $data;
2731 return $this->mData
;
2739 * This allows us to distinguish a blob from a normal string and an array of strings
2744 function __construct( $data ) {
2745 $this->mData
= $data;
2749 return $this->mData
;
2754 * Base for all database-specific classes representing information about database fields
2765 * Name of table this field belongs to
2768 function tableName();
2777 * Whether this field can store NULL values
2780 function isNullable();
2783 /******************************************************************************
2785 *****************************************************************************/
2788 * Database error base class
2791 class DBError
extends MWException
{
2795 * Construct a database error
2796 * @param $db Database object which threw the error
2797 * @param $error A simple error message to be used for debugging
2799 function __construct( DatabaseBase
&$db, $error ) {
2801 parent
::__construct( $error );
2804 function getText() {
2805 global $wgShowDBErrorBacktrace;
2807 $s = $this->getMessage() . "\n";
2809 if ( $wgShowDBErrorBacktrace ) {
2810 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2820 class DBConnectionError
extends DBError
{
2823 function __construct( DatabaseBase
&$db, $error = 'unknown error' ) {
2824 $msg = 'DB connection error';
2826 if ( trim( $error ) != '' ) {
2830 $this->error
= $error;
2832 parent
::__construct( $db, $msg );
2835 function useOutputPage() {
2836 // Not likely to work
2840 function useMessageCache() {
2841 // Not likely to work
2845 function getLogMessage() {
2846 # Don't send to the exception log
2850 function getPageTitle() {
2851 global $wgSitename, $wgLang;
2853 $header = "$wgSitename has a problem";
2855 if ( $wgLang instanceof Language
) {
2856 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2862 function getHTML() {
2863 global $wgLang, $wgMessageCache, $wgUseFileCache, $wgShowDBErrorBacktrace;
2865 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2866 $again = 'Try waiting a few minutes and reloading.';
2867 $info = '(Can\'t contact the database server: $1)';
2869 if ( $wgLang instanceof Language
) {
2870 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2871 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2872 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2875 # No database access
2876 if ( is_object( $wgMessageCache ) ) {
2877 $wgMessageCache->disable();
2880 if ( trim( $this->error
) == '' ) {
2881 $this->error
= $this->db
->getProperty( 'mServer' );
2884 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2885 $text = str_replace( '$1', $this->error
, $noconnect );
2887 if ( $wgShowDBErrorBacktrace ) {
2888 $text .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2891 $extra = $this->searchForm();
2893 if ( $wgUseFileCache ) {
2895 $cache = $this->fileCachedPage();
2896 # Cached version on file system?
2897 if ( $cache !== null ) {
2898 # Hack: extend the body for error messages
2899 $cache = str_replace( array( '</html>', '</body>' ), '', $cache );
2900 # Add cache notice...
2901 $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2903 # Localize it if possible...
2904 if ( $wgLang instanceof Language
) {
2905 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2908 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2910 # Output cached page with notices on bottom and re-close body
2911 return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2913 } catch ( MWException
$e ) {
2914 // Do nothing, just use the default page
2918 # Headers needed here - output is just the error message
2919 return $this->htmlHeader() . "$text<hr />$extra" . $this->htmlFooter();
2922 function searchForm() {
2923 global $wgSitename, $wgServer, $wgLang;
2925 $usegoogle = "You can try searching via Google in the meantime.";
2926 $outofdate = "Note that their indexes of our content may be out of date.";
2927 $googlesearch = "Search";
2929 if ( $wgLang instanceof Language
) {
2930 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2931 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2932 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2935 $search = htmlspecialchars( @$_REQUEST['search'] );
2937 $server = htmlspecialchars( $wgServer );
2938 $sitename = htmlspecialchars( $wgSitename );
2941 <div style="margin: 1.5em">$usegoogle<br />
2942 <small>$outofdate</small></div>
2943 <!-- SiteSearch Google -->
2944 <form method="get" action="http://www.google.com/search" id="googlesearch">
2945 <input type="hidden" name="domains" value="$server" />
2946 <input type="hidden" name="num" value="50" />
2947 <input type="hidden" name="ie" value="UTF-8" />
2948 <input type="hidden" name="oe" value="UTF-8" />
2950 <input type="text" name="q" size="31" maxlength="255" value="$search" />
2951 <input type="submit" name="btnG" value="$googlesearch" />
2953 <input type="radio" name="sitesearch" id="gwiki" value="$server" checked="checked" /><label for="gwiki">$sitename</label>
2954 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
2957 <!-- SiteSearch Google -->
2962 private function fileCachedPage() {
2963 global $wgTitle, $wgLang, $wgOut;
2965 if ( $wgOut->isDisabled() ) {
2966 return; // Done already?
2969 $mainpage = 'Main Page';
2971 if ( $wgLang instanceof Language
) {
2972 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
2978 $t = Title
::newFromText( $mainpage );
2981 $cache = new HTMLFileCache( $t );
2982 if ( $cache->isFileCached() ) {
2983 return $cache->fetchPageText();
2989 function htmlBodyOnly() {
2997 class DBQueryError
extends DBError
{
2998 public $error, $errno, $sql, $fname;
3000 function __construct( DatabaseBase
&$db, $error, $errno, $sql, $fname ) {
3001 $message = "A database error has occurred. Did you forget to run maintenance/update.php after upgrading? See: http://www.mediawiki.org/wiki/Manual:Upgrading#Run_the_update_script\n" .
3003 "Function: $fname\n" .
3004 "Error: $errno $error\n";
3006 parent
::__construct( $db, $message );
3008 $this->error
= $error;
3009 $this->errno
= $errno;
3011 $this->fname
= $fname;
3014 function getText() {
3015 global $wgShowDBErrorBacktrace;
3017 if ( $this->useMessageCache() ) {
3018 $s = wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
3019 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
3021 if ( $wgShowDBErrorBacktrace ) {
3022 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
3027 return parent
::getText();
3032 global $wgShowSQLErrors;
3034 if ( !$wgShowSQLErrors ) {
3035 return $this->msg( 'sqlhidden', 'SQL hidden' );
3041 function getLogMessage() {
3042 # Don't send to the exception log
3046 function getPageTitle() {
3047 return $this->msg( 'databaseerror', 'Database error' );
3050 function getHTML() {
3051 global $wgShowDBErrorBacktrace;
3053 if ( $this->useMessageCache() ) {
3054 $s = wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
3055 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
3057 $s = nl2br( htmlspecialchars( $this->getMessage() ) );
3060 if ( $wgShowDBErrorBacktrace ) {
3061 $s .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
3071 class DBUnexpectedError
extends DBError
{}
3075 * Result wrapper for grabbing data queried by someone else
3078 class ResultWrapper
implements Iterator
{
3079 var $db, $result, $pos = 0, $currentRow = null;
3082 * Create a new result object from a result resource and a Database object
3084 function __construct( $database, $result ) {
3085 $this->db
= $database;
3087 if ( $result instanceof ResultWrapper
) {
3088 $this->result
= $result->result
;
3090 $this->result
= $result;
3095 * Get the number of rows in a result object
3097 function numRows() {
3098 return $this->db
->numRows( $this );
3102 * Fetch the next row from the given result object, in object form.
3103 * Fields can be retrieved with $row->fieldname, with fields acting like
3106 * @return MySQL row object
3107 * @throws DBUnexpectedError Thrown if the database returns an error
3109 function fetchObject() {
3110 return $this->db
->fetchObject( $this );
3114 * Fetch the next row from the given result object, in associative array
3115 * form. Fields are retrieved with $row['fieldname'].
3117 * @return MySQL row object
3118 * @throws DBUnexpectedError Thrown if the database returns an error
3120 function fetchRow() {
3121 return $this->db
->fetchRow( $this );
3125 * Free a result object
3128 $this->db
->freeResult( $this );
3129 unset( $this->result
);
3134 * Change the position of the cursor in a result object
3135 * See mysql_data_seek()
3137 function seek( $row ) {
3138 $this->db
->dataSeek( $this, $row );
3141 /*********************
3142 * Iterator functions
3143 * Note that using these in combination with the non-iterator functions
3144 * above may cause rows to be skipped or repeated.
3148 if ( $this->numRows() ) {
3149 $this->db
->dataSeek( $this, 0 );
3152 $this->currentRow
= null;
3155 function current() {
3156 if ( is_null( $this->currentRow
) ) {
3159 return $this->currentRow
;
3168 $this->currentRow
= $this->fetchObject();
3169 return $this->currentRow
;
3173 return $this->current() !== false;
3178 * Overloads the relevant methods of the real ResultsWrapper so it
3179 * doesn't go anywhere near an actual database.
3181 class FakeResultWrapper
extends ResultWrapper
{
3182 var $result = array();
3183 var $db = null; // And it's going to stay that way :D
3185 var $currentRow = null;
3187 function __construct( $array ) {
3188 $this->result
= $array;
3191 function numRows() {
3192 return count( $this->result
);
3195 function fetchRow() {
3196 $this->currentRow
= $this->result
[$this->pos++
];
3197 return $this->currentRow
;
3200 function seek( $row ) {
3206 // Callers want to be able to access fields with $this->fieldName
3207 function fetchObject() {
3208 $this->currentRow
= $this->result
[$this->pos++
];
3209 return (object)$this->currentRow
;
3214 $this->currentRow
= null;
3219 * Used by DatabaseBase::buildLike() to represent characters that have special meaning in SQL LIKE clauses
3220 * and thus need no escaping. Don't instantiate it manually, use DatabaseBase::anyChar() and anyString() instead.
3225 public function __construct( $s ) {
3229 public function toString() {