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 );
29 function DBObject($data) {
43 * Database abstraction object
48 #------------------------------------------------------------------------------
50 #------------------------------------------------------------------------------
56 var $mServer, $mUser, $mPassword, $mConn, $mDBname;
57 var $mOut, $mOpened = false;
66 #------------------------------------------------------------------------------
68 #------------------------------------------------------------------------------
69 # These optionally set a variable and return the previous state
72 * Fail function, takes a Database as a parameter
73 * Set to false for default, 1 for ignore errors
75 function failFunction( $function = NULL ) {
76 return wfSetVar( $this->mFailFunction
, $function );
80 * Output page, used for reporting errors
81 * FALSE means discard output
83 function &setOutputPage( &$out ) {
88 * Boolean, controls output of large amounts of debug information
90 function debug( $debug = NULL ) {
91 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
95 * Turns buffering of SQL result sets on (true) or off (false).
96 * Default is "on" and it should not be changed without good reasons.
98 function bufferResults( $buffer = NULL ) {
99 if ( is_null( $buffer ) ) {
100 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
102 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
107 * Turns on (false) or off (true) the automatic generation and sending
108 * of a "we're sorry, but there has been a database error" page on
109 * database errors. Default is on (false). When turned off, the
110 * code should use wfLastErrno() and wfLastError() to handle the
111 * situation as appropriate.
113 function ignoreErrors( $ignoreErrors = NULL ) {
114 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
118 * The current depth of nested transactions
119 * @param integer $level
121 function trxLevel( $level = NULL ) {
122 return wfSetVar( $this->mTrxLevel
, $level );
126 * Number of errors logged, only useful when errors are ignored
128 function errorCount( $count = NULL ) {
129 return wfSetVar( $this->mErrorCount
, $count );
135 function lastQuery() { return $this->mLastQuery
; }
136 function isOpen() { return $this->mOpened
; }
139 #------------------------------------------------------------------------------
141 #------------------------------------------------------------------------------
144 * @param string $server database server host
145 * @param string $user database user name
146 * @param string $password database user password
147 * @param string $dbname database name
151 * @param failFunction
153 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
155 function Database( $server = false, $user = false, $password = false, $dbName = false,
156 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
158 global $wgOut, $wgDBprefix, $wgCommandLineMode;
159 # Can't get a reference if it hasn't been set yet
160 if ( !isset( $wgOut ) ) {
163 $this->mOut
=& $wgOut;
165 $this->mFailFunction
= $failFunction;
166 $this->mFlags
= $flags;
168 if ( $this->mFlags
& DBO_DEFAULT
) {
169 if ( $wgCommandLineMode ) {
170 $this->mFlags
&= ~DBO_TRX
;
172 $this->mFlags |
= DBO_TRX
;
177 // Faster read-only access
178 if ( wfReadOnly() ) {
179 $this->mFlags |= DBO_PERSISTENT;
180 $this->mFlags &= ~DBO_TRX;
183 /** Get the default table prefix*/
184 if ( $tablePrefix == 'get from global' ) {
185 $this->mTablePrefix
= $wgDBprefix;
187 $this->mTablePrefix
= $tablePrefix;
191 $this->open( $server, $user, $password, $dbName );
197 * @param failFunction
200 function newFromParams( $server, $user, $password, $dbName,
201 $failFunction = false, $flags = 0 )
203 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
207 * Usually aborts on failure
208 * If the failFunction is set to a non-zero integer, returns success
210 function open( $server, $user, $password, $dbName ) {
211 # Test for missing mysql.so
212 # First try to load it
213 if (!@extension_loaded
('mysql')) {
217 # Otherwise we get a suppressed fatal error, which is very hard to track down
218 if ( !function_exists( 'mysql_connect' ) ) {
219 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
223 $this->mServer
= $server;
224 $this->mUser
= $user;
225 $this->mPassword
= $password;
226 $this->mDBname
= $dbName;
230 if ( $this->mFlags
& DBO_PERSISTENT
) {
231 @/**/$this->mConn
= mysql_pconnect( $server, $user, $password );
233 # Create a new connection...
234 @/**/$this->mConn
= mysql_connect( $server, $user, $password, true );
237 if ( $dbName != '' ) {
238 if ( $this->mConn
!== false ) {
239 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
241 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
244 wfDebug( "DB connection error\n" );
245 wfDebug( "Server: $server, User: $user, Password: " .
246 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
251 $success = (bool)$this->mConn
;
255 $this->reportConnectionError();
258 $this->mOpened
= $success;
264 * Closes a database connection.
265 * if it is open : commits any open transactions
267 * @return bool operation success. true if already closed.
271 $this->mOpened
= false;
272 if ( $this->mConn
) {
273 if ( $this->trxLevel() ) {
274 $this->immediateCommit();
276 return mysql_close( $this->mConn
);
284 * @param string $msg error message ?
285 * @todo parameter $msg is not used
287 function reportConnectionError( $msg = '') {
288 if ( $this->mFailFunction
) {
289 if ( !is_int( $this->mFailFunction
) ) {
290 $ff = $this->mFailFunction
;
291 $ff( $this, $this->lastError() );
294 wfEmergencyAbort( $this, mysql_error() );
299 * Usually aborts on failure
300 * If errors are explicitly ignored, returns success
302 function query( $sql, $fname = '', $tempIgnore = false ) {
303 global $wgProfiling, $wgCommandLineMode;
305 if ( wfReadOnly() ) {
306 # This is a quick check for the most common kinds of write query used
307 # in MediaWiki, to provide extra safety in addition to UI-level checks.
308 # It is not intended to prevent every conceivable write query, or even
309 # to handle such queries gracefully.
310 if ( preg_match( '/^(update|insert|replace|delete)/i', $sql ) ) {
311 wfDebug( "Write query from $fname blocked\n" );
316 if ( $wgProfiling ) {
317 # generalizeSQL will probably cut down the query to reasonable
318 # logging size most of the time. The substr is really just a sanity check.
319 $profName = 'query: ' . $fname . ' ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
320 wfProfileIn( 'Database::query' );
321 wfProfileIn( $profName );
324 $this->mLastQuery
= $sql;
326 # Add a comment for easy SHOW PROCESSLIST interpretation
328 $commentedSql = "/* $fname */ $sql";
330 $commentedSql = $sql;
333 # If DBO_TRX is set, start a transaction
334 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() && $sql != 'BEGIN' ) {
338 if ( $this->debug() ) {
339 $sqlx = substr( $commentedSql, 0, 500 );
340 $sqlx = strtr( $sqlx, "\t\n", ' ' );
341 wfDebug( "SQL: $sqlx\n" );
344 # Do the query and handle errors
345 $ret = $this->doQuery( $commentedSql );
347 # Try reconnecting if the connection was lost
348 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
349 # Transaction is gone, like it or not
350 $this->mTrxLevel
= 0;
351 wfDebug( "Connection lost, reconnecting...\n" );
352 if ( $this->ping() ) {
353 wfDebug( "Reconnected\n" );
354 $ret = $this->doQuery( $commentedSql );
356 wfDebug( "Failed\n" );
360 if ( false === $ret ) {
361 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
364 if ( $wgProfiling ) {
365 wfProfileOut( $profName );
366 wfProfileOut( 'Database::query' );
372 * The DBMS-dependent part of query()
373 * @param string $sql SQL query.
375 function doQuery( $sql ) {
376 if( $this->bufferResults() ) {
377 $ret = mysql_query( $sql, $this->mConn
);
379 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
388 * @param string $fname
389 * @param bool $tempIgnore
391 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
392 global $wgCommandLineMode, $wgFullyInitialised;
393 # Ignore errors during error handling to avoid infinite recursion
394 $ignore = $this->ignoreErrors( true );
395 $this->mErrorCount ++
;
397 if( $ignore ||
$tempIgnore ) {
398 wfDebug("SQL ERROR (ignored): " . $error . "\n");
400 $sql1line = str_replace( "\n", "\\n", $sql );
401 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
402 wfDebug("SQL ERROR: " . $error . "\n");
403 if ( $wgCommandLineMode ||
!$this->mOut ||
empty( $wgFullyInitialised ) ) {
404 $message = "A database error has occurred\n" .
406 "Function: $fname\n" .
407 "Error: $errno $error\n";
408 if ( !$wgCommandLineMode ) {
409 $message = nl2br( $message );
411 wfDebugDieBacktrace( $message );
413 // this calls wfAbruptExit()
414 $this->mOut
->databaseError( $fname, $sql, $error, $errno );
417 $this->ignoreErrors( $ignore );
422 * Intended to be compatible with the PEAR::DB wrapper functions.
423 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
425 * ? = scalar value, quoted as necessary
426 * ! = raw SQL bit (a function for instance)
427 * & = filename; reads the file and inserts as a blob
428 * (we don't use this though...)
430 function prepare( $sql, $func = 'Database::prepare' ) {
431 /* MySQL doesn't support prepared statements (yet), so just
432 pack up the query for reference. We'll manually replace
434 return array( 'query' => $sql, 'func' => $func );
437 function freePrepared( $prepared ) {
438 /* No-op for MySQL */
442 * Execute a prepared query with the various arguments
443 * @param string $prepared the prepared sql
444 * @param mixed $args Either an array here, or put scalars as varargs
446 function execute( $prepared, $args = null ) {
447 if( !is_array( $args ) ) {
449 $args = func_get_args();
450 array_shift( $args );
452 $sql = $this->fillPrepared( $prepared['query'], $args );
453 return $this->query( $sql, $prepared['func'] );
457 * Prepare & execute an SQL statement, quoting and inserting arguments
458 * in the appropriate places.
459 * @param string $query
460 * @param string $args ...
462 function safeQuery( $query, $args = null ) {
463 $prepared = $this->prepare( $query, 'Database::safeQuery' );
464 if( !is_array( $args ) ) {
466 $args = func_get_args();
467 array_shift( $args );
469 $retval = $this->execute( $prepared, $args );
470 $this->freePrepared( $prepared );
475 * For faking prepared SQL statements on DBs that don't support
477 * @param string $preparedSql - a 'preparable' SQL statement
478 * @param array $args - array of arguments to fill it with
479 * @return string executable SQL
481 function fillPrepared( $preparedQuery, $args ) {
484 $this->preparedArgs
=& $args;
485 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
486 array( &$this, 'fillPreparedArg' ), $preparedQuery );
490 * preg_callback func for fillPrepared()
491 * The arguments should be in $this->preparedArgs and must not be touched
492 * while we're doing this.
494 * @param array $matches
498 function fillPreparedArg( $matches ) {
499 switch( $matches[1] ) {
500 case '\\?': return '?';
501 case '\\!': return '!';
502 case '\\&': return '&';
504 list( $n, $arg ) = each( $this->preparedArgs
);
505 switch( $matches[1] ) {
506 case '?': return $this->addQuotes( $arg );
507 case '!': return $arg;
509 # return $this->addQuotes( file_get_contents( $arg ) );
510 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
512 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
517 * @param mixed $res A SQL result
520 * Free a result object
522 function freeResult( $res ) {
523 if ( !@/**/mysql_free_result( $res ) ) {
524 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
529 * Fetch the next row from the given result object, in object form
531 function fetchObject( $res ) {
532 @/**/$row = mysql_fetch_object( $res );
533 if( mysql_errno() ) {
534 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
540 * Fetch the next row from the given result object
543 function fetchRow( $res ) {
544 @/**/$row = mysql_fetch_array( $res );
545 if (mysql_errno() ) {
546 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
552 * Get the number of rows in a result object
554 function numRows( $res ) {
555 @/**/$n = mysql_num_rows( $res );
556 if( mysql_errno() ) {
557 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
563 * Get the number of fields in a result object
564 * See documentation for mysql_num_fields()
566 function numFields( $res ) { return mysql_num_fields( $res ); }
569 * Get a field name in a result object
570 * See documentation for mysql_field_name()
572 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
575 * Get the inserted value of an auto-increment row
577 * The value inserted should be fetched from nextSequenceValue()
580 * $id = $dbw->nextSequenceValue('page_page_id_seq');
581 * $dbw->insert('page',array('page_id' => $id));
582 * $id = $dbw->insertId();
584 function insertId() { return mysql_insert_id( $this->mConn
); }
587 * Change the position of the cursor in a result object
588 * See mysql_data_seek()
590 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
593 * Get the last error number
596 function lastErrno() {
597 if ( $this->mConn
) {
598 return mysql_errno( $this->mConn
);
600 return mysql_errno();
605 * Get a description of the last error
606 * See mysql_error() for more details
608 function lastError() {
609 if ( $this->mConn
) {
610 $error = mysql_error( $this->mConn
);
612 $error = mysql_error();
615 $error .= ' (' . $this->mServer
. ')';
620 * Get the number of rows affected by the last write query
621 * See mysql_affected_rows() for more details
623 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
624 /**#@-*/ // end of template : @param $result
627 * Simple UPDATE wrapper
628 * Usually aborts on failure
629 * If errors are explicitly ignored, returns success
631 * This function exists for historical reasons, Database::update() has a more standard
632 * calling convention and feature set
634 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
636 $table = $this->tableName( $table );
637 $sql = "UPDATE $table SET $var = '" .
638 $this->strencode( $value ) . "' WHERE ($cond)";
639 return (bool)$this->query( $sql, DB_MASTER
, $fname );
643 * Simple SELECT wrapper, returns a single field, input must be encoded
644 * Usually aborts on failure
645 * If errors are explicitly ignored, returns FALSE on failure
647 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
648 if ( !is_array( $options ) ) {
649 $options = array( $options );
651 $options['LIMIT'] = 1;
653 $res = $this->select( $table, $var, $cond, $fname, $options );
654 if ( $res === false ||
!$this->numRows( $res ) ) {
657 $row = $this->fetchRow( $res );
658 if ( $row !== false ) {
659 $this->freeResult( $res );
667 * Returns an optional USE INDEX clause to go after the table, and a
668 * string to go at the end of the query
672 * @param array $options an associative array of options to be turned into
673 * an SQL query, valid keys are listed in the function.
676 function makeSelectOptions( $options ) {
679 if ( isset( $options['GROUP BY'] ) ) {
680 $tailOpts .= " GROUP BY {$options['GROUP BY']}";
682 if ( isset( $options['ORDER BY'] ) ) {
683 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
686 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
687 $tailOpts .= ' FOR UPDATE';
690 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
691 $tailOpts .= ' LOCK IN SHARE MODE';
694 if ( isset( $options['USE INDEX'] ) ) {
695 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
699 return array( $useIndex, $tailOpts );
705 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
707 if( is_array( $vars ) ) {
708 $vars = implode( ',', $vars );
710 if( !is_array( $options ) ) {
711 $options = array( $options );
713 if( is_array( $table ) ) {
714 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
715 } elseif ($table!='') {
716 $from = ' FROM ' .$this->tableName( $table );
721 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
723 if( !empty( $conds ) ) {
724 if ( is_array( $conds ) ) {
725 $conds = $this->makeList( $conds, LIST_AND
);
727 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
729 $sql = "SELECT $vars $from $useIndex $tailOpts";
731 if (isset($options['LIMIT'])) {
732 $sql = $this->limitResult($sql, $options['LIMIT'], isset($options['OFFSET']) ?
$options['OFFSET'] : false);
734 return $this->query( $sql, $fname );
738 * Single row SELECT wrapper
739 * Aborts or returns FALSE on error
741 * $vars: the selected variables
742 * $conds: a condition map, terms are ANDed together.
743 * Items with numeric keys are taken to be literal conditions
744 * Takes an array of selected variables, and a condition map, which is ANDed
745 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
746 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
747 * $obj- >page_id is the ID of the Astronomy article
749 * @todo migrate documentation to phpdocumentor format
751 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
752 $options['LIMIT'] = 1;
753 $res = $this->select( $table, $vars, $conds, $fname, $options );
754 if ( $res === false )
756 if ( !$this->numRows($res) ) {
757 $this->freeResult($res);
760 $obj = $this->fetchObject( $res );
761 $this->freeResult( $res );
767 * Removes most variables from an SQL query and replaces them with X or N for numbers.
768 * It's only slightly flawed. Don't use for anything important.
770 * @param string $sql A SQL Query
773 function generalizeSQL( $sql ) {
774 # This does the same as the regexp below would do, but in such a way
775 # as to avoid crashing php on some large strings.
776 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
778 $sql = str_replace ( "\\\\", '', $sql);
779 $sql = str_replace ( "\\'", '', $sql);
780 $sql = str_replace ( "\\\"", '', $sql);
781 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
782 $sql = preg_replace ('/".*"/s', "'X'", $sql);
784 # All newlines, tabs, etc replaced by single space
785 $sql = preg_replace ( "/\s+/", ' ', $sql);
788 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
794 * Determines whether a field exists in a table
795 * Usually aborts on failure
796 * If errors are explicitly ignored, returns NULL on failure
798 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
799 $table = $this->tableName( $table );
800 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE
, $fname );
807 while ( $row = $this->fetchObject( $res ) ) {
808 if ( $row->Field
== $field ) {
817 * Determines whether an index exists
818 * Usually aborts on failure
819 * If errors are explicitly ignored, returns NULL on failure
821 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
822 $info = $this->indexInfo( $table, $index, $fname );
823 if ( is_null( $info ) ) {
826 return $info !== false;
832 * Get information about an index into an object
833 * Returns false if the index does not exist
835 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
836 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
837 # SHOW INDEX should work for 3.x and up:
838 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
839 $table = $this->tableName( $table );
840 $sql = 'SHOW INDEX FROM '.$table;
841 $res = $this->query( $sql, $fname );
846 while ( $row = $this->fetchObject( $res ) ) {
847 if ( $row->Key_name
== $index ) {
855 * Query whether a given table exists
857 function tableExists( $table ) {
858 $table = $this->tableName( $table );
859 $old = $this->ignoreErrors( true );
860 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
861 $this->ignoreErrors( $old );
863 $this->freeResult( $res );
871 * mysql_fetch_field() wrapper
872 * Returns false if the field doesn't exist
877 function fieldInfo( $table, $field ) {
878 $table = $this->tableName( $table );
879 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
880 $n = mysql_num_fields( $res );
881 for( $i = 0; $i < $n; $i++
) {
882 $meta = mysql_fetch_field( $res, $i );
883 if( $field == $meta->name
) {
891 * mysql_field_type() wrapper
893 function fieldType( $res, $index ) {
894 return mysql_field_type( $res, $index );
898 * Determines if a given index is unique
900 function indexUnique( $table, $index ) {
901 $indexInfo = $this->indexInfo( $table, $index );
905 return !$indexInfo->Non_unique
;
909 * INSERT wrapper, inserts an array into a table
911 * $a may be a single associative array, or an array of these with numeric keys, for
914 * Usually aborts on failure
915 * If errors are explicitly ignored, returns success
917 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
918 # No rows to insert, easy just return now
919 if ( !count( $a ) ) {
923 $table = $this->tableName( $table );
924 if ( !is_array( $options ) ) {
925 $options = array( $options );
927 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
929 $keys = array_keys( $a[0] );
932 $keys = array_keys( $a );
935 $sql = 'INSERT ' . implode( ' ', $options ) .
936 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
940 foreach ( $a as $row ) {
946 $sql .= '(' . $this->makeList( $row ) . ')';
949 $sql .= '(' . $this->makeList( $a ) . ')';
951 return (bool)$this->query( $sql, $fname );
955 * Make UPDATE options for the Database::update function
958 * @param array $options The options passed to Database::update
961 function makeUpdateOptions( $options ) {
962 if( !is_array( $options ) ) {
963 wfDebugDieBacktrace( 'makeUpdateOptions given non-array' );
966 if ( in_array( 'LOW_PRIORITY', $options ) )
967 $opts[] = $this->lowPriorityOption();
968 if ( in_array( 'IGNORE', $options ) )
970 return implode(' ', $opts);
974 * UPDATE wrapper, takes a condition array and a SET array
976 * @param string $table The table to UPDATE
977 * @param array $values An array of values to SET
978 * @param array $conds An array of conditions (WHERE)
979 * @param string $fname The Class::Function calling this function
981 * @param array $options An array of UPDATE options, can be one or
982 * more of IGNORE, LOW_PRIORITY
984 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
985 $table = $this->tableName( $table );
986 $opts = $this->makeUpdateOptions( $options );
987 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
988 if ( $conds != '*' ) {
989 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
991 $this->query( $sql, $fname );
995 * Makes a wfStrencoded list from an array
996 * $mode: LIST_COMMA - comma separated, no field names
997 * LIST_AND - ANDed WHERE clause (without the WHERE)
998 * LIST_SET - comma separated with field names, like a SET clause
999 * LIST_NAMES - comma separated field names
1001 function makeList( $a, $mode = LIST_COMMA
) {
1002 if ( !is_array( $a ) ) {
1003 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
1008 foreach ( $a as $field => $value ) {
1010 if ( $mode == LIST_AND
) {
1018 if ( $mode == LIST_AND
&& is_numeric( $field ) ) {
1019 $list .= "($value)";
1020 } elseif ( $mode == LIST_AND
&& is_array ($value) ) {
1021 $list .= $field." IN (".$this->makeList($value).") ";
1023 if ( $mode == LIST_AND ||
$mode == LIST_SET
) {
1024 $list .= "$field = ";
1026 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1033 * Change the current database
1035 function selectDB( $db ) {
1036 $this->mDBname
= $db;
1037 return mysql_select_db( $db, $this->mConn
);
1041 * Starts a timer which will kill the DB thread after $timeout seconds
1043 function startTimer( $timeout ) {
1045 if( function_exists( 'mysql_thread_id' ) ) {
1046 # This will kill the query if it's still running after $timeout seconds.
1047 $tid = mysql_thread_id( $this->mConn
);
1048 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
1053 * Stop a timer started by startTimer()
1054 * Currently unimplemented.
1057 function stopTimer() { }
1060 * Format a table name ready for use in constructing an SQL query
1062 * This does two important things: it quotes table names which as necessary,
1063 * and it adds a table prefix if there is one.
1065 * All functions of this object which require a table name call this function
1066 * themselves. Pass the canonical name to such functions. This is only needed
1067 * when calling query() directly.
1069 * @param string $name database table name
1071 function tableName( $name ) {
1073 # Skip quoted literals
1074 if ( $name{0} != '`' ) {
1075 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
1076 $name = "{$this->mTablePrefix}$name";
1078 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1079 $name = "`$wgSharedDB`.`$name`";
1089 * Fetch a number of table names into an array
1090 * This is handy when you need to construct SQL for joins
1093 * extract($dbr->tableNames('user','watchlist'));
1094 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1095 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1097 function tableNames() {
1098 $inArray = func_get_args();
1100 foreach ( $inArray as $name ) {
1101 $retVal[$name] = $this->tableName( $name );
1107 * Wrapper for addslashes()
1108 * @param string $s String to be slashed.
1109 * @return string slashed string.
1111 function strencode( $s ) {
1112 return addslashes( $s );
1116 * If it's a string, adds quotes and backslashes
1117 * Otherwise returns as-is
1119 function addQuotes( $s ) {
1120 if ( is_null( $s ) ) {
1123 # This will also quote numeric values. This should be harmless,
1124 # and protects against weird problems that occur when they really
1125 # _are_ strings such as article titles and string->number->string
1126 # conversion is not 1:1.
1127 return "'" . $this->strencode( $s ) . "'";
1132 * Returns an appropriately quoted sequence value for inserting a new row.
1133 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1134 * subclass will return an integer, and save the value for insertId()
1136 function nextSequenceValue( $seqName ) {
1142 * PostgreSQL doesn't have them and returns ""
1144 function useIndexClause( $index ) {
1145 return "FORCE INDEX ($index)";
1149 * REPLACE query wrapper
1150 * PostgreSQL simulates this with a DELETE followed by INSERT
1151 * $row is the row to insert, an associative array
1152 * $uniqueIndexes is an array of indexes. Each element may be either a
1153 * field name or an array of field names
1155 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1156 * However if you do this, you run the risk of encountering errors which wouldn't have
1159 * @todo migrate comment to phodocumentor format
1161 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1162 $table = $this->tableName( $table );
1165 if ( !is_array( reset( $rows ) ) ) {
1166 $rows = array( $rows );
1169 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1171 foreach ( $rows as $row ) {
1177 $sql .= '(' . $this->makeList( $row ) . ')';
1179 return $this->query( $sql, $fname );
1183 * DELETE where the condition is a join
1184 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1186 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1187 * join condition matches, set $conds='*'
1189 * DO NOT put the join condition in $conds
1191 * @param string $delTable The table to delete from.
1192 * @param string $joinTable The other table.
1193 * @param string $delVar The variable to join on, in the first table.
1194 * @param string $joinVar The variable to join on, in the second table.
1195 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1197 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1199 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1202 $delTable = $this->tableName( $delTable );
1203 $joinTable = $this->tableName( $joinTable );
1204 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1205 if ( $conds != '*' ) {
1206 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1209 return $this->query( $sql, $fname );
1213 * Returns the size of a text field, or -1 for "unlimited"
1215 function textFieldSize( $table, $field ) {
1216 $table = $this->tableName( $table );
1217 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1218 $res = $this->query( $sql, 'Database::textFieldSize' );
1219 $row = $this->fetchObject( $res );
1220 $this->freeResult( $res );
1222 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
1231 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1233 function lowPriorityOption() {
1234 return 'LOW_PRIORITY';
1238 * DELETE query wrapper
1240 * Use $conds == "*" to delete all rows
1242 function delete( $table, $conds, $fname = 'Database::delete' ) {
1244 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1246 $table = $this->tableName( $table );
1247 $sql = "DELETE FROM $table";
1248 if ( $conds != '*' ) {
1249 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1251 return $this->query( $sql, $fname );
1255 * INSERT SELECT wrapper
1256 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1257 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1258 * $conds may be "*" to copy the whole table
1259 * srcTable may be an array of tables.
1261 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1262 $destTable = $this->tableName( $destTable );
1263 if( is_array( $srcTable ) ) {
1264 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1266 $srcTable = $this->tableName( $srcTable );
1268 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1269 ' SELECT ' . implode( ',', $varMap ) .
1271 if ( $conds != '*' ) {
1272 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1274 return $this->query( $sql, $fname );
1278 * Construct a LIMIT query with optional offset
1279 * This is used for query pages
1281 function limitResult($sql, $limit, $offset) {
1282 return "$sql LIMIT ".((is_numeric($offset) && $offset != 0)?
"{$offset},":"")."{$limit} ";
1284 function limitResultForUpdate($sql, $num) {
1285 return $this->limitResult($sql, $num, 0);
1289 * Returns an SQL expression for a simple conditional.
1292 * @param string $cond SQL expression which will result in a boolean value
1293 * @param string $trueVal SQL expression to return if true
1294 * @param string $falseVal SQL expression to return if false
1295 * @return string SQL fragment
1297 function conditional( $cond, $trueVal, $falseVal ) {
1298 return " IF($cond, $trueVal, $falseVal) ";
1302 * Determines if the last failure was due to a deadlock
1304 function wasDeadlock() {
1305 return $this->lastErrno() == 1213;
1309 * Perform a deadlock-prone transaction.
1311 * This function invokes a callback function to perform a set of write
1312 * queries. If a deadlock occurs during the processing, the transaction
1313 * will be rolled back and the callback function will be called again.
1316 * $dbw->deadlockLoop( callback, ... );
1318 * Extra arguments are passed through to the specified callback function.
1320 * Returns whatever the callback function returned on its successful,
1321 * iteration, or false on error, for example if the retry limit was
1324 function deadlockLoop() {
1325 $myFname = 'Database::deadlockLoop';
1328 $args = func_get_args();
1329 $function = array_shift( $args );
1330 $oldIgnore = $this->ignoreErrors( true );
1331 $tries = DEADLOCK_TRIES
;
1332 if ( is_array( $function ) ) {
1333 $fname = $function[0];
1338 $retVal = call_user_func_array( $function, $args );
1339 $error = $this->lastError();
1340 $errno = $this->lastErrno();
1341 $sql = $this->lastQuery();
1344 if ( $this->wasDeadlock() ) {
1346 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1348 $this->reportQueryError( $error, $errno, $sql, $fname );
1351 } while( $this->wasDeadlock() && --$tries > 0 );
1352 $this->ignoreErrors( $oldIgnore );
1353 if ( $tries <= 0 ) {
1354 $this->query( 'ROLLBACK', $myFname );
1355 $this->reportQueryError( $error, $errno, $sql, $fname );
1358 $this->query( 'COMMIT', $myFname );
1364 * Do a SELECT MASTER_POS_WAIT()
1366 * @param string $file the binlog file
1367 * @param string $pos the binlog position
1368 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1370 function masterPosWait( $file, $pos, $timeout ) {
1371 $fname = 'Database::masterPosWait';
1372 wfProfileIn( $fname );
1375 # Commit any open transactions
1376 $this->immediateCommit();
1378 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1379 $encFile = $this->strencode( $file );
1380 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1381 $res = $this->doQuery( $sql );
1382 if ( $res && $row = $this->fetchRow( $res ) ) {
1383 $this->freeResult( $res );
1384 wfProfileOut( $fname );
1387 wfProfileOut( $fname );
1393 * Get the position of the master from SHOW SLAVE STATUS
1395 function getSlavePos() {
1396 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1397 $row = $this->fetchObject( $res );
1399 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1401 return array( false, false );
1406 * Get the position of the master from SHOW MASTER STATUS
1408 function getMasterPos() {
1409 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1410 $row = $this->fetchObject( $res );
1412 return array( $row->File
, $row->Position
);
1414 return array( false, false );
1419 * Begin a transaction, or if a transaction has already started, continue it
1421 function begin( $fname = 'Database::begin' ) {
1422 if ( !$this->mTrxLevel
) {
1423 $this->immediateBegin( $fname );
1430 * End a transaction, or decrement the nest level if transactions are nested
1432 function commit( $fname = 'Database::commit' ) {
1433 if ( $this->mTrxLevel
) {
1436 if ( !$this->mTrxLevel
) {
1437 $this->immediateCommit( $fname );
1442 * Rollback a transaction
1444 function rollback( $fname = 'Database::rollback' ) {
1445 $this->query( 'ROLLBACK', $fname );
1446 $this->mTrxLevel
= 0;
1450 * Begin a transaction, committing any previously open transaction
1452 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1453 $this->query( 'BEGIN', $fname );
1454 $this->mTrxLevel
= 1;
1458 * Commit transaction, if one is open
1460 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1461 $this->query( 'COMMIT', $fname );
1462 $this->mTrxLevel
= 0;
1466 * Return MW-style timestamp used for MySQL schema
1468 function timestamp( $ts=0 ) {
1469 return wfTimestamp(TS_MW
,$ts);
1473 * Local database timestamp format or null
1475 function timestampOrNull( $ts = null ) {
1476 if( is_null( $ts ) ) {
1479 return $this->timestamp( $ts );
1486 function resultObject( &$result ) {
1487 if( empty( $result ) ) {
1490 return new ResultWrapper( $this, $result );
1495 * Return aggregated value alias
1497 function aggregateValue ($valuedata,$valuename='value') {
1502 * @return string wikitext of a link to the server software's web site
1504 function getSoftwareLink() {
1505 return "[http://www.mysql.com/ MySQL]";
1509 * @return string Version information from the database
1511 function getServerVersion() {
1512 return mysql_get_server_info();
1516 * Ping the server and try to reconnect if it there is no connection
1519 if( function_exists( 'mysql_ping' ) ) {
1520 return mysql_ping( $this->mConn
);
1522 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1529 * At the moment, this will only work if the DB user has the PROCESS privilege
1532 $res = $this->query( 'SHOW PROCESSLIST' );
1533 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1534 # dubious, but unfortunately there's no easy rigorous way
1536 while ( $row = $this->fetchObject( $res ) ) {
1537 if ( $row->User
== 'system user' ) {
1538 if ( ++
$slaveThreads == 2 ) {
1539 # This is it, return the time
1548 * Get status information from SHOW STATUS in an associative array
1550 function getStatus() {
1551 $res = $this->query( 'SHOW STATUS' );
1553 while ( $row = $this->fetchObject( $res ) ) {
1554 $status[$row->Variable_name
] = $row->Value
;
1560 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1562 function maxListLen() {
1566 function encodeBlob($b) {
1570 function notNullTimestamp() {
1573 function isNullTimestamp() {
1579 * Database abstraction object for mySQL
1580 * Inherit all methods and properties of Database::Database()
1582 * @package MediaWiki
1585 class DatabaseMysql
extends Database
{
1591 * Result wrapper for grabbing data queried by someone else
1593 * @package MediaWiki
1595 class ResultWrapper
{
1601 function ResultWrapper( $database, $result ) {
1602 $this->db
=& $database;
1603 $this->result
=& $result;
1609 function numRows() {
1610 return $this->db
->numRows( $this->result
);
1616 function fetchObject() {
1617 return $this->db
->fetchObject( $this->result
);
1623 function &fetchRow() {
1624 return $this->db
->fetchRow( $this->result
);
1631 $this->db
->freeResult( $this->result
);
1632 unset( $this->result
);
1636 function seek( $row ) {
1637 $this->db
->dataSeek( $this->result
, $row );
1641 #------------------------------------------------------------------------------
1643 #------------------------------------------------------------------------------
1646 * Standard fail function, called by default when a connection cannot be
1648 * Displays the file cache if possible
1650 function wfEmergencyAbort( &$conn, $error ) {
1651 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1652 global $wgSitename, $wgServer;
1654 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1655 # Hard coding strings instead.
1657 $noconnect = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server: $1. <br />
1659 $mainpage = 'Main Page';
1660 $searchdisabled = <<<EOT
1661 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1662 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1666 <!-- SiteSearch Google -->
1667 <FORM method=GET action=\"http://www.google.com/search\">
1668 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1669 <A HREF=\"http://www.google.com/\">
1670 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1671 border=\"0\" ALT=\"Google\"></A>
1674 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1675 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1677 <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 />
1678 <input type='hidden' name='ie' value='$2'>
1679 <input type='hidden' name='oe' value='$2'>
1683 <!-- SiteSearch Google -->";
1684 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1687 if( !headers_sent() ) {
1688 header( 'HTTP/1.0 500 Internal Server Error' );
1689 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1690 /* Don't cache error pages! They cause no end of trouble... */
1691 header( 'Cache-control: none' );
1692 header( 'Pragma: nocache' );
1694 $msg = wfGetSiteNotice();
1696 $msg = str_replace( '$1', $error, $noconnect );
1700 if($wgUseFileCache) {
1705 $t = Title
::newFromURL( $title );
1706 } elseif (@/**/$_REQUEST['search']) {
1707 $search = $_REQUEST['search'];
1708 echo $searchdisabled;
1709 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1710 $wgInputEncoding ), $googlesearch );
1713 $t = Title
::newFromText( $mainpage );
1717 $cache = new CacheManager( $t );
1718 if( $cache->isFileCached() ) {
1719 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1720 $cachederror . "</b></p>\n";
1722 $tag = '<div id="article">';
1723 $text = str_replace(
1726 $cache->fetchPageText() );