3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
10 * Depends on the CacheManager
12 require_once( 'CacheManager.php' );
15 define( 'LIST_COMMA', 0 );
17 define( 'LIST_AND', 1 );
19 define( 'LIST_SET', 2 );
21 define( 'LIST_NAMES', 3);
23 /** Number of times to re-try an operation in case of deadlock */
24 define( 'DEADLOCK_TRIES', 4 );
25 /** Minimum time to wait before retry, in microseconds */
26 define( 'DEADLOCK_DELAY_MIN', 500000 );
27 /** Maximum time to wait before retry */
28 define( 'DEADLOCK_DELAY_MAX', 1500000 );
31 * Database abstraction object
37 #------------------------------------------------------------------------------
39 #------------------------------------------------------------------------------
45 var $mServer, $mUser, $mPassword, $mConn, $mDBname;
46 var $mOut, $mOpened = false;
54 #------------------------------------------------------------------------------
56 #------------------------------------------------------------------------------
57 # These optionally set a variable and return the previous state
60 * Fail function, takes a Database as a parameter
61 * Set to false for default, 1 for ignore errors
63 function failFunction( $function = NULL ) {
64 return wfSetVar( $this->mFailFunction
, $function );
68 * Output page, used for reporting errors
69 * FALSE means discard output
71 function &setOutputPage( &$out ) {
76 * Boolean, controls output of large amounts of debug information
78 function debug( $debug = NULL ) {
79 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
83 * Turns buffering of SQL result sets on (true) or off (false).
84 * Default is "on" and it should not be changed without good reasons.
86 function bufferResults( $buffer = NULL ) {
87 if ( is_null( $buffer ) ) {
88 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
90 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
95 * Turns on (false) or off (true) the automatic generation and sending
96 * of a "we're sorry, but there has been a database error" page on
97 * database errors. Default is on (false). When turned off, the
98 * code should use wfLastErrno() and wfLastError() to handle the
99 * situation as appropriate.
101 function ignoreErrors( $ignoreErrors = NULL ) {
102 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
106 * The current depth of nested transactions
107 * @param integer $level
109 function trxLevel( $level = NULL ) {
110 return wfSetVar( $this->mTrxLevel
, $level );
116 function lastQuery() { return $this->mLastQuery
; }
117 function isOpen() { return $this->mOpened
; }
120 #------------------------------------------------------------------------------
122 #------------------------------------------------------------------------------
125 * @param string $server database server host
126 * @param string $user database user name
127 * @param string $password database user password
128 * @param string $dbname database name
132 * @param failFunction
134 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
136 function Database( $server = false, $user = false, $password = false, $dbName = false,
137 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
139 global $wgOut, $wgDBprefix, $wgCommandLineMode;
140 # Can't get a reference if it hasn't been set yet
141 if ( !isset( $wgOut ) ) {
144 $this->mOut
=& $wgOut;
146 $this->mFailFunction
= $failFunction;
147 $this->mFlags
= $flags;
149 if ( $this->mFlags
& DBO_DEFAULT
) {
150 if ( $wgCommandLineMode ) {
151 $this->mFlags
&= ~DBO_TRX
;
153 $this->mFlags |
= DBO_TRX
;
157 /** Get the default table prefix*/
158 if ( $tablePrefix == 'get from global' ) {
159 $this->mTablePrefix
= $wgDBprefix;
161 $this->mTablePrefix
= $tablePrefix;
165 $this->open( $server, $user, $password, $dbName );
171 * @param failFunction
174 function newFromParams( $server, $user, $password, $dbName,
175 $failFunction = false, $flags = 0 )
177 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
181 * Usually aborts on failure
182 * If the failFunction is set to a non-zero integer, returns success
184 function open( $server, $user, $password, $dbName ) {
185 # Test for missing mysql.so
186 # Otherwise we get a suppressed fatal error, which is very hard to track down
187 if ( !function_exists( 'mysql_connect' ) ) {
188 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
192 $this->mServer
= $server;
193 $this->mUser
= $user;
194 $this->mPassword
= $password;
195 $this->mDBname
= $dbName;
199 @/**/$this->mConn
= mysql_connect( $server, $user, $password );
200 if ( $dbName != '' ) {
201 if ( $this->mConn
!== false ) {
202 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
204 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
207 wfDebug( "DB connection error\n" );
208 wfDebug( "Server: $server, User: $user, Password: " .
209 substr( $password, 0, 3 ) . "...\n" );
214 $success = !!$this->mConn
;
218 $this->reportConnectionError();
221 $this->mOpened
= $success;
227 * Closes a database connection.
228 * if it is open : commits any open transactions
230 * @return bool operation success. true if already closed.
234 $this->mOpened
= false;
235 if ( $this->mConn
) {
236 if ( $this->trxLevel() ) {
237 $this->immediateCommit();
239 return mysql_close( $this->mConn
);
247 * @param string $msg error message ?
248 * @todo parameter $msg is not used
250 function reportConnectionError( $msg = '') {
251 if ( $this->mFailFunction
) {
252 if ( !is_int( $this->mFailFunction
) ) {
253 $ff = $this->mFailFunction
;
254 $ff( $this, mysql_error() );
257 wfEmergencyAbort( $this, mysql_error() );
262 * Usually aborts on failure
263 * If errors are explicitly ignored, returns success
265 function query( $sql, $fname = '', $tempIgnore = false ) {
266 global $wgProfiling, $wgCommandLineMode;
268 if ( $wgProfiling ) {
269 # generalizeSQL will probably cut down the query to reasonable
270 # logging size most of the time. The substr is really just a sanity check.
271 $profName = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
272 wfProfileIn( $profName );
275 $this->mLastQuery
= $sql;
277 if ( $this->debug() ) {
278 $sqlx = substr( $sql, 0, 500 );
279 $sqlx = wordwrap(strtr($sqlx,"\t\n",' '));
280 wfDebug( "SQL: $sqlx\n" );
282 # Add a comment for easy SHOW PROCESSLIST interpretation
284 $commentedSql = "/* $fname */ $sql";
286 $commentedSql = $sql;
289 # If DBO_TRX is set, start a transaction
290 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() && $sql != 'BEGIN' ) {
294 # Do the query and handle errors
295 $ret = $this->doQuery( $commentedSql );
296 if ( false === $ret ) {
297 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
300 if ( $wgProfiling ) {
301 wfProfileOut( $profName );
307 * The DBMS-dependent part of query()
308 * @param string $sql SQL query.
310 function doQuery( $sql ) {
311 if( $this->bufferResults() ) {
312 $ret = mysql_query( $sql, $this->mConn
);
314 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
323 * @param string $fname
324 * @param bool $tempIgnore
326 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
327 global $wgCommandLineMode, $wgFullyInitialised;
328 # Ignore errors during error handling to avoid infinite recursion
329 $ignore = $this->ignoreErrors( true );
331 if( $ignore ||
$tempIgnore ) {
332 wfDebug("SQL ERROR (ignored): " . $error . "\n");
334 $sql1line = str_replace( "\n", "\\n", $sql );
335 wfLogDBError("$fname\t$errno\t$error\t$sql1line\n");
336 wfDebug("SQL ERROR: " . $error . "\n");
337 if ( $wgCommandLineMode ||
!$this->mOut ||
empty( $wgFullyInitialised ) ) {
338 $message = "A database error has occurred\n" .
340 "Function: $fname\n" .
341 "Error: $errno $error\n";
342 if ( !$wgCommandLineMode ) {
343 $message = nl2br( $message );
345 wfDebugDieBacktrace( $message );
347 // this calls wfAbruptExit()
348 $this->mOut
->databaseError( $fname, $sql, $error, $errno );
351 $this->ignoreErrors( $ignore );
356 * Intended to be compatible with the PEAR::DB wrapper functions.
357 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
359 * ? = scalar value, quoted as necessary
360 * ! = raw SQL bit (a function for instance)
361 * & = filename; reads the file and inserts as a blob
362 * (we don't use this though...)
364 function prepare( $sql, $func = 'Database::prepare' ) {
365 /* MySQL doesn't support prepared statements (yet), so just
366 pack up the query for reference. We'll manually replace
368 return array( 'query' => $sql, 'func' => $func );
371 function freePrepared( $prepared ) {
372 /* No-op for MySQL */
376 * Execute a prepared query with the various arguments
377 * @param string $prepared the prepared sql
378 * @param mixed $args Either an array here, or put scalars as varargs
380 function execute( $prepared, $args = null ) {
381 if( !is_array( $args ) ) {
383 $args = func_get_args();
384 array_shift( $args );
386 $sql = $this->fillPrepared( $prepared['query'], $args );
387 return $this->query( $sql, $prepared['func'] );
391 * Prepare & execute an SQL statement, quoting and inserting arguments
392 * in the appropriate places.
395 function safeQuery( $query, $args = null ) {
396 $prepared = $this->prepare( $query, 'Database::safeQuery' );
397 if( !is_array( $args ) ) {
399 $args = func_get_args();
400 array_shift( $args );
402 $retval = $this->execute( $prepared, $args );
403 $this->freePrepared( $prepared );
408 * For faking prepared SQL statements on DBs that don't support
410 * @param string $preparedSql - a 'preparable' SQL statement
411 * @param array $args - array of arguments to fill it with
412 * @return string executable SQL
414 function fillPrepared( $preparedQuery, $args ) {
417 $this->preparedArgs
=& $args;
418 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
419 array( &$this, 'fillPreparedArg' ), $preparedQuery );
423 * preg_callback func for fillPrepared()
424 * The arguments should be in $this->preparedArgs and must not be touched
425 * while we're doing this.
427 * @param array $matches
431 function fillPreparedArg( $matches ) {
432 switch( $matches[1] ) {
433 case '\\?': return '?';
434 case '\\!': return '!';
435 case '\\&': return '&';
437 list( $n, $arg ) = each( $this->preparedArgs
);
438 switch( $matches[1] ) {
439 case '?': return $this->addQuotes( $arg );
440 case '!': return $arg;
442 # return $this->addQuotes( file_get_contents( $arg ) );
443 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
445 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
450 * @param mixed $res A SQL result
455 function freeResult( $res ) {
456 if ( !@/**/mysql_free_result( $res ) ) {
457 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
462 * @todo FIXME: HACK HACK HACK HACK debug
464 function fetchObject( $res ) {
465 @/**/$row = mysql_fetch_object( $res );
466 # FIXME: HACK HACK HACK HACK debug
467 if( mysql_errno() ) {
468 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
476 function fetchRow( $res ) {
477 @/**/$row = mysql_fetch_array( $res );
478 if (mysql_errno() ) {
479 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
487 function numRows( $res ) {
488 @/**/$n = mysql_num_rows( $res );
489 if( mysql_errno() ) {
490 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
498 function numFields( $res ) { return mysql_num_fields( $res ); }
503 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
507 function insertId() { return mysql_insert_id( $this->mConn
); }
511 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
515 function lastErrno() { return mysql_errno(); }
519 function lastError() { return mysql_error(); }
523 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
524 /**#@-*/ // end of template : @param $result
527 * Simple UPDATE wrapper
528 * Usually aborts on failure
529 * If errors are explicitly ignored, returns success
531 * This function exists for historical reasons, Database::update() has a more standard
532 * calling convention and feature set
534 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
536 $table = $this->tableName( $table );
537 $sql = "UPDATE $table SET $var = '" .
538 $this->strencode( $value ) . "' WHERE ($cond)";
539 return !!$this->query( $sql, DB_MASTER
, $fname );
545 function getField( $table, $var, $cond='', $fname = 'Database::getField', $options = array() ) {
546 return $this->selectField( $table, $var, $cond, $fname = 'Database::get', $options = array() );
550 * Simple SELECT wrapper, returns a single field, input must be encoded
551 * Usually aborts on failure
552 * If errors are explicitly ignored, returns FALSE on failure
554 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
555 if ( !is_array( $options ) ) {
556 $options = array( $options );
558 $options['LIMIT'] = 1;
560 $res = $this->select( $table, $var, $cond, $fname, $options );
561 if ( $res === false ||
!$this->numRows( $res ) ) {
564 $row = $this->fetchRow( $res );
565 if ( $row !== false ) {
566 $this->freeResult( $res );
574 * Returns an optional USE INDEX clause to go after the table, and a
575 * string to go at the end of the query
577 function makeSelectOptions( $options ) {
578 if ( !is_array( $options ) ) {
579 $options = array( $options );
584 if ( isset( $options['ORDER BY'] ) ) {
585 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
587 if ( isset( $options['LIMIT'] ) ) {
588 $tailOpts .= " LIMIT {$options['LIMIT']}";
591 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
592 $tailOpts .= ' FOR UPDATE';
595 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
596 $tailOpts .= ' LOCK IN SHARE MODE';
599 if ( isset( $options['USE INDEX'] ) ) {
600 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
604 return array( $useIndex, $tailOpts );
610 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
612 if ( is_array( $vars ) ) {
613 $vars = implode( ',', $vars );
615 if( is_array( $table ) ) {
616 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
617 } elseif ($table!='') {
618 $from = ' FROM ' .$this->tableName( $table );
623 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
625 if ( $conds !== false && $conds != '' ) {
626 if ( is_array( $conds ) ) {
627 $conds = $this->makeList( $conds, LIST_AND
);
629 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
631 $sql = "SELECT $vars $from $useIndex $tailOpts";
633 return $this->query( $sql, $fname );
639 function getArray( $table, $vars, $conds, $fname = 'Database::getArray', $options = array() ) {
640 return $this->selectRow( $table, $vars, $conds, $fname, $options );
645 * Single row SELECT wrapper
646 * Aborts or returns FALSE on error
648 * $vars: the selected variables
649 * $conds: a condition map, terms are ANDed together.
650 * Items with numeric keys are taken to be literal conditions
651 * Takes an array of selected variables, and a condition map, which is ANDed
652 * e.g. selectRow( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
653 * would return an object where $obj->cur_id is the ID of the Astronomy article
655 * @todo migrate documentation to phpdocumentor format
657 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
658 $options['LIMIT'] = 1;
659 $res = $this->select( $table, $vars, $conds, $fname, $options );
660 if ( $res === false ||
!$this->numRows( $res ) ) {
663 $obj = $this->fetchObject( $res );
664 $this->freeResult( $res );
670 * Removes most variables from an SQL query and replaces them with X or N for numbers.
671 * It's only slightly flawed. Don't use for anything important.
673 * @param string $sql A SQL Query
676 function generalizeSQL( $sql ) {
677 # This does the same as the regexp below would do, but in such a way
678 # as to avoid crashing php on some large strings.
679 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
681 $sql = str_replace ( "\\\\", '', $sql);
682 $sql = str_replace ( "\\'", '', $sql);
683 $sql = str_replace ( "\\\"", '', $sql);
684 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
685 $sql = preg_replace ('/".*"/s', "'X'", $sql);
687 # All newlines, tabs, etc replaced by single space
688 $sql = preg_replace ( "/\s+/", ' ', $sql);
691 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
697 * Determines whether a field exists in a table
698 * Usually aborts on failure
699 * If errors are explicitly ignored, returns NULL on failure
701 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
702 $table = $this->tableName( $table );
703 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE
, $fname );
710 while ( $row = $this->fetchObject( $res ) ) {
711 if ( $row->Field
== $field ) {
720 * Determines whether an index exists
721 * Usually aborts on failure
722 * If errors are explicitly ignored, returns NULL on failure
724 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
725 $info = $this->indexInfo( $table, $index, $fname );
726 if ( is_null( $info ) ) {
729 return $info !== false;
737 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
738 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
739 # SHOW INDEX should work for 3.x and up:
740 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
741 $table = $this->tableName( $table );
742 $sql = 'SHOW INDEX FROM '.$table;
743 $res = $this->query( $sql, $fname );
748 while ( $row = $this->fetchObject( $res ) ) {
749 if ( $row->Key_name
== $index ) {
760 function tableExists( $table ) {
761 $table = $this->tableName( $table );
762 $old = $this->ignoreErrors( true );
763 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
764 $this->ignoreErrors( $old );
766 $this->freeResult( $res );
778 function fieldInfo( $table, $field ) {
779 $table = $this->tableName( $table );
780 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
781 $n = mysql_num_fields( $res );
782 for( $i = 0; $i < $n; $i++
) {
783 $meta = mysql_fetch_field( $res, $i );
784 if( $field == $meta->name
) {
794 function fieldType( $res, $index ) {
795 return mysql_field_type( $res, $index );
801 function indexUnique( $table, $index ) {
802 $indexInfo = $this->indexInfo( $table, $index );
806 return !$indexInfo->Non_unique
;
812 function insertArray( $table, $a, $fname = 'Database::insertArray', $options = array() ) {
813 return $this->insert( $table, $a, $fname, $options );
817 * INSERT wrapper, inserts an array into a table
819 * $a may be a single associative array, or an array of these with numeric keys, for
822 * Usually aborts on failure
823 * If errors are explicitly ignored, returns success
825 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
826 # No rows to insert, easy just return now
827 if ( !count( $a ) ) {
831 $table = $this->tableName( $table );
832 if ( !is_array( $options ) ) {
833 $options = array( $options );
835 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
837 $keys = array_keys( $a[0] );
840 $keys = array_keys( $a );
843 $sql = 'INSERT ' . implode( ' ', $options ) .
844 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
848 foreach ( $a as $row ) {
854 $sql .= '(' . $this->makeList( $row ) . ')';
857 $sql .= '(' . $this->makeList( $a ) . ')';
859 return !!$this->query( $sql, $fname );
865 function updateArray( $table, $values, $conds, $fname = 'Database::updateArray' ) {
866 return $this->update( $table, $values, $conds, $fname );
870 * UPDATE wrapper, takes a condition array and a SET array
872 function update( $table, $values, $conds, $fname = 'Database::update' ) {
873 $table = $this->tableName( $table );
874 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET
);
875 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
876 $this->query( $sql, $fname );
880 * Makes a wfStrencoded list from an array
881 * $mode: LIST_COMMA - comma separated, no field names
882 * LIST_AND - ANDed WHERE clause (without the WHERE)
883 * LIST_SET - comma separated with field names, like a SET clause
884 * LIST_NAMES - comma separated field names
886 function makeList( $a, $mode = LIST_COMMA
) {
887 if ( !is_array( $a ) ) {
888 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
893 foreach ( $a as $field => $value ) {
895 if ( $mode == LIST_AND
) {
903 if ( $mode == LIST_AND
&& is_numeric( $field ) ) {
905 } elseif ( $mode == LIST_AND
&& is_array ($value) ) {
906 $list .= $field." IN (".$this->makeList($value).") ";
908 if ( $mode == LIST_AND ||
$mode == LIST_SET
) {
911 $list .= ($mode==LIST_NAMES?
$value:$this->addQuotes( $value ));
920 function selectDB( $db ) {
921 $this->mDBname
= $db;
922 return mysql_select_db( $db, $this->mConn
);
928 function startTimer( $timeout ) {
930 if( function_exists( 'mysql_thread_id' ) ) {
931 # This will kill the query if it's still running after $timeout seconds.
932 $tid = mysql_thread_id( $this->mConn
);
933 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
938 * Does nothing at all
941 function stopTimer() { }
944 * @param string $name database table name
947 function tableName( $name ) {
949 if ( $this->mTablePrefix
!== '' ) {
950 if ( strpos( '.', $name ) === false ) {
951 $name = $this->mTablePrefix
. $name;
954 if ( isset( $wgSharedDB ) && 'user' == $name ) {
955 $name = $wgSharedDB . '.' . $name;
963 function tableNames() {
964 $inArray = func_get_args();
966 foreach ( $inArray as $name ) {
967 $retVal[$name] = $this->tableName( $name );
973 * Wrapper for addslashes()
974 * @param string $s String to be slashed.
975 * @return string slashed string.
977 function strencode( $s ) {
978 return addslashes( $s );
982 * If it's a string, adds quotes and backslashes
983 * Otherwise returns as-is
985 function addQuotes( $s ) {
986 if ( is_null( $s ) ) {
989 # This will also quote numeric values. This should be harmless,
990 # and protects against weird problems that occur when they really
991 # _are_ strings such as article titles and string->number->string
992 # conversion is not 1:1.
993 $s = "'" . $this->strencode( $s ) . "'";
999 * Returns an appropriately quoted sequence value for inserting a new row.
1000 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1001 * subclass will return an integer, and save the value for insertId()
1003 function nextSequenceValue( $seqName ) {
1009 * PostgreSQL doesn't have them and returns ""
1011 function useIndexClause( $index ) {
1012 return 'USE INDEX ('.$index.')';
1016 * REPLACE query wrapper
1017 * PostgreSQL simulates this with a DELETE followed by INSERT
1018 * $row is the row to insert, an associative array
1019 * $uniqueIndexes is an array of indexes. Each element may be either a
1020 * field name or an array of field names
1022 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1023 * However if you do this, you run the risk of encountering errors which wouldn't have
1026 * @todo migrate comment to phodocumentor format
1028 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1029 $table = $this->tableName( $table );
1032 if ( !is_array( reset( $rows ) ) ) {
1033 $rows = array( $rows );
1036 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1038 foreach ( $rows as $row ) {
1044 $sql .= '(' . $this->makeList( $row ) . ')';
1046 return $this->query( $sql, $fname );
1050 * DELETE where the condition is a join
1051 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1053 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1054 * join condition matches, set $conds='*'
1056 * DO NOT put the join condition in $conds
1058 * @param string $delTable The table to delete from.
1059 * @param string $joinTable The other table.
1060 * @param string $delVar The variable to join on, in the first table.
1061 * @param string $joinVar The variable to join on, in the second table.
1062 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1064 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1066 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1069 $delTable = $this->tableName( $delTable );
1070 $joinTable = $this->tableName( $joinTable );
1071 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1072 if ( $conds != '*' ) {
1073 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1076 return $this->query( $sql, $fname );
1080 * Returns the size of a text field, or -1 for "unlimited"
1082 function textFieldSize( $table, $field ) {
1083 $table = $this->tableName( $table );
1084 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1085 $res = $this->query( $sql, 'Database::textFieldSize' );
1086 $row = $this->fetchObject( $res );
1087 $this->freeResult( $res );
1089 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
1098 * @return string Always return 'LOW_PRIORITY'
1100 function lowPriorityOption() {
1101 return 'LOW_PRIORITY';
1105 * Use $conds == "*" to delete all rows
1108 function delete( $table, $conds, $fname = 'Database::delete' ) {
1110 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1112 $table = $this->tableName( $table );
1113 $sql = "DELETE FROM $table ";
1114 if ( $conds != '*' ) {
1115 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1117 return $this->query( $sql, $fname );
1121 * INSERT SELECT wrapper
1122 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1123 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1124 * $conds may be "*" to copy the whole table
1126 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1127 $destTable = $this->tableName( $destTable );
1128 $srcTable = $this->tableName( $srcTable );
1129 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1130 ' SELECT ' . implode( ',', $varMap ) .
1132 if ( $conds != '*' ) {
1133 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1135 return $this->query( $sql, $fname );
1141 function limitResult($limit,$offset) {
1142 return ' LIMIT '.(is_numeric($offset)?
"{$offset},":"")."{$limit} ";
1146 * Returns an SQL expression for a simple conditional.
1149 * @param string $cond SQL expression which will result in a boolean value
1150 * @param string $trueVal SQL expression to return if true
1151 * @param string $falseVal SQL expression to return if false
1152 * @return string SQL fragment
1154 function conditional( $cond, $trueVal, $falseVal ) {
1155 return " IF($cond, $trueVal, $falseVal) ";
1161 function wasDeadlock() {
1162 return $this->lastErrno() == 1213;
1168 function deadlockLoop() {
1169 $myFname = 'Database::deadlockLoop';
1171 $this->query( 'BEGIN', $myFname );
1172 $args = func_get_args();
1173 $function = array_shift( $args );
1174 $oldIgnore = $dbw->ignoreErrors( true );
1175 $tries = DEADLOCK_TRIES
;
1176 if ( is_array( $function ) ) {
1177 $fname = $function[0];
1182 $retVal = call_user_func_array( $function, $args );
1183 $error = $this->lastError();
1184 $errno = $this->lastErrno();
1185 $sql = $this->lastQuery();
1188 if ( $dbw->wasDeadlock() ) {
1190 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1192 $dbw->reportQueryError( $error, $errno, $sql, $fname );
1195 } while( $dbw->wasDeadlock
&& --$tries > 0 );
1196 $this->ignoreErrors( $oldIgnore );
1197 if ( $tries <= 0 ) {
1198 $this->query( 'ROLLBACK', $myFname );
1199 $this->reportQueryError( $error, $errno, $sql, $fname );
1202 $this->query( 'COMMIT', $myFname );
1208 * Do a SELECT MASTER_POS_WAIT()
1211 function masterPosWait( $file, $pos, $timeout ) {
1212 $encFile = $this->strencode( $file );
1213 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1214 $res = $this->query( $sql, 'Database::masterPosWait' );
1215 if ( $res && $row = $this->fetchRow( $res ) ) {
1216 $this->freeResult( $res );
1224 * Get the position of the master from SHOW SLAVE STATUS
1226 function getSlavePos() {
1227 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1228 $row = $this->fetchObject( $res );
1230 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1232 return array( false, false );
1237 * Get the position of the master from SHOW MASTER STATUS
1239 function getMasterPos() {
1240 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1241 $row = $this->fetchObject( $res );
1243 return array( $row->File
, $row->Position
);
1245 return array( false, false );
1250 * Begin a transaction, or if a transaction has already started, continue it
1252 function begin( $fname = 'Database::begin' ) {
1253 if ( !$this->mTrxLevel
) {
1254 $this->immediateBegin( $fname );
1261 * End a transaction, or decrement the nest level if transactions are nested
1263 function commit( $fname = 'Database::commit' ) {
1264 if ( $this->mTrxLevel
) {
1267 if ( !$this->mTrxLevel
) {
1268 $this->immediateCommit( $fname );
1273 * Rollback a transaction
1275 function rollback( $fname = 'Database::rollback' ) {
1276 $this->query( 'ROLLBACK', $fname );
1277 $this->mTrxLevel
= 0;
1281 * Begin a transaction, committing any previously open transaction
1283 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1284 $this->query( 'BEGIN', $fname );
1285 $this->mTrxLevel
= 1;
1289 * Commit transaction, if one is open
1291 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1292 $this->query( 'COMMIT', $fname );
1293 $this->mTrxLevel
= 0;
1297 * Return MW-style timestamp used for MySQL schema
1299 function timestamp( $ts=0 ) {
1300 return wfTimestamp(TS_MW
,$ts);
1306 function &resultObject( &$result ) {
1307 if( empty( $result ) ) {
1310 return new ResultWrapper( $this, $result );
1315 * Return aggregated value alias
1317 function aggregateValue ($valuedata,$valuename='value') {
1322 * @return string wikitext of a link to the server software's web site
1324 function getSoftwareLink() {
1325 return "[http://www.mysql.com/ MySQL]";
1329 * @return string Version information from the database
1331 function getServerVersion() {
1332 return mysql_get_server_info();
1337 * Database abstraction object for mySQL
1338 * Inherit all methods and properties of Database::Database()
1340 * @package MediaWiki
1344 class DatabaseMysql
extends Database
{
1350 * Result wrapper for grabbing data queried by someone else
1352 * @package MediaWiki
1355 class ResultWrapper
{
1361 function ResultWrapper( $database, $result ) {
1362 $this->db
=& $database;
1363 $this->result
=& $result;
1369 function numRows() {
1370 return $this->db
->numRows( $this->result
);
1376 function &fetchObject() {
1377 return $this->db
->fetchObject( $this->result
);
1383 function &fetchRow() {
1384 return $this->db
->fetchRow( $this->result
);
1391 $this->db
->freeResult( $this->result
);
1392 unset( $this->result
);
1397 #------------------------------------------------------------------------------
1399 #------------------------------------------------------------------------------
1402 * Standard fail function, called by default when a connection cannot be
1404 * Displays the file cache if possible
1406 function wfEmergencyAbort( &$conn, $error ) {
1407 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
1409 if( !headers_sent() ) {
1410 header( 'HTTP/1.0 500 Internal Server Error' );
1411 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1412 /* Don't cache error pages! They cause no end of trouble... */
1413 header( 'Cache-control: none' );
1414 header( 'Pragma: nocache' );
1416 $msg = $wgSiteNotice;
1417 if($msg == '') $msg = wfMsgNoDB( 'noconnect', $error );
1420 if($wgUseFileCache) {
1425 $t = Title
::newFromURL( $title );
1426 } elseif (@/**/$_REQUEST['search']) {
1427 $search = $_REQUEST['search'];
1428 echo wfMsgNoDB( 'searchdisabled' );
1429 echo wfMsgNoDB( 'googlesearch', htmlspecialchars( $search ), $wgInputEncoding );
1432 $t = Title
::newFromText( wfMsgNoDBForContent( 'mainpage' ) );
1436 $cache = new CacheManager( $t );
1437 if( $cache->isFileCached() ) {
1438 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1439 wfMsgNoDB( 'cachederror' ) . "</b></p>\n";
1441 $tag = '<div id="article">';
1442 $text = str_replace(
1445 $cache->fetchPageText() );