3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
9 * Depends on the CacheManager
11 require_once( 'CacheManager.php' );
13 /** See Database::makeList() */
14 define( 'LIST_COMMA', 0 );
15 define( 'LIST_AND', 1 );
16 define( 'LIST_SET', 2 );
17 define( 'LIST_NAMES', 3);
19 /** Number of times to re-try an operation in case of deadlock */
20 define( 'DEADLOCK_TRIES', 4 );
21 /** Minimum time to wait before retry, in microseconds */
22 define( 'DEADLOCK_DELAY_MIN', 500000 );
23 /** Maximum time to wait before retry */
24 define( 'DEADLOCK_DELAY_MAX', 1500000 );
27 * Database abstraction object
32 #------------------------------------------------------------------------------
34 #------------------------------------------------------------------------------
40 var $mServer, $mUser, $mPassword, $mConn, $mDBname;
41 var $mOut, $mOpened = false;
50 #------------------------------------------------------------------------------
52 #------------------------------------------------------------------------------
53 # These optionally set a variable and return the previous state
56 * Fail function, takes a Database as a parameter
57 * Set to false for default, 1 for ignore errors
59 function failFunction( $function = NULL ) {
60 return wfSetVar( $this->mFailFunction
, $function );
64 * Output page, used for reporting errors
65 * FALSE means discard output
67 function &setOutputPage( &$out ) {
72 * Boolean, controls output of large amounts of debug information
74 function debug( $debug = NULL ) {
75 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
79 * Turns buffering of SQL result sets on (true) or off (false).
80 * Default is "on" and it should not be changed without good reasons.
82 function bufferResults( $buffer = NULL ) {
83 if ( is_null( $buffer ) ) {
84 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
86 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
91 * Turns on (false) or off (true) the automatic generation and sending
92 * of a "we're sorry, but there has been a database error" page on
93 * database errors. Default is on (false). When turned off, the
94 * code should use wfLastErrno() and wfLastError() to handle the
95 * situation as appropriate.
97 function ignoreErrors( $ignoreErrors = NULL ) {
98 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
102 * The current depth of nested transactions
103 * @param integer $level
105 function trxLevel( $level = NULL ) {
106 return wfSetVar( $this->mTrxLevel
, $level );
110 * Number of errors logged, only useful when errors are ignored
112 function errorCount( $count = NULL ) {
113 return wfSetVar( $this->mErrorCount
, $count );
119 function lastQuery() { return $this->mLastQuery
; }
120 function isOpen() { return $this->mOpened
; }
123 #------------------------------------------------------------------------------
125 #------------------------------------------------------------------------------
128 * @param string $server database server host
129 * @param string $user database user name
130 * @param string $password database user password
131 * @param string $dbname database name
135 * @param failFunction
137 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
139 function Database( $server = false, $user = false, $password = false, $dbName = false,
140 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
142 global $wgOut, $wgDBprefix, $wgCommandLineMode;
143 # Can't get a reference if it hasn't been set yet
144 if ( !isset( $wgOut ) ) {
147 $this->mOut
=& $wgOut;
149 $this->mFailFunction
= $failFunction;
150 $this->mFlags
= $flags;
152 if ( $this->mFlags
& DBO_DEFAULT
) {
153 if ( $wgCommandLineMode ) {
154 $this->mFlags
&= ~DBO_TRX
;
156 $this->mFlags |
= DBO_TRX
;
161 // Faster read-only access
162 if ( wfReadOnly() ) {
163 $this->mFlags |= DBO_PERSISTENT;
164 $this->mFlags &= ~DBO_TRX;
167 /** Get the default table prefix*/
168 if ( $tablePrefix == 'get from global' ) {
169 $this->mTablePrefix
= $wgDBprefix;
171 $this->mTablePrefix
= $tablePrefix;
175 $this->open( $server, $user, $password, $dbName );
181 * @param failFunction
184 function newFromParams( $server, $user, $password, $dbName,
185 $failFunction = false, $flags = 0 )
187 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
191 * Usually aborts on failure
192 * If the failFunction is set to a non-zero integer, returns success
194 function open( $server, $user, $password, $dbName ) {
195 # Test for missing mysql.so
196 # First try to load it
197 if (!@extension_loaded
('mysql')) {
201 # Otherwise we get a suppressed fatal error, which is very hard to track down
202 if ( !function_exists( 'mysql_connect' ) ) {
203 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
207 $this->mServer
= $server;
208 $this->mUser
= $user;
209 $this->mPassword
= $password;
210 $this->mDBname
= $dbName;
214 if ( $this->mFlags
& DBO_PERSISTENT
) {
215 @/**/$this->mConn
= mysql_pconnect( $server, $user, $password );
217 @/**/$this->mConn
= mysql_connect( $server, $user, $password );
220 if ( $dbName != '' ) {
221 if ( $this->mConn
!== false ) {
222 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
224 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
227 wfDebug( "DB connection error\n" );
228 wfDebug( "Server: $server, User: $user, Password: " .
229 substr( $password, 0, 3 ) . "...\n" );
234 $success = !!$this->mConn
;
238 $this->reportConnectionError();
241 $this->mOpened
= $success;
247 * Closes a database connection.
248 * if it is open : commits any open transactions
250 * @return bool operation success. true if already closed.
254 $this->mOpened
= false;
255 if ( $this->mConn
) {
256 if ( $this->trxLevel() ) {
257 $this->immediateCommit();
259 return mysql_close( $this->mConn
);
267 * @param string $msg error message ?
268 * @todo parameter $msg is not used
270 function reportConnectionError( $msg = '') {
271 if ( $this->mFailFunction
) {
272 if ( !is_int( $this->mFailFunction
) ) {
273 $ff = $this->mFailFunction
;
274 $ff( $this, mysql_error() );
277 wfEmergencyAbort( $this, mysql_error() );
282 * Usually aborts on failure
283 * If errors are explicitly ignored, returns success
285 function query( $sql, $fname = '', $tempIgnore = false ) {
286 global $wgProfiling, $wgCommandLineMode;
288 if ( $wgProfiling ) {
289 # generalizeSQL will probably cut down the query to reasonable
290 # logging size most of the time. The substr is really just a sanity check.
291 $profName = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
292 wfProfileIn( $profName );
295 $this->mLastQuery
= $sql;
297 # Add a comment for easy SHOW PROCESSLIST interpretation
299 $commentedSql = "/* $fname */ $sql";
301 $commentedSql = $sql;
304 # If DBO_TRX is set, start a transaction
305 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() && $sql != 'BEGIN' ) {
309 if ( $this->debug() ) {
310 $sqlx = substr( $sql, 0, 500 );
311 $sqlx = strtr($sqlx,"\t\n",' ');
312 wfDebug( "SQL: $sqlx\n" );
315 # Do the query and handle errors
316 $ret = $this->doQuery( $commentedSql );
318 # Try reconnecting if the connection was lost
319 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
320 # Transaction is gone, like it or not
321 $this->mTrxLevel
= 0;
322 wfDebug( "Connection lost, reconnecting...\n" );
323 if ( $this->ping() ) {
324 wfDebug( "Reconnected\n" );
325 $ret = $this->doQuery( $commentedSql );
327 wfDebug( "Failed\n" );
331 if ( false === $ret ) {
332 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
335 if ( $wgProfiling ) {
336 wfProfileOut( $profName );
342 * The DBMS-dependent part of query()
343 * @param string $sql SQL query.
345 function doQuery( $sql ) {
346 if( $this->bufferResults() ) {
347 $ret = mysql_query( $sql, $this->mConn
);
349 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
358 * @param string $fname
359 * @param bool $tempIgnore
361 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
362 global $wgCommandLineMode, $wgFullyInitialised;
363 # Ignore errors during error handling to avoid infinite recursion
364 $ignore = $this->ignoreErrors( true );
365 $this->mErrorCount ++
;
367 if( $ignore ||
$tempIgnore ) {
368 wfDebug("SQL ERROR (ignored): " . $error . "\n");
370 $sql1line = str_replace( "\n", "\\n", $sql );
371 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
372 wfDebug("SQL ERROR: " . $error . "\n");
373 if ( $wgCommandLineMode ||
!$this->mOut ||
empty( $wgFullyInitialised ) ) {
374 $message = "A database error has occurred\n" .
376 "Function: $fname\n" .
377 "Error: $errno $error\n";
378 if ( !$wgCommandLineMode ) {
379 $message = nl2br( $message );
381 wfDebugDieBacktrace( $message );
383 // this calls wfAbruptExit()
384 $this->mOut
->databaseError( $fname, $sql, $error, $errno );
387 $this->ignoreErrors( $ignore );
392 * Intended to be compatible with the PEAR::DB wrapper functions.
393 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
395 * ? = scalar value, quoted as necessary
396 * ! = raw SQL bit (a function for instance)
397 * & = filename; reads the file and inserts as a blob
398 * (we don't use this though...)
400 function prepare( $sql, $func = 'Database::prepare' ) {
401 /* MySQL doesn't support prepared statements (yet), so just
402 pack up the query for reference. We'll manually replace
404 return array( 'query' => $sql, 'func' => $func );
407 function freePrepared( $prepared ) {
408 /* No-op for MySQL */
412 * Execute a prepared query with the various arguments
413 * @param string $prepared the prepared sql
414 * @param mixed $args Either an array here, or put scalars as varargs
416 function execute( $prepared, $args = null ) {
417 if( !is_array( $args ) ) {
419 $args = func_get_args();
420 array_shift( $args );
422 $sql = $this->fillPrepared( $prepared['query'], $args );
423 return $this->query( $sql, $prepared['func'] );
427 * Prepare & execute an SQL statement, quoting and inserting arguments
428 * in the appropriate places.
429 * @param string $query
430 * @param string $args (default null)
432 function safeQuery( $query, $args = null ) {
433 $prepared = $this->prepare( $query, 'Database::safeQuery' );
434 if( !is_array( $args ) ) {
436 $args = func_get_args();
437 array_shift( $args );
439 $retval = $this->execute( $prepared, $args );
440 $this->freePrepared( $prepared );
445 * For faking prepared SQL statements on DBs that don't support
447 * @param string $preparedSql - a 'preparable' SQL statement
448 * @param array $args - array of arguments to fill it with
449 * @return string executable SQL
451 function fillPrepared( $preparedQuery, $args ) {
454 $this->preparedArgs
=& $args;
455 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
456 array( &$this, 'fillPreparedArg' ), $preparedQuery );
460 * preg_callback func for fillPrepared()
461 * The arguments should be in $this->preparedArgs and must not be touched
462 * while we're doing this.
464 * @param array $matches
468 function fillPreparedArg( $matches ) {
469 switch( $matches[1] ) {
470 case '\\?': return '?';
471 case '\\!': return '!';
472 case '\\&': return '&';
474 list( $n, $arg ) = each( $this->preparedArgs
);
475 switch( $matches[1] ) {
476 case '?': return $this->addQuotes( $arg );
477 case '!': return $arg;
479 # return $this->addQuotes( file_get_contents( $arg ) );
480 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
482 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
487 * @param mixed $res A SQL result
490 * Free a result object
492 function freeResult( $res ) {
493 if ( !@/**/mysql_free_result( $res ) ) {
494 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
499 * Fetch the next row from the given result object, in object form
501 function fetchObject( $res ) {
502 @/**/$row = mysql_fetch_object( $res );
503 if( mysql_errno() ) {
504 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
510 * Fetch the next row from the given result object
513 function fetchRow( $res ) {
514 @/**/$row = mysql_fetch_array( $res );
515 if (mysql_errno() ) {
516 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
522 * Get the number of rows in a result object
524 function numRows( $res ) {
525 @/**/$n = mysql_num_rows( $res );
526 if( mysql_errno() ) {
527 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
533 * Get the number of fields in a result object
534 * See documentation for mysql_num_fields()
536 function numFields( $res ) { return mysql_num_fields( $res ); }
539 * Get a field name in a result object
540 * See documentation for mysql_field_name()
542 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
545 * Get the inserted value of an auto-increment row
547 * The value inserted should be fetched from nextSequenceValue()
550 * $id = $dbw->nextSequenceValue('page_page_id_seq');
551 * $dbw->insert('page',array('page_id' => $id));
552 * $id = $dbw->insertId();
554 function insertId() { return mysql_insert_id( $this->mConn
); }
557 * Change the position of the cursor in a result object
558 * See mysql_data_seek()
560 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
563 * Get the last error number
566 function lastErrno() {
567 if ( $this->mConn
) {
568 return mysql_errno( $this->mConn
);
570 return mysql_errno();
575 * Get a description of the last error
576 * See mysql_error() for more details
578 function lastError() {
579 if ( $this->mConn
) {
580 $error = mysql_error( $this->mConn
);
582 $error = mysql_error();
585 $error .= ' (' . $this->mServer
. ')';
590 * Get the number of rows affected by the last write query
591 * See mysql_affected_rows() for more details
593 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
594 /**#@-*/ // end of template : @param $result
597 * Simple UPDATE wrapper
598 * Usually aborts on failure
599 * If errors are explicitly ignored, returns success
601 * This function exists for historical reasons, Database::update() has a more standard
602 * calling convention and feature set
604 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
606 $table = $this->tableName( $table );
607 $sql = "UPDATE $table SET $var = '" .
608 $this->strencode( $value ) . "' WHERE ($cond)";
609 return !!$this->query( $sql, DB_MASTER
, $fname );
613 * Simple SELECT wrapper, returns a single field, input must be encoded
614 * Usually aborts on failure
615 * If errors are explicitly ignored, returns FALSE on failure
617 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
618 if ( !is_array( $options ) ) {
619 $options = array( $options );
621 $options['LIMIT'] = 1;
623 $res = $this->select( $table, $var, $cond, $fname, $options );
624 if ( $res === false ||
!$this->numRows( $res ) ) {
627 $row = $this->fetchRow( $res );
628 if ( $row !== false ) {
629 $this->freeResult( $res );
637 * Returns an optional USE INDEX clause to go after the table, and a
638 * string to go at the end of the query
640 function makeSelectOptions( $options ) {
641 if ( !is_array( $options ) ) {
642 $options = array( $options );
647 if ( isset( $options['ORDER BY'] ) ) {
648 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
650 if ( isset( $options['LIMIT'] ) ) {
651 $tailOpts .= " LIMIT {$options['LIMIT']}";
654 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
655 $tailOpts .= ' FOR UPDATE';
658 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
659 $tailOpts .= ' LOCK IN SHARE MODE';
662 if ( isset( $options['USE INDEX'] ) ) {
663 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
667 return array( $useIndex, $tailOpts );
673 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
675 if( is_array( $vars ) ) {
676 $vars = implode( ',', $vars );
678 if( is_array( $table ) ) {
679 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
680 } elseif ($table!='') {
681 $from = ' FROM ' .$this->tableName( $table );
686 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
688 if( !empty( $conds ) ) {
689 if ( is_array( $conds ) ) {
690 $conds = $this->makeList( $conds, LIST_AND
);
692 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
694 $sql = "SELECT $vars $from $useIndex $tailOpts";
696 return $this->query( $sql, $fname );
700 * Single row SELECT wrapper
701 * Aborts or returns FALSE on error
703 * $vars: the selected variables
704 * $conds: a condition map, terms are ANDed together.
705 * Items with numeric keys are taken to be literal conditions
706 * Takes an array of selected variables, and a condition map, which is ANDed
707 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
708 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
709 * $obj- >page_id is the ID of the Astronomy article
711 * @todo migrate documentation to phpdocumentor format
713 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
714 $options['LIMIT'] = 1;
715 $res = $this->select( $table, $vars, $conds, $fname, $options );
716 if ( $res === false ||
!$this->numRows( $res ) ) {
719 $obj = $this->fetchObject( $res );
720 $this->freeResult( $res );
726 * Removes most variables from an SQL query and replaces them with X or N for numbers.
727 * It's only slightly flawed. Don't use for anything important.
729 * @param string $sql A SQL Query
732 function generalizeSQL( $sql ) {
733 # This does the same as the regexp below would do, but in such a way
734 # as to avoid crashing php on some large strings.
735 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
737 $sql = str_replace ( "\\\\", '', $sql);
738 $sql = str_replace ( "\\'", '', $sql);
739 $sql = str_replace ( "\\\"", '', $sql);
740 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
741 $sql = preg_replace ('/".*"/s', "'X'", $sql);
743 # All newlines, tabs, etc replaced by single space
744 $sql = preg_replace ( "/\s+/", ' ', $sql);
747 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
753 * Determines whether a field exists in a table
754 * Usually aborts on failure
755 * If errors are explicitly ignored, returns NULL on failure
757 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
758 $table = $this->tableName( $table );
759 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE
, $fname );
766 while ( $row = $this->fetchObject( $res ) ) {
767 if ( $row->Field
== $field ) {
776 * Determines whether an index exists
777 * Usually aborts on failure
778 * If errors are explicitly ignored, returns NULL on failure
780 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
781 $info = $this->indexInfo( $table, $index, $fname );
782 if ( is_null( $info ) ) {
785 return $info !== false;
791 * Get information about an index into an object
792 * Returns false if the index does not exist
794 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
795 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
796 # SHOW INDEX should work for 3.x and up:
797 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
798 $table = $this->tableName( $table );
799 $sql = 'SHOW INDEX FROM '.$table;
800 $res = $this->query( $sql, $fname );
805 while ( $row = $this->fetchObject( $res ) ) {
806 if ( $row->Key_name
== $index ) {
814 * Query whether a given table exists
816 function tableExists( $table ) {
817 $table = $this->tableName( $table );
818 $old = $this->ignoreErrors( true );
819 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
820 $this->ignoreErrors( $old );
822 $this->freeResult( $res );
830 * mysql_fetch_field() wrapper
831 * Returns false if the field doesn't exist
836 function fieldInfo( $table, $field ) {
837 $table = $this->tableName( $table );
838 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
839 $n = mysql_num_fields( $res );
840 for( $i = 0; $i < $n; $i++
) {
841 $meta = mysql_fetch_field( $res, $i );
842 if( $field == $meta->name
) {
850 * mysql_field_type() wrapper
852 function fieldType( $res, $index ) {
853 return mysql_field_type( $res, $index );
857 * Determines if a given index is unique
859 function indexUnique( $table, $index ) {
860 $indexInfo = $this->indexInfo( $table, $index );
864 return !$indexInfo->Non_unique
;
868 * INSERT wrapper, inserts an array into a table
870 * $a may be a single associative array, or an array of these with numeric keys, for
873 * Usually aborts on failure
874 * If errors are explicitly ignored, returns success
876 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
877 # No rows to insert, easy just return now
878 if ( !count( $a ) ) {
882 $table = $this->tableName( $table );
883 if ( !is_array( $options ) ) {
884 $options = array( $options );
886 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
888 $keys = array_keys( $a[0] );
891 $keys = array_keys( $a );
894 $sql = 'INSERT ' . implode( ' ', $options ) .
895 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
899 foreach ( $a as $row ) {
905 $sql .= '(' . $this->makeList( $row ) . ')';
908 $sql .= '(' . $this->makeList( $a ) . ')';
910 return !!$this->query( $sql, $fname );
914 * UPDATE wrapper, takes a condition array and a SET array
916 function update( $table, $values, $conds, $fname = 'Database::update' ) {
917 $table = $this->tableName( $table );
918 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET
);
919 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
920 $this->query( $sql, $fname );
924 * Makes a wfStrencoded list from an array
925 * $mode: LIST_COMMA - comma separated, no field names
926 * LIST_AND - ANDed WHERE clause (without the WHERE)
927 * LIST_SET - comma separated with field names, like a SET clause
928 * LIST_NAMES - comma separated field names
930 function makeList( $a, $mode = LIST_COMMA
) {
931 if ( !is_array( $a ) ) {
932 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
937 foreach ( $a as $field => $value ) {
939 if ( $mode == LIST_AND
) {
947 if ( $mode == LIST_AND
&& is_numeric( $field ) ) {
949 } elseif ( $mode == LIST_AND
&& is_array ($value) ) {
950 $list .= $field." IN (".$this->makeList($value).") ";
952 if ( $mode == LIST_AND ||
$mode == LIST_SET
) {
955 $list .= ($mode==LIST_NAMES?
$value:$this->addQuotes( $value ));
962 * Change the current database
964 function selectDB( $db ) {
965 $this->mDBname
= $db;
966 return mysql_select_db( $db, $this->mConn
);
970 * Starts a timer which will kill the DB thread after $timeout seconds
972 function startTimer( $timeout ) {
974 if( function_exists( 'mysql_thread_id' ) ) {
975 # This will kill the query if it's still running after $timeout seconds.
976 $tid = mysql_thread_id( $this->mConn
);
977 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
982 * Stop a timer started by startTimer()
983 * Currently unimplemented.
986 function stopTimer() { }
989 * Format a table name ready for use in constructing an SQL query
991 * This does two important things: it quotes table names which as necessary,
992 * and it adds a table prefix if there is one.
994 * All functions of this object which require a table name call this function
995 * themselves. Pass the canonical name to such functions. This is only needed
996 * when calling query() directly.
998 * @param string $name database table name
1000 function tableName( $name ) {
1002 # Skip quoted literals
1003 if ( $name{0} != '`' ) {
1004 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
1005 $name = "{$this->mTablePrefix}$name";
1007 if ( isset( $wgSharedDB ) && 'user' == $name ) {
1008 $name = "`$wgSharedDB`.`$name`";
1018 * Fetch a number of table names into an array
1019 * This is handy when you need to construct SQL for joins
1022 * extract($dbr->tableNames('user','watchlist'));
1023 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1024 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1026 function tableNames() {
1027 $inArray = func_get_args();
1029 foreach ( $inArray as $name ) {
1030 $retVal[$name] = $this->tableName( $name );
1036 * Wrapper for addslashes()
1037 * @param string $s String to be slashed.
1038 * @return string slashed string.
1040 function strencode( $s ) {
1041 return addslashes( $s );
1045 * If it's a string, adds quotes and backslashes
1046 * Otherwise returns as-is
1048 function addQuotes( $s ) {
1049 if ( is_null( $s ) ) {
1052 # This will also quote numeric values. This should be harmless,
1053 # and protects against weird problems that occur when they really
1054 # _are_ strings such as article titles and string->number->string
1055 # conversion is not 1:1.
1056 $s = "'" . $this->strencode( $s ) . "'";
1062 * Returns an appropriately quoted sequence value for inserting a new row.
1063 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1064 * subclass will return an integer, and save the value for insertId()
1066 function nextSequenceValue( $seqName ) {
1072 * PostgreSQL doesn't have them and returns ""
1074 function useIndexClause( $index ) {
1075 return 'USE INDEX ('.$index.')';
1079 * REPLACE query wrapper
1080 * PostgreSQL simulates this with a DELETE followed by INSERT
1081 * $row is the row to insert, an associative array
1082 * $uniqueIndexes is an array of indexes. Each element may be either a
1083 * field name or an array of field names
1085 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1086 * However if you do this, you run the risk of encountering errors which wouldn't have
1089 * @todo migrate comment to phodocumentor format
1091 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1092 $table = $this->tableName( $table );
1095 if ( !is_array( reset( $rows ) ) ) {
1096 $rows = array( $rows );
1099 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1101 foreach ( $rows as $row ) {
1107 $sql .= '(' . $this->makeList( $row ) . ')';
1109 return $this->query( $sql, $fname );
1113 * DELETE where the condition is a join
1114 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1116 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1117 * join condition matches, set $conds='*'
1119 * DO NOT put the join condition in $conds
1121 * @param string $delTable The table to delete from.
1122 * @param string $joinTable The other table.
1123 * @param string $delVar The variable to join on, in the first table.
1124 * @param string $joinVar The variable to join on, in the second table.
1125 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1127 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1129 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1132 $delTable = $this->tableName( $delTable );
1133 $joinTable = $this->tableName( $joinTable );
1134 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1135 if ( $conds != '*' ) {
1136 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1139 return $this->query( $sql, $fname );
1143 * Returns the size of a text field, or -1 for "unlimited"
1145 function textFieldSize( $table, $field ) {
1146 $table = $this->tableName( $table );
1147 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1148 $res = $this->query( $sql, 'Database::textFieldSize' );
1149 $row = $this->fetchObject( $res );
1150 $this->freeResult( $res );
1152 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
1161 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1163 function lowPriorityOption() {
1164 return 'LOW_PRIORITY';
1168 * DELETE query wrapper
1170 * Use $conds == "*" to delete all rows
1172 function delete( $table, $conds, $fname = 'Database::delete' ) {
1174 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1176 $table = $this->tableName( $table );
1177 $sql = "DELETE FROM $table ";
1178 if ( $conds != '*' ) {
1179 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1181 return $this->query( $sql, $fname );
1185 * INSERT SELECT wrapper
1186 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1187 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1188 * $conds may be "*" to copy the whole table
1189 * srcTable may be an array of tables.
1191 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1192 $destTable = $this->tableName( $destTable );
1193 if( is_array( $srcTable ) ) {
1194 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1196 $srcTable = $this->tableName( $srcTable );
1198 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1199 ' SELECT ' . implode( ',', $varMap ) .
1201 if ( $conds != '*' ) {
1202 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1204 return $this->query( $sql, $fname );
1208 * Construct a LIMIT query with optional offset
1209 * This is used for query pages
1211 function limitResult($limit,$offset) {
1212 return ' LIMIT '.(is_numeric($offset)?
"{$offset},":"")."{$limit} ";
1216 * Returns an SQL expression for a simple conditional.
1219 * @param string $cond SQL expression which will result in a boolean value
1220 * @param string $trueVal SQL expression to return if true
1221 * @param string $falseVal SQL expression to return if false
1222 * @return string SQL fragment
1224 function conditional( $cond, $trueVal, $falseVal ) {
1225 return " IF($cond, $trueVal, $falseVal) ";
1229 * Determines if the last failure was due to a deadlock
1231 function wasDeadlock() {
1232 return $this->lastErrno() == 1213;
1236 * Perform a deadlock-prone transaction.
1238 * This function invokes a callback function to perform a set of write
1239 * queries. If a deadlock occurs during the processing, the transaction
1240 * will be rolled back and the callback function will be called again.
1243 * $dbw->deadlockLoop( callback, ... );
1245 * Extra arguments are passed through to the specified callback function.
1247 * Returns whatever the callback function returned on its successful,
1248 * iteration, or false on error, for example if the retry limit was
1251 function deadlockLoop() {
1252 $myFname = 'Database::deadlockLoop';
1254 $this->query( 'BEGIN', $myFname );
1255 $args = func_get_args();
1256 $function = array_shift( $args );
1257 $oldIgnore = $this->ignoreErrors( true );
1258 $tries = DEADLOCK_TRIES
;
1259 if ( is_array( $function ) ) {
1260 $fname = $function[0];
1265 $retVal = call_user_func_array( $function, $args );
1266 $error = $this->lastError();
1267 $errno = $this->lastErrno();
1268 $sql = $this->lastQuery();
1271 if ( $this->wasDeadlock() ) {
1273 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1275 $this->reportQueryError( $error, $errno, $sql, $fname );
1278 } while( $this->wasDeadlock() && --$tries > 0 );
1279 $this->ignoreErrors( $oldIgnore );
1280 if ( $tries <= 0 ) {
1281 $this->query( 'ROLLBACK', $myFname );
1282 $this->reportQueryError( $error, $errno, $sql, $fname );
1285 $this->query( 'COMMIT', $myFname );
1291 * Do a SELECT MASTER_POS_WAIT()
1293 * @param string $file the binlog file
1294 * @param string $pos the binlog position
1295 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1297 function masterPosWait( $file, $pos, $timeout ) {
1298 $fname = 'Database::masterPosWait';
1299 wfProfileIn( $fname );
1302 # Commit any open transactions
1303 $this->immediateCommit();
1305 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1306 $encFile = $this->strencode( $file );
1307 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1308 $res = $this->doQuery( $sql );
1309 if ( $res && $row = $this->fetchRow( $res ) ) {
1310 $this->freeResult( $res );
1318 * Get the position of the master from SHOW SLAVE STATUS
1320 function getSlavePos() {
1321 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1322 $row = $this->fetchObject( $res );
1324 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1326 return array( false, false );
1331 * Get the position of the master from SHOW MASTER STATUS
1333 function getMasterPos() {
1334 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1335 $row = $this->fetchObject( $res );
1337 return array( $row->File
, $row->Position
);
1339 return array( false, false );
1344 * Begin a transaction, or if a transaction has already started, continue it
1346 function begin( $fname = 'Database::begin' ) {
1347 if ( !$this->mTrxLevel
) {
1348 $this->immediateBegin( $fname );
1355 * End a transaction, or decrement the nest level if transactions are nested
1357 function commit( $fname = 'Database::commit' ) {
1358 if ( $this->mTrxLevel
) {
1361 if ( !$this->mTrxLevel
) {
1362 $this->immediateCommit( $fname );
1367 * Rollback a transaction
1369 function rollback( $fname = 'Database::rollback' ) {
1370 $this->query( 'ROLLBACK', $fname );
1371 $this->mTrxLevel
= 0;
1375 * Begin a transaction, committing any previously open transaction
1377 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1378 $this->query( 'BEGIN', $fname );
1379 $this->mTrxLevel
= 1;
1383 * Commit transaction, if one is open
1385 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1386 $this->query( 'COMMIT', $fname );
1387 $this->mTrxLevel
= 0;
1391 * Return MW-style timestamp used for MySQL schema
1393 function timestamp( $ts=0 ) {
1394 return wfTimestamp(TS_MW
,$ts);
1400 function &resultObject( &$result ) {
1401 if( empty( $result ) ) {
1404 return new ResultWrapper( $this, $result );
1409 * Return aggregated value alias
1411 function aggregateValue ($valuedata,$valuename='value') {
1416 * @return string wikitext of a link to the server software's web site
1418 function getSoftwareLink() {
1419 return "[http://www.mysql.com/ MySQL]";
1423 * @return string Version information from the database
1425 function getServerVersion() {
1426 return mysql_get_server_info();
1430 * Ping the server and try to reconnect if it there is no connection
1433 return mysql_ping( $this->mConn
);
1438 * Database abstraction object for mySQL
1439 * Inherit all methods and properties of Database::Database()
1441 * @package MediaWiki
1444 class DatabaseMysql
extends Database
{
1450 * Result wrapper for grabbing data queried by someone else
1452 * @package MediaWiki
1454 class ResultWrapper
{
1460 function ResultWrapper( $database, $result ) {
1461 $this->db
=& $database;
1462 $this->result
=& $result;
1468 function numRows() {
1469 return $this->db
->numRows( $this->result
);
1475 function &fetchObject() {
1476 return $this->db
->fetchObject( $this->result
);
1482 function &fetchRow() {
1483 return $this->db
->fetchRow( $this->result
);
1490 $this->db
->freeResult( $this->result
);
1491 unset( $this->result
);
1495 function seek( $row ) {
1496 $this->db
->dataSeek( $this->result
, $row );
1500 #------------------------------------------------------------------------------
1502 #------------------------------------------------------------------------------
1505 * Standard fail function, called by default when a connection cannot be
1507 * Displays the file cache if possible
1509 function wfEmergencyAbort( &$conn, $error ) {
1510 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1511 global $wgSitename, $wgServer;
1513 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1514 # Hard coding strings instead.
1516 $noconnect = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server. <br />
1518 $mainpage = 'Main Page';
1519 $searchdisabled = <<<EOT
1520 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1521 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1525 <!-- SiteSearch Google -->
1526 <FORM method=GET action=\"http://www.google.com/search\">
1527 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1528 <A HREF=\"http://www.google.com/\">
1529 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1530 border=\"0\" ALT=\"Google\"></A>
1533 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1534 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1536 <input type=hidden name=domains value=\"$wgServer\"><br /><input type=radio name=sitesearch value=\"\"> WWW <input type=radio name=sitesearch value=\"$wgServer\" checked> $wgServer <br />
1537 <input type='hidden' name='ie' value='$2'>
1538 <input type='hidden' name='oe' value='$2'>
1542 <!-- SiteSearch Google -->";
1543 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1546 if( !headers_sent() ) {
1547 header( 'HTTP/1.0 500 Internal Server Error' );
1548 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1549 /* Don't cache error pages! They cause no end of trouble... */
1550 header( 'Cache-control: none' );
1551 header( 'Pragma: nocache' );
1553 $msg = wfGetSiteNotice();
1555 $msg = str_replace( '$1', $error, $noconnect );
1559 if($wgUseFileCache) {
1564 $t = Title
::newFromURL( $title );
1565 } elseif (@/**/$_REQUEST['search']) {
1566 $search = $_REQUEST['search'];
1567 echo $searchdisabled;
1568 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1569 $wgInputEncoding ), $googlesearch );
1572 $t = Title
::newFromText( $mainpage );
1576 $cache = new CacheManager( $t );
1577 if( $cache->isFileCached() ) {
1578 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1579 $cachederror . "</b></p>\n";
1581 $tag = '<div id="article">';
1582 $text = str_replace(
1585 $cache->fetchPageText() );