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 # Create a new connection...
218 @/**/$this->mConn
= mysql_connect( $server, $user, $password, true );
221 if ( $dbName != '' ) {
222 if ( $this->mConn
!== false ) {
223 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
225 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
228 wfDebug( "DB connection error\n" );
229 wfDebug( "Server: $server, User: $user, Password: " .
230 substr( $password, 0, 3 ) . "...\n" );
235 $success = !!$this->mConn
;
239 $this->reportConnectionError();
242 $this->mOpened
= $success;
248 * Closes a database connection.
249 * if it is open : commits any open transactions
251 * @return bool operation success. true if already closed.
255 $this->mOpened
= false;
256 if ( $this->mConn
) {
257 if ( $this->trxLevel() ) {
258 $this->immediateCommit();
260 return mysql_close( $this->mConn
);
268 * @param string $msg error message ?
269 * @todo parameter $msg is not used
271 function reportConnectionError( $msg = '') {
272 if ( $this->mFailFunction
) {
273 if ( !is_int( $this->mFailFunction
) ) {
274 $ff = $this->mFailFunction
;
275 $ff( $this, mysql_error() );
278 wfEmergencyAbort( $this, mysql_error() );
283 * Usually aborts on failure
284 * If errors are explicitly ignored, returns success
286 function query( $sql, $fname = '', $tempIgnore = false ) {
287 global $wgProfiling, $wgCommandLineMode;
289 if ( $wgProfiling ) {
290 # generalizeSQL will probably cut down the query to reasonable
291 # logging size most of the time. The substr is really just a sanity check.
292 $profName = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
293 wfProfileIn( 'Database::query' );
294 wfProfileIn( $profName );
297 $this->mLastQuery
= $sql;
299 # Add a comment for easy SHOW PROCESSLIST interpretation
301 $commentedSql = "/* $fname */ $sql";
303 $commentedSql = $sql;
306 # If DBO_TRX is set, start a transaction
307 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() && $sql != 'BEGIN' ) {
311 if ( $this->debug() ) {
312 $sqlx = substr( $commentedSql, 0, 500 );
313 $sqlx = strtr( $sqlx, "\t\n", ' ' );
314 wfDebug( "SQL: $sqlx\n" );
317 # Do the query and handle errors
318 $ret = $this->doQuery( $commentedSql );
320 # Try reconnecting if the connection was lost
321 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
322 # Transaction is gone, like it or not
323 $this->mTrxLevel
= 0;
324 wfDebug( "Connection lost, reconnecting...\n" );
325 if ( $this->ping() ) {
326 wfDebug( "Reconnected\n" );
327 $ret = $this->doQuery( $commentedSql );
329 wfDebug( "Failed\n" );
333 if ( false === $ret ) {
334 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
337 if ( $wgProfiling ) {
338 wfProfileOut( $profName );
339 wfProfileOut( 'Database::query' );
345 * The DBMS-dependent part of query()
346 * @param string $sql SQL query.
348 function doQuery( $sql ) {
349 if( $this->bufferResults() ) {
350 $ret = mysql_query( $sql, $this->mConn
);
352 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
361 * @param string $fname
362 * @param bool $tempIgnore
364 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
365 global $wgCommandLineMode, $wgFullyInitialised;
366 # Ignore errors during error handling to avoid infinite recursion
367 $ignore = $this->ignoreErrors( true );
368 $this->mErrorCount ++
;
370 if( $ignore ||
$tempIgnore ) {
371 wfDebug("SQL ERROR (ignored): " . $error . "\n");
373 $sql1line = str_replace( "\n", "\\n", $sql );
374 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
375 wfDebug("SQL ERROR: " . $error . "\n");
376 if ( $wgCommandLineMode ||
!$this->mOut ||
empty( $wgFullyInitialised ) ) {
377 $message = "A database error has occurred\n" .
379 "Function: $fname\n" .
380 "Error: $errno $error\n";
381 if ( !$wgCommandLineMode ) {
382 $message = nl2br( $message );
384 wfDebugDieBacktrace( $message );
386 // this calls wfAbruptExit()
387 $this->mOut
->databaseError( $fname, $sql, $error, $errno );
390 $this->ignoreErrors( $ignore );
395 * Intended to be compatible with the PEAR::DB wrapper functions.
396 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
398 * ? = scalar value, quoted as necessary
399 * ! = raw SQL bit (a function for instance)
400 * & = filename; reads the file and inserts as a blob
401 * (we don't use this though...)
403 function prepare( $sql, $func = 'Database::prepare' ) {
404 /* MySQL doesn't support prepared statements (yet), so just
405 pack up the query for reference. We'll manually replace
407 return array( 'query' => $sql, 'func' => $func );
410 function freePrepared( $prepared ) {
411 /* No-op for MySQL */
415 * Execute a prepared query with the various arguments
416 * @param string $prepared the prepared sql
417 * @param mixed $args Either an array here, or put scalars as varargs
419 function execute( $prepared, $args = null ) {
420 if( !is_array( $args ) ) {
422 $args = func_get_args();
423 array_shift( $args );
425 $sql = $this->fillPrepared( $prepared['query'], $args );
426 return $this->query( $sql, $prepared['func'] );
430 * Prepare & execute an SQL statement, quoting and inserting arguments
431 * in the appropriate places.
432 * @param string $query
433 * @param string $args ...
435 function safeQuery( $query, $args = null ) {
436 $prepared = $this->prepare( $query, 'Database::safeQuery' );
437 if( !is_array( $args ) ) {
439 $args = func_get_args();
440 array_shift( $args );
442 $retval = $this->execute( $prepared, $args );
443 $this->freePrepared( $prepared );
448 * For faking prepared SQL statements on DBs that don't support
450 * @param string $preparedSql - a 'preparable' SQL statement
451 * @param array $args - array of arguments to fill it with
452 * @return string executable SQL
454 function fillPrepared( $preparedQuery, $args ) {
457 $this->preparedArgs
=& $args;
458 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
459 array( &$this, 'fillPreparedArg' ), $preparedQuery );
463 * preg_callback func for fillPrepared()
464 * The arguments should be in $this->preparedArgs and must not be touched
465 * while we're doing this.
467 * @param array $matches
471 function fillPreparedArg( $matches ) {
472 switch( $matches[1] ) {
473 case '\\?': return '?';
474 case '\\!': return '!';
475 case '\\&': return '&';
477 list( $n, $arg ) = each( $this->preparedArgs
);
478 switch( $matches[1] ) {
479 case '?': return $this->addQuotes( $arg );
480 case '!': return $arg;
482 # return $this->addQuotes( file_get_contents( $arg ) );
483 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
485 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
490 * @param mixed $res A SQL result
493 * Free a result object
495 function freeResult( $res ) {
496 if ( !@/**/mysql_free_result( $res ) ) {
497 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
502 * Fetch the next row from the given result object, in object form
504 function fetchObject( $res ) {
505 @/**/$row = mysql_fetch_object( $res );
506 if( mysql_errno() ) {
507 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
513 * Fetch the next row from the given result object
516 function fetchRow( $res ) {
517 @/**/$row = mysql_fetch_array( $res );
518 if (mysql_errno() ) {
519 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
525 * Get the number of rows in a result object
527 function numRows( $res ) {
528 @/**/$n = mysql_num_rows( $res );
529 if( mysql_errno() ) {
530 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
536 * Get the number of fields in a result object
537 * See documentation for mysql_num_fields()
539 function numFields( $res ) { return mysql_num_fields( $res ); }
542 * Get a field name in a result object
543 * See documentation for mysql_field_name()
545 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
548 * Get the inserted value of an auto-increment row
550 * The value inserted should be fetched from nextSequenceValue()
553 * $id = $dbw->nextSequenceValue('page_page_id_seq');
554 * $dbw->insert('page',array('page_id' => $id));
555 * $id = $dbw->insertId();
557 function insertId() { return mysql_insert_id( $this->mConn
); }
560 * Change the position of the cursor in a result object
561 * See mysql_data_seek()
563 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
566 * Get the last error number
569 function lastErrno() {
570 if ( $this->mConn
) {
571 return mysql_errno( $this->mConn
);
573 return mysql_errno();
578 * Get a description of the last error
579 * See mysql_error() for more details
581 function lastError() {
582 if ( $this->mConn
) {
583 $error = mysql_error( $this->mConn
);
585 $error = mysql_error();
588 $error .= ' (' . $this->mServer
. ')';
593 * Get the number of rows affected by the last write query
594 * See mysql_affected_rows() for more details
596 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
597 /**#@-*/ // end of template : @param $result
600 * Simple UPDATE wrapper
601 * Usually aborts on failure
602 * If errors are explicitly ignored, returns success
604 * This function exists for historical reasons, Database::update() has a more standard
605 * calling convention and feature set
607 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
609 $table = $this->tableName( $table );
610 $sql = "UPDATE $table SET $var = '" .
611 $this->strencode( $value ) . "' WHERE ($cond)";
612 return !!$this->query( $sql, DB_MASTER
, $fname );
616 * Simple SELECT wrapper, returns a single field, input must be encoded
617 * Usually aborts on failure
618 * If errors are explicitly ignored, returns FALSE on failure
620 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
621 if ( !is_array( $options ) ) {
622 $options = array( $options );
624 $options['LIMIT'] = 1;
626 $res = $this->select( $table, $var, $cond, $fname, $options );
627 if ( $res === false ||
!$this->numRows( $res ) ) {
630 $row = $this->fetchRow( $res );
631 if ( $row !== false ) {
632 $this->freeResult( $res );
640 * Returns an optional USE INDEX clause to go after the table, and a
641 * string to go at the end of the query
645 * @param array $options an associative array of options to be turned into
646 * an SQL query, valid keys are listed in the function.
649 function makeSelectOptions( $options ) {
652 if ( isset( $options['ORDER BY'] ) ) {
653 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
655 if ( isset( $options['LIMIT'] ) ) {
656 $tailOpts .= " LIMIT {$options['LIMIT']}";
659 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
660 $tailOpts .= ' FOR UPDATE';
663 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
664 $tailOpts .= ' LOCK IN SHARE MODE';
667 if ( isset( $options['USE INDEX'] ) ) {
668 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
672 return array( $useIndex, $tailOpts );
678 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
680 if( is_array( $vars ) ) {
681 $vars = implode( ',', $vars );
683 if( is_array( $table ) ) {
684 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
685 } elseif ($table!='') {
686 $from = ' FROM ' .$this->tableName( $table );
691 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( (array)$options );
693 if( !empty( $conds ) ) {
694 if ( is_array( $conds ) ) {
695 $conds = $this->makeList( $conds, LIST_AND
);
697 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
699 $sql = "SELECT $vars $from $useIndex $tailOpts";
701 return $this->query( $sql, $fname );
705 * Single row SELECT wrapper
706 * Aborts or returns FALSE on error
708 * $vars: the selected variables
709 * $conds: a condition map, terms are ANDed together.
710 * Items with numeric keys are taken to be literal conditions
711 * Takes an array of selected variables, and a condition map, which is ANDed
712 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
713 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
714 * $obj- >page_id is the ID of the Astronomy article
716 * @todo migrate documentation to phpdocumentor format
718 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
719 $options['LIMIT'] = 1;
720 $res = $this->select( $table, $vars, $conds, $fname, $options );
721 if ( $res === false ||
!$this->numRows( $res ) ) {
724 $obj = $this->fetchObject( $res );
725 $this->freeResult( $res );
731 * Removes most variables from an SQL query and replaces them with X or N for numbers.
732 * It's only slightly flawed. Don't use for anything important.
734 * @param string $sql A SQL Query
737 function generalizeSQL( $sql ) {
738 # This does the same as the regexp below would do, but in such a way
739 # as to avoid crashing php on some large strings.
740 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
742 $sql = str_replace ( "\\\\", '', $sql);
743 $sql = str_replace ( "\\'", '', $sql);
744 $sql = str_replace ( "\\\"", '', $sql);
745 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
746 $sql = preg_replace ('/".*"/s', "'X'", $sql);
748 # All newlines, tabs, etc replaced by single space
749 $sql = preg_replace ( "/\s+/", ' ', $sql);
752 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
758 * Determines whether a field exists in a table
759 * Usually aborts on failure
760 * If errors are explicitly ignored, returns NULL on failure
762 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
763 $table = $this->tableName( $table );
764 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE
, $fname );
771 while ( $row = $this->fetchObject( $res ) ) {
772 if ( $row->Field
== $field ) {
781 * Determines whether an index exists
782 * Usually aborts on failure
783 * If errors are explicitly ignored, returns NULL on failure
785 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
786 $info = $this->indexInfo( $table, $index, $fname );
787 if ( is_null( $info ) ) {
790 return $info !== false;
796 * Get information about an index into an object
797 * Returns false if the index does not exist
799 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
800 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
801 # SHOW INDEX should work for 3.x and up:
802 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
803 $table = $this->tableName( $table );
804 $sql = 'SHOW INDEX FROM '.$table;
805 $res = $this->query( $sql, $fname );
810 while ( $row = $this->fetchObject( $res ) ) {
811 if ( $row->Key_name
== $index ) {
819 * Query whether a given table exists
821 function tableExists( $table ) {
822 $table = $this->tableName( $table );
823 $old = $this->ignoreErrors( true );
824 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
825 $this->ignoreErrors( $old );
827 $this->freeResult( $res );
835 * mysql_fetch_field() wrapper
836 * Returns false if the field doesn't exist
841 function fieldInfo( $table, $field ) {
842 $table = $this->tableName( $table );
843 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
844 $n = mysql_num_fields( $res );
845 for( $i = 0; $i < $n; $i++
) {
846 $meta = mysql_fetch_field( $res, $i );
847 if( $field == $meta->name
) {
855 * mysql_field_type() wrapper
857 function fieldType( $res, $index ) {
858 return mysql_field_type( $res, $index );
862 * Determines if a given index is unique
864 function indexUnique( $table, $index ) {
865 $indexInfo = $this->indexInfo( $table, $index );
869 return !$indexInfo->Non_unique
;
873 * INSERT wrapper, inserts an array into a table
875 * $a may be a single associative array, or an array of these with numeric keys, for
878 * Usually aborts on failure
879 * If errors are explicitly ignored, returns success
881 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
882 # No rows to insert, easy just return now
883 if ( !count( $a ) ) {
887 $table = $this->tableName( $table );
888 if ( !is_array( $options ) ) {
889 $options = array( $options );
891 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
893 $keys = array_keys( $a[0] );
896 $keys = array_keys( $a );
899 $sql = 'INSERT ' . implode( ' ', $options ) .
900 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
904 foreach ( $a as $row ) {
910 $sql .= '(' . $this->makeList( $row ) . ')';
913 $sql .= '(' . $this->makeList( $a ) . ')';
915 return !!$this->query( $sql, $fname );
919 * UPDATE wrapper, takes a condition array and a SET array
921 function update( $table, $values, $conds, $fname = 'Database::update' ) {
922 $table = $this->tableName( $table );
923 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET
);
924 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
925 $this->query( $sql, $fname );
929 * Makes a wfStrencoded list from an array
930 * $mode: LIST_COMMA - comma separated, no field names
931 * LIST_AND - ANDed WHERE clause (without the WHERE)
932 * LIST_SET - comma separated with field names, like a SET clause
933 * LIST_NAMES - comma separated field names
935 function makeList( $a, $mode = LIST_COMMA
) {
936 if ( !is_array( $a ) ) {
937 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
942 foreach ( $a as $field => $value ) {
944 if ( $mode == LIST_AND
) {
952 if ( $mode == LIST_AND
&& is_numeric( $field ) ) {
954 } elseif ( $mode == LIST_AND
&& is_array ($value) ) {
955 $list .= $field." IN (".$this->makeList($value).") ";
957 if ( $mode == LIST_AND ||
$mode == LIST_SET
) {
960 $list .= ($mode==LIST_NAMES?
$value:$this->addQuotes( $value ));
967 * Change the current database
969 function selectDB( $db ) {
970 $this->mDBname
= $db;
971 return mysql_select_db( $db, $this->mConn
);
975 * Starts a timer which will kill the DB thread after $timeout seconds
977 function startTimer( $timeout ) {
979 if( function_exists( 'mysql_thread_id' ) ) {
980 # This will kill the query if it's still running after $timeout seconds.
981 $tid = mysql_thread_id( $this->mConn
);
982 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
987 * Stop a timer started by startTimer()
988 * Currently unimplemented.
991 function stopTimer() { }
994 * Format a table name ready for use in constructing an SQL query
996 * This does two important things: it quotes table names which as necessary,
997 * and it adds a table prefix if there is one.
999 * All functions of this object which require a table name call this function
1000 * themselves. Pass the canonical name to such functions. This is only needed
1001 * when calling query() directly.
1003 * @param string $name database table name
1005 function tableName( $name ) {
1007 # Skip quoted literals
1008 if ( $name{0} != '`' ) {
1009 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
1010 $name = "{$this->mTablePrefix}$name";
1012 if ( isset( $wgSharedDB ) && 'user' == $name ) {
1013 $name = "`$wgSharedDB`.`$name`";
1023 * Fetch a number of table names into an array
1024 * This is handy when you need to construct SQL for joins
1027 * extract($dbr->tableNames('user','watchlist'));
1028 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1029 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1031 function tableNames() {
1032 $inArray = func_get_args();
1034 foreach ( $inArray as $name ) {
1035 $retVal[$name] = $this->tableName( $name );
1041 * Wrapper for addslashes()
1042 * @param string $s String to be slashed.
1043 * @return string slashed string.
1045 function strencode( $s ) {
1046 return addslashes( $s );
1050 * If it's a string, adds quotes and backslashes
1051 * Otherwise returns as-is
1053 function addQuotes( $s ) {
1054 if ( is_null( $s ) ) {
1057 # This will also quote numeric values. This should be harmless,
1058 # and protects against weird problems that occur when they really
1059 # _are_ strings such as article titles and string->number->string
1060 # conversion is not 1:1.
1061 return "'" . $this->strencode( $s ) . "'";
1066 * Returns an appropriately quoted sequence value for inserting a new row.
1067 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1068 * subclass will return an integer, and save the value for insertId()
1070 function nextSequenceValue( $seqName ) {
1076 * PostgreSQL doesn't have them and returns ""
1078 function useIndexClause( $index ) {
1079 return "USE INDEX ($index)";
1083 * REPLACE query wrapper
1084 * PostgreSQL simulates this with a DELETE followed by INSERT
1085 * $row is the row to insert, an associative array
1086 * $uniqueIndexes is an array of indexes. Each element may be either a
1087 * field name or an array of field names
1089 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1090 * However if you do this, you run the risk of encountering errors which wouldn't have
1093 * @todo migrate comment to phodocumentor format
1095 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1096 $table = $this->tableName( $table );
1099 if ( !is_array( reset( $rows ) ) ) {
1100 $rows = array( $rows );
1103 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1105 foreach ( $rows as $row ) {
1111 $sql .= '(' . $this->makeList( $row ) . ')';
1113 return $this->query( $sql, $fname );
1117 * DELETE where the condition is a join
1118 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1120 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1121 * join condition matches, set $conds='*'
1123 * DO NOT put the join condition in $conds
1125 * @param string $delTable The table to delete from.
1126 * @param string $joinTable The other table.
1127 * @param string $delVar The variable to join on, in the first table.
1128 * @param string $joinVar The variable to join on, in the second table.
1129 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1131 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1133 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1136 $delTable = $this->tableName( $delTable );
1137 $joinTable = $this->tableName( $joinTable );
1138 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1139 if ( $conds != '*' ) {
1140 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1143 return $this->query( $sql, $fname );
1147 * Returns the size of a text field, or -1 for "unlimited"
1149 function textFieldSize( $table, $field ) {
1150 $table = $this->tableName( $table );
1151 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1152 $res = $this->query( $sql, 'Database::textFieldSize' );
1153 $row = $this->fetchObject( $res );
1154 $this->freeResult( $res );
1156 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
1165 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1167 function lowPriorityOption() {
1168 return 'LOW_PRIORITY';
1172 * DELETE query wrapper
1174 * Use $conds == "*" to delete all rows
1176 function delete( $table, $conds, $fname = 'Database::delete' ) {
1178 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1180 $table = $this->tableName( $table );
1181 $sql = "DELETE FROM $table";
1182 if ( $conds != '*' ) {
1183 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1185 return $this->query( $sql, $fname );
1189 * INSERT SELECT wrapper
1190 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1191 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1192 * $conds may be "*" to copy the whole table
1193 * srcTable may be an array of tables.
1195 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1196 $destTable = $this->tableName( $destTable );
1197 if( is_array( $srcTable ) ) {
1198 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1200 $srcTable = $this->tableName( $srcTable );
1202 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1203 ' SELECT ' . implode( ',', $varMap ) .
1205 if ( $conds != '*' ) {
1206 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1208 return $this->query( $sql, $fname );
1212 * Construct a LIMIT query with optional offset
1213 * This is used for query pages
1215 function limitResult($limit,$offset) {
1216 return ' LIMIT '.(is_numeric($offset)?
"{$offset},":"")."{$limit} ";
1220 * Returns an SQL expression for a simple conditional.
1223 * @param string $cond SQL expression which will result in a boolean value
1224 * @param string $trueVal SQL expression to return if true
1225 * @param string $falseVal SQL expression to return if false
1226 * @return string SQL fragment
1228 function conditional( $cond, $trueVal, $falseVal ) {
1229 return " IF($cond, $trueVal, $falseVal) ";
1233 * Determines if the last failure was due to a deadlock
1235 function wasDeadlock() {
1236 return $this->lastErrno() == 1213;
1240 * Perform a deadlock-prone transaction.
1242 * This function invokes a callback function to perform a set of write
1243 * queries. If a deadlock occurs during the processing, the transaction
1244 * will be rolled back and the callback function will be called again.
1247 * $dbw->deadlockLoop( callback, ... );
1249 * Extra arguments are passed through to the specified callback function.
1251 * Returns whatever the callback function returned on its successful,
1252 * iteration, or false on error, for example if the retry limit was
1255 function deadlockLoop() {
1256 $myFname = 'Database::deadlockLoop';
1258 $this->query( 'BEGIN', $myFname );
1259 $args = func_get_args();
1260 $function = array_shift( $args );
1261 $oldIgnore = $this->ignoreErrors( true );
1262 $tries = DEADLOCK_TRIES
;
1263 if ( is_array( $function ) ) {
1264 $fname = $function[0];
1269 $retVal = call_user_func_array( $function, $args );
1270 $error = $this->lastError();
1271 $errno = $this->lastErrno();
1272 $sql = $this->lastQuery();
1275 if ( $this->wasDeadlock() ) {
1277 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1279 $this->reportQueryError( $error, $errno, $sql, $fname );
1282 } while( $this->wasDeadlock() && --$tries > 0 );
1283 $this->ignoreErrors( $oldIgnore );
1284 if ( $tries <= 0 ) {
1285 $this->query( 'ROLLBACK', $myFname );
1286 $this->reportQueryError( $error, $errno, $sql, $fname );
1289 $this->query( 'COMMIT', $myFname );
1295 * Do a SELECT MASTER_POS_WAIT()
1297 * @param string $file the binlog file
1298 * @param string $pos the binlog position
1299 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1301 function masterPosWait( $file, $pos, $timeout ) {
1302 $fname = 'Database::masterPosWait';
1303 wfProfileIn( $fname );
1306 # Commit any open transactions
1307 $this->immediateCommit();
1309 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1310 $encFile = $this->strencode( $file );
1311 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1312 $res = $this->doQuery( $sql );
1313 if ( $res && $row = $this->fetchRow( $res ) ) {
1314 $this->freeResult( $res );
1322 * Get the position of the master from SHOW SLAVE STATUS
1324 function getSlavePos() {
1325 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1326 $row = $this->fetchObject( $res );
1328 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1330 return array( false, false );
1335 * Get the position of the master from SHOW MASTER STATUS
1337 function getMasterPos() {
1338 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1339 $row = $this->fetchObject( $res );
1341 return array( $row->File
, $row->Position
);
1343 return array( false, false );
1348 * Begin a transaction, or if a transaction has already started, continue it
1350 function begin( $fname = 'Database::begin' ) {
1351 if ( !$this->mTrxLevel
) {
1352 $this->immediateBegin( $fname );
1359 * End a transaction, or decrement the nest level if transactions are nested
1361 function commit( $fname = 'Database::commit' ) {
1362 if ( $this->mTrxLevel
) {
1365 if ( !$this->mTrxLevel
) {
1366 $this->immediateCommit( $fname );
1371 * Rollback a transaction
1373 function rollback( $fname = 'Database::rollback' ) {
1374 $this->query( 'ROLLBACK', $fname );
1375 $this->mTrxLevel
= 0;
1379 * Begin a transaction, committing any previously open transaction
1381 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1382 $this->query( 'BEGIN', $fname );
1383 $this->mTrxLevel
= 1;
1387 * Commit transaction, if one is open
1389 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1390 $this->query( 'COMMIT', $fname );
1391 $this->mTrxLevel
= 0;
1395 * Return MW-style timestamp used for MySQL schema
1397 function timestamp( $ts=0 ) {
1398 return wfTimestamp(TS_MW
,$ts);
1402 * Local database timestamp format or null
1404 function timestampOrNull( $ts = null ) {
1405 if( is_null( $ts ) ) {
1408 return $this->timestamp( $ts );
1415 function &resultObject( &$result ) {
1416 if( empty( $result ) ) {
1419 return new ResultWrapper( $this, $result );
1424 * Return aggregated value alias
1426 function aggregateValue ($valuedata,$valuename='value') {
1431 * @return string wikitext of a link to the server software's web site
1433 function getSoftwareLink() {
1434 return "[http://www.mysql.com/ MySQL]";
1438 * @return string Version information from the database
1440 function getServerVersion() {
1441 return mysql_get_server_info();
1445 * Ping the server and try to reconnect if it there is no connection
1448 return mysql_ping( $this->mConn
);
1453 * At the moment, this will only work if the DB user has the PROCESS privilege
1456 $res = $this->query( 'SHOW PROCESSLIST' );
1457 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1458 # dubious, but unfortunately there's no easy rigorous way
1460 while ( $row = $this->fetchObject( $res ) ) {
1461 if ( $row->User
== 'system user' ) {
1462 if ( ++
$slaveThreads == 2 ) {
1463 # This is it, return the time
1472 * Get status information from SHOW STATUS in an associative array
1474 function getStatus() {
1475 $res = $this->query( 'SHOW STATUS' );
1477 while ( $row = $this->fetchObject( $res ) ) {
1478 $status[$row->Variable_name
] = $row->Value
;
1485 * Database abstraction object for mySQL
1486 * Inherit all methods and properties of Database::Database()
1488 * @package MediaWiki
1491 class DatabaseMysql
extends Database
{
1497 * Result wrapper for grabbing data queried by someone else
1499 * @package MediaWiki
1501 class ResultWrapper
{
1507 function ResultWrapper( $database, $result ) {
1508 $this->db
=& $database;
1509 $this->result
=& $result;
1515 function numRows() {
1516 return $this->db
->numRows( $this->result
);
1522 function &fetchObject() {
1523 return $this->db
->fetchObject( $this->result
);
1529 function &fetchRow() {
1530 return $this->db
->fetchRow( $this->result
);
1537 $this->db
->freeResult( $this->result
);
1538 unset( $this->result
);
1542 function seek( $row ) {
1543 $this->db
->dataSeek( $this->result
, $row );
1547 #------------------------------------------------------------------------------
1549 #------------------------------------------------------------------------------
1552 * Standard fail function, called by default when a connection cannot be
1554 * Displays the file cache if possible
1556 function wfEmergencyAbort( &$conn, $error ) {
1557 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1558 global $wgSitename, $wgServer;
1560 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1561 # Hard coding strings instead.
1563 $noconnect = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server. <br />
1565 $mainpage = 'Main Page';
1566 $searchdisabled = <<<EOT
1567 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1568 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1572 <!-- SiteSearch Google -->
1573 <FORM method=GET action=\"http://www.google.com/search\">
1574 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1575 <A HREF=\"http://www.google.com/\">
1576 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1577 border=\"0\" ALT=\"Google\"></A>
1580 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1581 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1583 <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 />
1584 <input type='hidden' name='ie' value='$2'>
1585 <input type='hidden' name='oe' value='$2'>
1589 <!-- SiteSearch Google -->";
1590 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1593 if( !headers_sent() ) {
1594 header( 'HTTP/1.0 500 Internal Server Error' );
1595 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1596 /* Don't cache error pages! They cause no end of trouble... */
1597 header( 'Cache-control: none' );
1598 header( 'Pragma: nocache' );
1600 $msg = wfGetSiteNotice();
1602 $msg = str_replace( '$1', $error, $noconnect );
1606 if($wgUseFileCache) {
1611 $t = Title
::newFromURL( $title );
1612 } elseif (@/**/$_REQUEST['search']) {
1613 $search = $_REQUEST['search'];
1614 echo $searchdisabled;
1615 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1616 $wgInputEncoding ), $googlesearch );
1619 $t = Title
::newFromText( $mainpage );
1623 $cache = new CacheManager( $t );
1624 if( $cache->isFileCached() ) {
1625 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1626 $cachederror . "</b></p>\n";
1628 $tag = '<div id="article">';
1629 $text = str_replace(
1632 $cache->fetchPageText() );