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 ) . "..., error: " . mysql_error() . "\n" );
235 $success = (bool)$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 ( wfReadOnly() ) {
290 # This is a quick check for the most common kinds of write query used
291 # in MediaWiki, to provide extra safety in addition to UI-level checks.
292 # It is not intended to prevent every conceivable write query, or even
293 # to handle such queries gracefully.
294 if ( preg_match( '/^(update|insert|replace|delete)/i', $sql ) ) {
295 wfDebug( "Write query from $fname blocked\n" );
300 if ( $wgProfiling ) {
301 # generalizeSQL will probably cut down the query to reasonable
302 # logging size most of the time. The substr is really just a sanity check.
303 $profName = 'query: ' . $fname . ' ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
304 wfProfileIn( 'Database::query' );
305 wfProfileIn( $profName );
308 $this->mLastQuery
= $sql;
310 # Add a comment for easy SHOW PROCESSLIST interpretation
312 $commentedSql = "/* $fname */ $sql";
314 $commentedSql = $sql;
317 # If DBO_TRX is set, start a transaction
318 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() && $sql != 'BEGIN' ) {
322 if ( $this->debug() ) {
323 $sqlx = substr( $commentedSql, 0, 500 );
324 $sqlx = strtr( $sqlx, "\t\n", ' ' );
325 wfDebug( "SQL: $sqlx\n" );
328 # Do the query and handle errors
329 $ret = $this->doQuery( $commentedSql );
331 # Try reconnecting if the connection was lost
332 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
333 # Transaction is gone, like it or not
334 $this->mTrxLevel
= 0;
335 wfDebug( "Connection lost, reconnecting...\n" );
336 if ( $this->ping() ) {
337 wfDebug( "Reconnected\n" );
338 $ret = $this->doQuery( $commentedSql );
340 wfDebug( "Failed\n" );
344 if ( false === $ret ) {
345 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
348 if ( $wgProfiling ) {
349 wfProfileOut( $profName );
350 wfProfileOut( 'Database::query' );
356 * The DBMS-dependent part of query()
357 * @param string $sql SQL query.
359 function doQuery( $sql ) {
360 if( $this->bufferResults() ) {
361 $ret = mysql_query( $sql, $this->mConn
);
363 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
372 * @param string $fname
373 * @param bool $tempIgnore
375 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
376 global $wgCommandLineMode, $wgFullyInitialised;
377 # Ignore errors during error handling to avoid infinite recursion
378 $ignore = $this->ignoreErrors( true );
379 $this->mErrorCount ++
;
381 if( $ignore ||
$tempIgnore ) {
382 wfDebug("SQL ERROR (ignored): " . $error . "\n");
384 $sql1line = str_replace( "\n", "\\n", $sql );
385 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
386 wfDebug("SQL ERROR: " . $error . "\n");
387 if ( $wgCommandLineMode ||
!$this->mOut ||
empty( $wgFullyInitialised ) ) {
388 $message = "A database error has occurred\n" .
390 "Function: $fname\n" .
391 "Error: $errno $error\n";
392 if ( !$wgCommandLineMode ) {
393 $message = nl2br( $message );
395 wfDebugDieBacktrace( $message );
397 // this calls wfAbruptExit()
398 $this->mOut
->databaseError( $fname, $sql, $error, $errno );
401 $this->ignoreErrors( $ignore );
406 * Intended to be compatible with the PEAR::DB wrapper functions.
407 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
409 * ? = scalar value, quoted as necessary
410 * ! = raw SQL bit (a function for instance)
411 * & = filename; reads the file and inserts as a blob
412 * (we don't use this though...)
414 function prepare( $sql, $func = 'Database::prepare' ) {
415 /* MySQL doesn't support prepared statements (yet), so just
416 pack up the query for reference. We'll manually replace
418 return array( 'query' => $sql, 'func' => $func );
421 function freePrepared( $prepared ) {
422 /* No-op for MySQL */
426 * Execute a prepared query with the various arguments
427 * @param string $prepared the prepared sql
428 * @param mixed $args Either an array here, or put scalars as varargs
430 function execute( $prepared, $args = null ) {
431 if( !is_array( $args ) ) {
433 $args = func_get_args();
434 array_shift( $args );
436 $sql = $this->fillPrepared( $prepared['query'], $args );
437 return $this->query( $sql, $prepared['func'] );
441 * Prepare & execute an SQL statement, quoting and inserting arguments
442 * in the appropriate places.
443 * @param string $query
444 * @param string $args ...
446 function safeQuery( $query, $args = null ) {
447 $prepared = $this->prepare( $query, 'Database::safeQuery' );
448 if( !is_array( $args ) ) {
450 $args = func_get_args();
451 array_shift( $args );
453 $retval = $this->execute( $prepared, $args );
454 $this->freePrepared( $prepared );
459 * For faking prepared SQL statements on DBs that don't support
461 * @param string $preparedSql - a 'preparable' SQL statement
462 * @param array $args - array of arguments to fill it with
463 * @return string executable SQL
465 function fillPrepared( $preparedQuery, $args ) {
468 $this->preparedArgs
=& $args;
469 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
470 array( &$this, 'fillPreparedArg' ), $preparedQuery );
474 * preg_callback func for fillPrepared()
475 * The arguments should be in $this->preparedArgs and must not be touched
476 * while we're doing this.
478 * @param array $matches
482 function fillPreparedArg( $matches ) {
483 switch( $matches[1] ) {
484 case '\\?': return '?';
485 case '\\!': return '!';
486 case '\\&': return '&';
488 list( $n, $arg ) = each( $this->preparedArgs
);
489 switch( $matches[1] ) {
490 case '?': return $this->addQuotes( $arg );
491 case '!': return $arg;
493 # return $this->addQuotes( file_get_contents( $arg ) );
494 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
496 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
501 * @param mixed $res A SQL result
504 * Free a result object
506 function freeResult( $res ) {
507 if ( !@/**/mysql_free_result( $res ) ) {
508 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
513 * Fetch the next row from the given result object, in object form
515 function fetchObject( $res ) {
516 @/**/$row = mysql_fetch_object( $res );
517 if( mysql_errno() ) {
518 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
524 * Fetch the next row from the given result object
527 function fetchRow( $res ) {
528 @/**/$row = mysql_fetch_array( $res );
529 if (mysql_errno() ) {
530 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
536 * Get the number of rows in a result object
538 function numRows( $res ) {
539 @/**/$n = mysql_num_rows( $res );
540 if( mysql_errno() ) {
541 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
547 * Get the number of fields in a result object
548 * See documentation for mysql_num_fields()
550 function numFields( $res ) { return mysql_num_fields( $res ); }
553 * Get a field name in a result object
554 * See documentation for mysql_field_name()
556 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
559 * Get the inserted value of an auto-increment row
561 * The value inserted should be fetched from nextSequenceValue()
564 * $id = $dbw->nextSequenceValue('page_page_id_seq');
565 * $dbw->insert('page',array('page_id' => $id));
566 * $id = $dbw->insertId();
568 function insertId() { return mysql_insert_id( $this->mConn
); }
571 * Change the position of the cursor in a result object
572 * See mysql_data_seek()
574 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
577 * Get the last error number
580 function lastErrno() {
581 if ( $this->mConn
) {
582 return mysql_errno( $this->mConn
);
584 return mysql_errno();
589 * Get a description of the last error
590 * See mysql_error() for more details
592 function lastError() {
593 if ( $this->mConn
) {
594 $error = mysql_error( $this->mConn
);
596 $error = mysql_error();
599 $error .= ' (' . $this->mServer
. ')';
604 * Get the number of rows affected by the last write query
605 * See mysql_affected_rows() for more details
607 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
608 /**#@-*/ // end of template : @param $result
611 * Simple UPDATE wrapper
612 * Usually aborts on failure
613 * If errors are explicitly ignored, returns success
615 * This function exists for historical reasons, Database::update() has a more standard
616 * calling convention and feature set
618 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
620 $table = $this->tableName( $table );
621 $sql = "UPDATE $table SET $var = '" .
622 $this->strencode( $value ) . "' WHERE ($cond)";
623 return (bool)$this->query( $sql, DB_MASTER
, $fname );
627 * Simple SELECT wrapper, returns a single field, input must be encoded
628 * Usually aborts on failure
629 * If errors are explicitly ignored, returns FALSE on failure
631 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
632 if ( !is_array( $options ) ) {
633 $options = array( $options );
635 $options['LIMIT'] = 1;
637 $res = $this->select( $table, $var, $cond, $fname, $options );
638 if ( $res === false ||
!$this->numRows( $res ) ) {
641 $row = $this->fetchRow( $res );
642 if ( $row !== false ) {
643 $this->freeResult( $res );
651 * Returns an optional USE INDEX clause to go after the table, and a
652 * string to go at the end of the query
656 * @param array $options an associative array of options to be turned into
657 * an SQL query, valid keys are listed in the function.
660 function makeSelectOptions( $options ) {
663 if ( isset( $options['GROUP BY'] ) ) {
664 $tailOpts .= " GROUP BY {$options['GROUP BY']}";
666 if ( isset( $options['ORDER BY'] ) ) {
667 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
669 if ( isset( $options['LIMIT'] ) ) {
670 $tailOpts .= " LIMIT {$options['LIMIT']}";
673 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
674 $tailOpts .= ' FOR UPDATE';
677 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
678 $tailOpts .= ' LOCK IN SHARE MODE';
681 if ( isset( $options['USE INDEX'] ) ) {
682 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
686 return array( $useIndex, $tailOpts );
692 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
694 if( is_array( $vars ) ) {
695 $vars = implode( ',', $vars );
697 if( is_array( $table ) ) {
698 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
699 } elseif ($table!='') {
700 $from = ' FROM ' .$this->tableName( $table );
705 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( (array)$options );
707 if( !empty( $conds ) ) {
708 if ( is_array( $conds ) ) {
709 $conds = $this->makeList( $conds, LIST_AND
);
711 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
713 $sql = "SELECT $vars $from $useIndex $tailOpts";
715 return $this->query( $sql, $fname );
719 * Single row SELECT wrapper
720 * Aborts or returns FALSE on error
722 * $vars: the selected variables
723 * $conds: a condition map, terms are ANDed together.
724 * Items with numeric keys are taken to be literal conditions
725 * Takes an array of selected variables, and a condition map, which is ANDed
726 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
727 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
728 * $obj- >page_id is the ID of the Astronomy article
730 * @todo migrate documentation to phpdocumentor format
732 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
733 $options['LIMIT'] = 1;
734 $res = $this->select( $table, $vars, $conds, $fname, $options );
735 if ( $res === false ||
!$this->numRows( $res ) ) {
738 $obj = $this->fetchObject( $res );
739 $this->freeResult( $res );
745 * Removes most variables from an SQL query and replaces them with X or N for numbers.
746 * It's only slightly flawed. Don't use for anything important.
748 * @param string $sql A SQL Query
751 function generalizeSQL( $sql ) {
752 # This does the same as the regexp below would do, but in such a way
753 # as to avoid crashing php on some large strings.
754 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
756 $sql = str_replace ( "\\\\", '', $sql);
757 $sql = str_replace ( "\\'", '', $sql);
758 $sql = str_replace ( "\\\"", '', $sql);
759 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
760 $sql = preg_replace ('/".*"/s', "'X'", $sql);
762 # All newlines, tabs, etc replaced by single space
763 $sql = preg_replace ( "/\s+/", ' ', $sql);
766 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
772 * Determines whether a field exists in a table
773 * Usually aborts on failure
774 * If errors are explicitly ignored, returns NULL on failure
776 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
777 $table = $this->tableName( $table );
778 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE
, $fname );
785 while ( $row = $this->fetchObject( $res ) ) {
786 if ( $row->Field
== $field ) {
795 * Determines whether an index exists
796 * Usually aborts on failure
797 * If errors are explicitly ignored, returns NULL on failure
799 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
800 $info = $this->indexInfo( $table, $index, $fname );
801 if ( is_null( $info ) ) {
804 return $info !== false;
810 * Get information about an index into an object
811 * Returns false if the index does not exist
813 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
814 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
815 # SHOW INDEX should work for 3.x and up:
816 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
817 $table = $this->tableName( $table );
818 $sql = 'SHOW INDEX FROM '.$table;
819 $res = $this->query( $sql, $fname );
824 while ( $row = $this->fetchObject( $res ) ) {
825 if ( $row->Key_name
== $index ) {
833 * Query whether a given table exists
835 function tableExists( $table ) {
836 $table = $this->tableName( $table );
837 $old = $this->ignoreErrors( true );
838 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
839 $this->ignoreErrors( $old );
841 $this->freeResult( $res );
849 * mysql_fetch_field() wrapper
850 * Returns false if the field doesn't exist
855 function fieldInfo( $table, $field ) {
856 $table = $this->tableName( $table );
857 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
858 $n = mysql_num_fields( $res );
859 for( $i = 0; $i < $n; $i++
) {
860 $meta = mysql_fetch_field( $res, $i );
861 if( $field == $meta->name
) {
869 * mysql_field_type() wrapper
871 function fieldType( $res, $index ) {
872 return mysql_field_type( $res, $index );
876 * Determines if a given index is unique
878 function indexUnique( $table, $index ) {
879 $indexInfo = $this->indexInfo( $table, $index );
883 return !$indexInfo->Non_unique
;
887 * INSERT wrapper, inserts an array into a table
889 * $a may be a single associative array, or an array of these with numeric keys, for
892 * Usually aborts on failure
893 * If errors are explicitly ignored, returns success
895 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
896 # No rows to insert, easy just return now
897 if ( !count( $a ) ) {
901 $table = $this->tableName( $table );
902 if ( !is_array( $options ) ) {
903 $options = array( $options );
905 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
907 $keys = array_keys( $a[0] );
910 $keys = array_keys( $a );
913 $sql = 'INSERT ' . implode( ' ', $options ) .
914 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
918 foreach ( $a as $row ) {
924 $sql .= '(' . $this->makeList( $row ) . ')';
927 $sql .= '(' . $this->makeList( $a ) . ')';
929 return (bool)$this->query( $sql, $fname );
933 * Make UPDATE options for the Database::update function
936 * @param array $options The options passed to Database::update
939 function makeUpdateOptions( $options ) {
940 if( !is_array( $options ) ) {
941 wfDebugDieBacktrace( 'makeUpdateOptions given non-array' );
944 if ( in_array( 'LOW_PRIORITY', $options ) )
945 $opts[] = $this->lowPriorityOption();
946 if ( in_array( 'IGNORE', $options ) )
948 return implode(' ', $opts);
952 * UPDATE wrapper, takes a condition array and a SET array
954 * @param string $table The table to UPDATE
955 * @param array $values An array of values to SET
956 * @param array $conds An array of conditions (WHERE)
957 * @param string $fname The Class::Function calling this function
959 * @param array $options An array of UPDATE options, can be one or
960 * more of IGNORE, LOW_PRIORITY
962 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
963 $table = $this->tableName( $table );
964 $opts = $this->makeUpdateOptions( $options );
965 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
966 if ( $conds != '*' ) {
967 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
969 $this->query( $sql, $fname );
973 * Makes a wfStrencoded list from an array
974 * $mode: LIST_COMMA - comma separated, no field names
975 * LIST_AND - ANDed WHERE clause (without the WHERE)
976 * LIST_SET - comma separated with field names, like a SET clause
977 * LIST_NAMES - comma separated field names
979 function makeList( $a, $mode = LIST_COMMA
) {
980 if ( !is_array( $a ) ) {
981 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
986 foreach ( $a as $field => $value ) {
988 if ( $mode == LIST_AND
) {
996 if ( $mode == LIST_AND
&& is_numeric( $field ) ) {
998 } elseif ( $mode == LIST_AND
&& is_array ($value) ) {
999 $list .= $field." IN (".$this->makeList($value).") ";
1001 if ( $mode == LIST_AND ||
$mode == LIST_SET
) {
1002 $list .= "$field = ";
1004 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1011 * Change the current database
1013 function selectDB( $db ) {
1014 $this->mDBname
= $db;
1015 return mysql_select_db( $db, $this->mConn
);
1019 * Starts a timer which will kill the DB thread after $timeout seconds
1021 function startTimer( $timeout ) {
1023 if( function_exists( 'mysql_thread_id' ) ) {
1024 # This will kill the query if it's still running after $timeout seconds.
1025 $tid = mysql_thread_id( $this->mConn
);
1026 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
1031 * Stop a timer started by startTimer()
1032 * Currently unimplemented.
1035 function stopTimer() { }
1038 * Format a table name ready for use in constructing an SQL query
1040 * This does two important things: it quotes table names which as necessary,
1041 * and it adds a table prefix if there is one.
1043 * All functions of this object which require a table name call this function
1044 * themselves. Pass the canonical name to such functions. This is only needed
1045 * when calling query() directly.
1047 * @param string $name database table name
1049 function tableName( $name ) {
1051 # Skip quoted literals
1052 if ( $name{0} != '`' ) {
1053 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
1054 $name = "{$this->mTablePrefix}$name";
1056 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1057 $name = "`$wgSharedDB`.`$name`";
1067 * Fetch a number of table names into an array
1068 * This is handy when you need to construct SQL for joins
1071 * extract($dbr->tableNames('user','watchlist'));
1072 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1073 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1075 function tableNames() {
1076 $inArray = func_get_args();
1078 foreach ( $inArray as $name ) {
1079 $retVal[$name] = $this->tableName( $name );
1085 * Wrapper for addslashes()
1086 * @param string $s String to be slashed.
1087 * @return string slashed string.
1089 function strencode( $s ) {
1090 return addslashes( $s );
1094 * If it's a string, adds quotes and backslashes
1095 * Otherwise returns as-is
1097 function addQuotes( $s ) {
1098 if ( is_null( $s ) ) {
1101 # This will also quote numeric values. This should be harmless,
1102 # and protects against weird problems that occur when they really
1103 # _are_ strings such as article titles and string->number->string
1104 # conversion is not 1:1.
1105 return "'" . $this->strencode( $s ) . "'";
1110 * Returns an appropriately quoted sequence value for inserting a new row.
1111 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1112 * subclass will return an integer, and save the value for insertId()
1114 function nextSequenceValue( $seqName ) {
1120 * PostgreSQL doesn't have them and returns ""
1122 function useIndexClause( $index ) {
1123 return "FORCE INDEX ($index)";
1127 * REPLACE query wrapper
1128 * PostgreSQL simulates this with a DELETE followed by INSERT
1129 * $row is the row to insert, an associative array
1130 * $uniqueIndexes is an array of indexes. Each element may be either a
1131 * field name or an array of field names
1133 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1134 * However if you do this, you run the risk of encountering errors which wouldn't have
1137 * @todo migrate comment to phodocumentor format
1139 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1140 $table = $this->tableName( $table );
1143 if ( !is_array( reset( $rows ) ) ) {
1144 $rows = array( $rows );
1147 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1149 foreach ( $rows as $row ) {
1155 $sql .= '(' . $this->makeList( $row ) . ')';
1157 return $this->query( $sql, $fname );
1161 * DELETE where the condition is a join
1162 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1164 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1165 * join condition matches, set $conds='*'
1167 * DO NOT put the join condition in $conds
1169 * @param string $delTable The table to delete from.
1170 * @param string $joinTable The other table.
1171 * @param string $delVar The variable to join on, in the first table.
1172 * @param string $joinVar The variable to join on, in the second table.
1173 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1175 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1177 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1180 $delTable = $this->tableName( $delTable );
1181 $joinTable = $this->tableName( $joinTable );
1182 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1183 if ( $conds != '*' ) {
1184 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1187 return $this->query( $sql, $fname );
1191 * Returns the size of a text field, or -1 for "unlimited"
1193 function textFieldSize( $table, $field ) {
1194 $table = $this->tableName( $table );
1195 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1196 $res = $this->query( $sql, 'Database::textFieldSize' );
1197 $row = $this->fetchObject( $res );
1198 $this->freeResult( $res );
1200 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
1209 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1211 function lowPriorityOption() {
1212 return 'LOW_PRIORITY';
1216 * DELETE query wrapper
1218 * Use $conds == "*" to delete all rows
1220 function delete( $table, $conds, $fname = 'Database::delete' ) {
1222 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1224 $table = $this->tableName( $table );
1225 $sql = "DELETE FROM $table";
1226 if ( $conds != '*' ) {
1227 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1229 return $this->query( $sql, $fname );
1233 * INSERT SELECT wrapper
1234 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1235 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1236 * $conds may be "*" to copy the whole table
1237 * srcTable may be an array of tables.
1239 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1240 $destTable = $this->tableName( $destTable );
1241 if( is_array( $srcTable ) ) {
1242 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1244 $srcTable = $this->tableName( $srcTable );
1246 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1247 ' SELECT ' . implode( ',', $varMap ) .
1249 if ( $conds != '*' ) {
1250 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1252 return $this->query( $sql, $fname );
1256 * Construct a LIMIT query with optional offset
1257 * This is used for query pages
1259 function limitResult($limit,$offset) {
1260 return ' LIMIT '.(is_numeric($offset)?
"{$offset},":"")."{$limit} ";
1264 * Returns an SQL expression for a simple conditional.
1267 * @param string $cond SQL expression which will result in a boolean value
1268 * @param string $trueVal SQL expression to return if true
1269 * @param string $falseVal SQL expression to return if false
1270 * @return string SQL fragment
1272 function conditional( $cond, $trueVal, $falseVal ) {
1273 return " IF($cond, $trueVal, $falseVal) ";
1277 * Determines if the last failure was due to a deadlock
1279 function wasDeadlock() {
1280 return $this->lastErrno() == 1213;
1284 * Perform a deadlock-prone transaction.
1286 * This function invokes a callback function to perform a set of write
1287 * queries. If a deadlock occurs during the processing, the transaction
1288 * will be rolled back and the callback function will be called again.
1291 * $dbw->deadlockLoop( callback, ... );
1293 * Extra arguments are passed through to the specified callback function.
1295 * Returns whatever the callback function returned on its successful,
1296 * iteration, or false on error, for example if the retry limit was
1299 function deadlockLoop() {
1300 $myFname = 'Database::deadlockLoop';
1302 $this->query( 'BEGIN', $myFname );
1303 $args = func_get_args();
1304 $function = array_shift( $args );
1305 $oldIgnore = $this->ignoreErrors( true );
1306 $tries = DEADLOCK_TRIES
;
1307 if ( is_array( $function ) ) {
1308 $fname = $function[0];
1313 $retVal = call_user_func_array( $function, $args );
1314 $error = $this->lastError();
1315 $errno = $this->lastErrno();
1316 $sql = $this->lastQuery();
1319 if ( $this->wasDeadlock() ) {
1321 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1323 $this->reportQueryError( $error, $errno, $sql, $fname );
1326 } while( $this->wasDeadlock() && --$tries > 0 );
1327 $this->ignoreErrors( $oldIgnore );
1328 if ( $tries <= 0 ) {
1329 $this->query( 'ROLLBACK', $myFname );
1330 $this->reportQueryError( $error, $errno, $sql, $fname );
1333 $this->query( 'COMMIT', $myFname );
1339 * Do a SELECT MASTER_POS_WAIT()
1341 * @param string $file the binlog file
1342 * @param string $pos the binlog position
1343 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1345 function masterPosWait( $file, $pos, $timeout ) {
1346 $fname = 'Database::masterPosWait';
1347 wfProfileIn( $fname );
1350 # Commit any open transactions
1351 $this->immediateCommit();
1353 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1354 $encFile = $this->strencode( $file );
1355 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1356 $res = $this->doQuery( $sql );
1357 if ( $res && $row = $this->fetchRow( $res ) ) {
1358 $this->freeResult( $res );
1359 wfProfileOut( $fname );
1362 wfProfileOut( $fname );
1368 * Get the position of the master from SHOW SLAVE STATUS
1370 function getSlavePos() {
1371 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1372 $row = $this->fetchObject( $res );
1374 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1376 return array( false, false );
1381 * Get the position of the master from SHOW MASTER STATUS
1383 function getMasterPos() {
1384 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1385 $row = $this->fetchObject( $res );
1387 return array( $row->File
, $row->Position
);
1389 return array( false, false );
1394 * Begin a transaction, or if a transaction has already started, continue it
1396 function begin( $fname = 'Database::begin' ) {
1397 if ( !$this->mTrxLevel
) {
1398 $this->immediateBegin( $fname );
1405 * End a transaction, or decrement the nest level if transactions are nested
1407 function commit( $fname = 'Database::commit' ) {
1408 if ( $this->mTrxLevel
) {
1411 if ( !$this->mTrxLevel
) {
1412 $this->immediateCommit( $fname );
1417 * Rollback a transaction
1419 function rollback( $fname = 'Database::rollback' ) {
1420 $this->query( 'ROLLBACK', $fname );
1421 $this->mTrxLevel
= 0;
1425 * Begin a transaction, committing any previously open transaction
1427 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1428 $this->query( 'BEGIN', $fname );
1429 $this->mTrxLevel
= 1;
1433 * Commit transaction, if one is open
1435 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1436 $this->query( 'COMMIT', $fname );
1437 $this->mTrxLevel
= 0;
1441 * Return MW-style timestamp used for MySQL schema
1443 function timestamp( $ts=0 ) {
1444 return wfTimestamp(TS_MW
,$ts);
1448 * Local database timestamp format or null
1450 function timestampOrNull( $ts = null ) {
1451 if( is_null( $ts ) ) {
1454 return $this->timestamp( $ts );
1461 function resultObject( &$result ) {
1462 if( empty( $result ) ) {
1465 return new ResultWrapper( $this, $result );
1470 * Return aggregated value alias
1472 function aggregateValue ($valuedata,$valuename='value') {
1477 * @return string wikitext of a link to the server software's web site
1479 function getSoftwareLink() {
1480 return "[http://www.mysql.com/ MySQL]";
1484 * @return string Version information from the database
1486 function getServerVersion() {
1487 return mysql_get_server_info();
1491 * Ping the server and try to reconnect if it there is no connection
1494 if( function_exists( 'mysql_ping' ) ) {
1495 return mysql_ping( $this->mConn
);
1497 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1504 * At the moment, this will only work if the DB user has the PROCESS privilege
1507 $res = $this->query( 'SHOW PROCESSLIST' );
1508 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1509 # dubious, but unfortunately there's no easy rigorous way
1511 while ( $row = $this->fetchObject( $res ) ) {
1512 if ( $row->User
== 'system user' ) {
1513 if ( ++
$slaveThreads == 2 ) {
1514 # This is it, return the time
1523 * Get status information from SHOW STATUS in an associative array
1525 function getStatus() {
1526 $res = $this->query( 'SHOW STATUS' );
1528 while ( $row = $this->fetchObject( $res ) ) {
1529 $status[$row->Variable_name
] = $row->Value
;
1536 * Database abstraction object for mySQL
1537 * Inherit all methods and properties of Database::Database()
1539 * @package MediaWiki
1542 class DatabaseMysql
extends Database
{
1548 * Result wrapper for grabbing data queried by someone else
1550 * @package MediaWiki
1552 class ResultWrapper
{
1558 function ResultWrapper( $database, $result ) {
1559 $this->db
=& $database;
1560 $this->result
=& $result;
1566 function numRows() {
1567 return $this->db
->numRows( $this->result
);
1573 function fetchObject() {
1574 return $this->db
->fetchObject( $this->result
);
1580 function &fetchRow() {
1581 return $this->db
->fetchRow( $this->result
);
1588 $this->db
->freeResult( $this->result
);
1589 unset( $this->result
);
1593 function seek( $row ) {
1594 $this->db
->dataSeek( $this->result
, $row );
1598 #------------------------------------------------------------------------------
1600 #------------------------------------------------------------------------------
1603 * Standard fail function, called by default when a connection cannot be
1605 * Displays the file cache if possible
1607 function wfEmergencyAbort( &$conn, $error ) {
1608 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1609 global $wgSitename, $wgServer;
1611 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1612 # Hard coding strings instead.
1614 $noconnect = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server. <br />
1616 $mainpage = 'Main Page';
1617 $searchdisabled = <<<EOT
1618 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1619 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1623 <!-- SiteSearch Google -->
1624 <FORM method=GET action=\"http://www.google.com/search\">
1625 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1626 <A HREF=\"http://www.google.com/\">
1627 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1628 border=\"0\" ALT=\"Google\"></A>
1631 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1632 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1634 <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 />
1635 <input type='hidden' name='ie' value='$2'>
1636 <input type='hidden' name='oe' value='$2'>
1640 <!-- SiteSearch Google -->";
1641 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1644 if( !headers_sent() ) {
1645 header( 'HTTP/1.0 500 Internal Server Error' );
1646 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1647 /* Don't cache error pages! They cause no end of trouble... */
1648 header( 'Cache-control: none' );
1649 header( 'Pragma: nocache' );
1651 $msg = wfGetSiteNotice();
1653 $msg = str_replace( '$1', $error, $noconnect );
1657 if($wgUseFileCache) {
1662 $t = Title
::newFromURL( $title );
1663 } elseif (@/**/$_REQUEST['search']) {
1664 $search = $_REQUEST['search'];
1665 echo $searchdisabled;
1666 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1667 $wgInputEncoding ), $googlesearch );
1670 $t = Title
::newFromText( $mainpage );
1674 $cache = new CacheManager( $t );
1675 if( $cache->isFileCached() ) {
1676 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1677 $cachederror . "</b></p>\n";
1679 $tag = '<div id="article">';
1680 $text = str_replace(
1683 $cache->fetchPageText() );