RC patrol fixlet: include rcid in 'diff' link in enhanced mode, for individually...
[mediawiki.git] / includes / Database.php
blobb6153a3b6f4c3e3ffa052a7a623191bb3cad13de
1 <?php
2 /**
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
5 * @version # $Id$
6 * @package MediaWiki
7 */
9 /**
10 * Depends on the CacheManager
12 require_once( 'CacheManager.php' );
14 /** See Database::makeList() */
15 define( 'LIST_COMMA', 0 );
16 define( 'LIST_AND', 1 );
17 define( 'LIST_SET', 2 );
18 define( 'LIST_NAMES', 3);
20 /** Number of times to re-try an operation in case of deadlock */
21 define( 'DEADLOCK_TRIES', 4 );
22 /** Minimum time to wait before retry, in microseconds */
23 define( 'DEADLOCK_DELAY_MIN', 500000 );
24 /** Maximum time to wait before retry */
25 define( 'DEADLOCK_DELAY_MAX', 1500000 );
27 /**
28 * Database abstraction object
29 * @package MediaWiki
30 * @version # $Id$
32 class Database {
34 #------------------------------------------------------------------------------
35 # Variables
36 #------------------------------------------------------------------------------
37 /**#@+
38 * @access private
40 var $mLastQuery = '';
42 var $mServer, $mUser, $mPassword, $mConn, $mDBname;
43 var $mOut, $mOpened = false;
45 var $mFailFunction;
46 var $mTablePrefix;
47 var $mFlags;
48 var $mTrxLevel = 0;
49 /**#@-*/
51 #------------------------------------------------------------------------------
52 # Accessors
53 #------------------------------------------------------------------------------
54 # These optionally set a variable and return the previous state
56 /**
57 * Fail function, takes a Database as a parameter
58 * Set to false for default, 1 for ignore errors
60 function failFunction( $function = NULL ) {
61 return wfSetVar( $this->mFailFunction, $function );
64 /**
65 * Output page, used for reporting errors
66 * FALSE means discard output
68 function &setOutputPage( &$out ) {
69 $this->mOut =& $out;
72 /**
73 * Boolean, controls output of large amounts of debug information
75 function debug( $debug = NULL ) {
76 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
79 /**
80 * Turns buffering of SQL result sets on (true) or off (false).
81 * Default is "on" and it should not be changed without good reasons.
83 function bufferResults( $buffer = NULL ) {
84 if ( is_null( $buffer ) ) {
85 return !(bool)( $this->mFlags & DBO_NOBUFFER );
86 } else {
87 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
91 /**
92 * Turns on (false) or off (true) the automatic generation and sending
93 * of a "we're sorry, but there has been a database error" page on
94 * database errors. Default is on (false). When turned off, the
95 * code should use wfLastErrno() and wfLastError() to handle the
96 * situation as appropriate.
98 function ignoreErrors( $ignoreErrors = NULL ) {
99 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
103 * The current depth of nested transactions
104 * @param integer $level
106 function trxLevel( $level = NULL ) {
107 return wfSetVar( $this->mTrxLevel, $level );
110 /**#@+
111 * Get function
113 function lastQuery() { return $this->mLastQuery; }
114 function isOpen() { return $this->mOpened; }
115 /**#@-*/
117 #------------------------------------------------------------------------------
118 # Other functions
119 #------------------------------------------------------------------------------
121 /**#@+
122 * @param string $server database server host
123 * @param string $user database user name
124 * @param string $password database user password
125 * @param string $dbname database name
129 * @param failFunction
130 * @param $flags
131 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
133 function Database( $server = false, $user = false, $password = false, $dbName = false,
134 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
136 global $wgOut, $wgDBprefix, $wgCommandLineMode;
137 # Can't get a reference if it hasn't been set yet
138 if ( !isset( $wgOut ) ) {
139 $wgOut = NULL;
141 $this->mOut =& $wgOut;
143 $this->mFailFunction = $failFunction;
144 $this->mFlags = $flags;
146 if ( $this->mFlags & DBO_DEFAULT ) {
147 if ( $wgCommandLineMode ) {
148 $this->mFlags &= ~DBO_TRX;
149 } else {
150 $this->mFlags |= DBO_TRX;
154 /** Get the default table prefix*/
155 if ( $tablePrefix == 'get from global' ) {
156 $this->mTablePrefix = $wgDBprefix;
157 } else {
158 $this->mTablePrefix = $tablePrefix;
161 if ( $server ) {
162 $this->open( $server, $user, $password, $dbName );
167 * @static
168 * @param failFunction
169 * @param $flags
171 function newFromParams( $server, $user, $password, $dbName,
172 $failFunction = false, $flags = 0 )
174 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
178 * Usually aborts on failure
179 * If the failFunction is set to a non-zero integer, returns success
181 function open( $server, $user, $password, $dbName ) {
182 # Test for missing mysql.so
183 # First try to load it
184 if (!@extension_loaded('mysql')) {
185 @dl('mysql.so');
188 # Otherwise we get a suppressed fatal error, which is very hard to track down
189 if ( !function_exists( 'mysql_connect' ) ) {
190 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
193 $this->close();
194 $this->mServer = $server;
195 $this->mUser = $user;
196 $this->mPassword = $password;
197 $this->mDBname = $dbName;
199 $success = false;
201 @/**/$this->mConn = mysql_connect( $server, $user, $password );
202 if ( $dbName != '' ) {
203 if ( $this->mConn !== false ) {
204 $success = @/**/mysql_select_db( $dbName, $this->mConn );
205 if ( !$success ) {
206 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
208 } else {
209 wfDebug( "DB connection error\n" );
210 wfDebug( "Server: $server, User: $user, Password: " .
211 substr( $password, 0, 3 ) . "...\n" );
212 $success = false;
214 } else {
215 # Delay USE query
216 $success = !!$this->mConn;
219 if ( !$success ) {
220 $this->reportConnectionError();
221 $this->close();
223 $this->mOpened = $success;
224 return $success;
226 /**#@-*/
229 * Closes a database connection.
230 * if it is open : commits any open transactions
232 * @return bool operation success. true if already closed.
234 function close()
236 $this->mOpened = false;
237 if ( $this->mConn ) {
238 if ( $this->trxLevel() ) {
239 $this->immediateCommit();
241 return mysql_close( $this->mConn );
242 } else {
243 return true;
248 * @access private
249 * @param string $msg error message ?
250 * @todo parameter $msg is not used
252 function reportConnectionError( $msg = '') {
253 if ( $this->mFailFunction ) {
254 if ( !is_int( $this->mFailFunction ) ) {
255 $ff = $this->mFailFunction;
256 $ff( $this, mysql_error() );
258 } else {
259 wfEmergencyAbort( $this, mysql_error() );
264 * Usually aborts on failure
265 * If errors are explicitly ignored, returns success
267 function query( $sql, $fname = '', $tempIgnore = false ) {
268 global $wgProfiling, $wgCommandLineMode;
270 if ( $wgProfiling ) {
271 # generalizeSQL will probably cut down the query to reasonable
272 # logging size most of the time. The substr is really just a sanity check.
273 $profName = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
274 wfProfileIn( $profName );
277 $this->mLastQuery = $sql;
279 if ( $this->debug() ) {
280 $sqlx = substr( $sql, 0, 500 );
281 $sqlx = wordwrap(strtr($sqlx,"\t\n",' '));
282 wfDebug( "SQL: $sqlx\n" );
284 # Add a comment for easy SHOW PROCESSLIST interpretation
285 if ( $fname ) {
286 $commentedSql = "/* $fname */ $sql";
287 } else {
288 $commentedSql = $sql;
291 # If DBO_TRX is set, start a transaction
292 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() && $sql != 'BEGIN' ) {
293 $this->begin();
296 # Do the query and handle errors
297 $ret = $this->doQuery( $commentedSql );
298 if ( false === $ret ) {
299 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
302 if ( $wgProfiling ) {
303 wfProfileOut( $profName );
305 return $ret;
309 * The DBMS-dependent part of query()
310 * @param string $sql SQL query.
312 function doQuery( $sql ) {
313 if( $this->bufferResults() ) {
314 $ret = mysql_query( $sql, $this->mConn );
315 } else {
316 $ret = mysql_unbuffered_query( $sql, $this->mConn );
318 return $ret;
322 * @param $error
323 * @param $errno
324 * @param $sql
325 * @param string $fname
326 * @param bool $tempIgnore
328 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
329 global $wgCommandLineMode, $wgFullyInitialised;
330 # Ignore errors during error handling to avoid infinite recursion
331 $ignore = $this->ignoreErrors( true );
333 if( $ignore || $tempIgnore ) {
334 wfDebug("SQL ERROR (ignored): " . $error . "\n");
335 } else {
336 $sql1line = str_replace( "\n", "\\n", $sql );
337 wfLogDBError("$fname\t$errno\t$error\t$sql1line\n");
338 wfDebug("SQL ERROR: " . $error . "\n");
339 if ( $wgCommandLineMode || !$this->mOut || empty( $wgFullyInitialised ) ) {
340 $message = "A database error has occurred\n" .
341 "Query: $sql\n" .
342 "Function: $fname\n" .
343 "Error: $errno $error\n";
344 if ( !$wgCommandLineMode ) {
345 $message = nl2br( $message );
347 wfDebugDieBacktrace( $message );
348 } else {
349 // this calls wfAbruptExit()
350 $this->mOut->databaseError( $fname, $sql, $error, $errno );
353 $this->ignoreErrors( $ignore );
358 * Intended to be compatible with the PEAR::DB wrapper functions.
359 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
361 * ? = scalar value, quoted as necessary
362 * ! = raw SQL bit (a function for instance)
363 * & = filename; reads the file and inserts as a blob
364 * (we don't use this though...)
366 function prepare( $sql, $func = 'Database::prepare' ) {
367 /* MySQL doesn't support prepared statements (yet), so just
368 pack up the query for reference. We'll manually replace
369 the bits later. */
370 return array( 'query' => $sql, 'func' => $func );
373 function freePrepared( $prepared ) {
374 /* No-op for MySQL */
378 * Execute a prepared query with the various arguments
379 * @param string $prepared the prepared sql
380 * @param mixed $args Either an array here, or put scalars as varargs
382 function execute( $prepared, $args = null ) {
383 if( !is_array( $args ) ) {
384 # Pull the var args
385 $args = func_get_args();
386 array_shift( $args );
388 $sql = $this->fillPrepared( $prepared['query'], $args );
389 return $this->query( $sql, $prepared['func'] );
393 * Prepare & execute an SQL statement, quoting and inserting arguments
394 * in the appropriate places.
395 * @param
397 function safeQuery( $query, $args = null ) {
398 $prepared = $this->prepare( $query, 'Database::safeQuery' );
399 if( !is_array( $args ) ) {
400 # Pull the var args
401 $args = func_get_args();
402 array_shift( $args );
404 $retval = $this->execute( $prepared, $args );
405 $this->freePrepared( $prepared );
406 return $retval;
410 * For faking prepared SQL statements on DBs that don't support
411 * it directly.
412 * @param string $preparedSql - a 'preparable' SQL statement
413 * @param array $args - array of arguments to fill it with
414 * @return string executable SQL
416 function fillPrepared( $preparedQuery, $args ) {
417 $n = 0;
418 reset( $args );
419 $this->preparedArgs =& $args;
420 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
421 array( &$this, 'fillPreparedArg' ), $preparedQuery );
425 * preg_callback func for fillPrepared()
426 * The arguments should be in $this->preparedArgs and must not be touched
427 * while we're doing this.
429 * @param array $matches
430 * @return string
431 * @access private
433 function fillPreparedArg( $matches ) {
434 switch( $matches[1] ) {
435 case '\\?': return '?';
436 case '\\!': return '!';
437 case '\\&': return '&';
439 list( $n, $arg ) = each( $this->preparedArgs );
440 switch( $matches[1] ) {
441 case '?': return $this->addQuotes( $arg );
442 case '!': return $arg;
443 case '&':
444 # return $this->addQuotes( file_get_contents( $arg ) );
445 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
446 default:
447 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
451 /**#@+
452 * @param mixed $res A SQL result
455 * Free a result object
457 function freeResult( $res ) {
458 if ( !@/**/mysql_free_result( $res ) ) {
459 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
464 * Fetch the next row from the given result object, in object form
466 function fetchObject( $res ) {
467 @/**/$row = mysql_fetch_object( $res );
468 if( mysql_errno() ) {
469 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
471 return $row;
475 * Fetch the next row from the given result object
476 * Returns an array
478 function fetchRow( $res ) {
479 @/**/$row = mysql_fetch_array( $res );
480 if (mysql_errno() ) {
481 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
483 return $row;
487 * Get the number of rows in a result object
489 function numRows( $res ) {
490 @/**/$n = mysql_num_rows( $res );
491 if( mysql_errno() ) {
492 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
494 return $n;
498 * Get the number of fields in a result object
499 * See documentation for mysql_num_fields()
501 function numFields( $res ) { return mysql_num_fields( $res ); }
504 * Get a field name in a result object
505 * See documentation for mysql_field_name()
507 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
510 * Get the inserted value of an auto-increment row
512 * The value inserted should be fetched from nextSequenceValue()
514 * Example:
515 * $id = $dbw->nextSequenceValue('cur_cur_id_seq');
516 * $dbw->insert('cur',array('cur_id' => $id));
517 * $id = $dbw->insertId();
519 function insertId() { return mysql_insert_id( $this->mConn ); }
522 * Change the position of the cursor in a result object
523 * See mysql_data_seek()
525 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
528 * Get the last error number
529 * See mysql_errno()
531 function lastErrno() { return mysql_errno(); }
534 * Get a description of the last error
535 * See mysql_error() for more details
537 function lastError() { return mysql_error(); }
540 * Get the number of rows affected by the last write query
541 * See mysql_affected_rows() for more details
543 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
544 /**#@-*/ // end of template : @param $result
547 * Simple UPDATE wrapper
548 * Usually aborts on failure
549 * If errors are explicitly ignored, returns success
551 * This function exists for historical reasons, Database::update() has a more standard
552 * calling convention and feature set
554 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
556 $table = $this->tableName( $table );
557 $sql = "UPDATE $table SET $var = '" .
558 $this->strencode( $value ) . "' WHERE ($cond)";
559 return !!$this->query( $sql, DB_MASTER, $fname );
563 * Simple SELECT wrapper, returns a single field, input must be encoded
564 * Usually aborts on failure
565 * If errors are explicitly ignored, returns FALSE on failure
567 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
568 if ( !is_array( $options ) ) {
569 $options = array( $options );
571 $options['LIMIT'] = 1;
573 $res = $this->select( $table, $var, $cond, $fname, $options );
574 if ( $res === false || !$this->numRows( $res ) ) {
575 return false;
577 $row = $this->fetchRow( $res );
578 if ( $row !== false ) {
579 $this->freeResult( $res );
580 return $row[0];
581 } else {
582 return false;
587 * Returns an optional USE INDEX clause to go after the table, and a
588 * string to go at the end of the query
590 function makeSelectOptions( $options ) {
591 if ( !is_array( $options ) ) {
592 $options = array( $options );
595 $tailOpts = '';
597 if ( isset( $options['ORDER BY'] ) ) {
598 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
600 if ( isset( $options['LIMIT'] ) ) {
601 $tailOpts .= " LIMIT {$options['LIMIT']}";
604 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
605 $tailOpts .= ' FOR UPDATE';
608 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
609 $tailOpts .= ' LOCK IN SHARE MODE';
612 if ( isset( $options['USE INDEX'] ) ) {
613 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
614 } else {
615 $useIndex = '';
617 return array( $useIndex, $tailOpts );
621 * SELECT wrapper
623 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
625 if ( is_array( $vars ) ) {
626 $vars = implode( ',', $vars );
628 if( is_array( $table ) ) {
629 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
630 } elseif ($table!='') {
631 $from = ' FROM ' .$this->tableName( $table );
632 } else {
633 $from = '';
636 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
638 if ( $conds !== false && $conds != '' ) {
639 if ( is_array( $conds ) ) {
640 $conds = $this->makeList( $conds, LIST_AND );
642 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
643 } else {
644 $sql = "SELECT $vars $from $useIndex $tailOpts";
646 return $this->query( $sql, $fname );
650 * Single row SELECT wrapper
651 * Aborts or returns FALSE on error
653 * $vars: the selected variables
654 * $conds: a condition map, terms are ANDed together.
655 * Items with numeric keys are taken to be literal conditions
656 * Takes an array of selected variables, and a condition map, which is ANDed
657 * e.g. selectRow( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
658 * would return an object where $obj->cur_id is the ID of the Astronomy article
660 * @todo migrate documentation to phpdocumentor format
662 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
663 $options['LIMIT'] = 1;
664 $res = $this->select( $table, $vars, $conds, $fname, $options );
665 if ( $res === false || !$this->numRows( $res ) ) {
666 return false;
668 $obj = $this->fetchObject( $res );
669 $this->freeResult( $res );
670 return $obj;
675 * Removes most variables from an SQL query and replaces them with X or N for numbers.
676 * It's only slightly flawed. Don't use for anything important.
678 * @param string $sql A SQL Query
679 * @static
681 function generalizeSQL( $sql ) {
682 # This does the same as the regexp below would do, but in such a way
683 # as to avoid crashing php on some large strings.
684 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
686 $sql = str_replace ( "\\\\", '', $sql);
687 $sql = str_replace ( "\\'", '', $sql);
688 $sql = str_replace ( "\\\"", '', $sql);
689 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
690 $sql = preg_replace ('/".*"/s', "'X'", $sql);
692 # All newlines, tabs, etc replaced by single space
693 $sql = preg_replace ( "/\s+/", ' ', $sql);
695 # All numbers => N
696 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
698 return $sql;
702 * Determines whether a field exists in a table
703 * Usually aborts on failure
704 * If errors are explicitly ignored, returns NULL on failure
706 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
707 $table = $this->tableName( $table );
708 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE, $fname );
709 if ( !$res ) {
710 return NULL;
713 $found = false;
715 while ( $row = $this->fetchObject( $res ) ) {
716 if ( $row->Field == $field ) {
717 $found = true;
718 break;
721 return $found;
725 * Determines whether an index exists
726 * Usually aborts on failure
727 * If errors are explicitly ignored, returns NULL on failure
729 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
730 $info = $this->indexInfo( $table, $index, $fname );
731 if ( is_null( $info ) ) {
732 return NULL;
733 } else {
734 return $info !== false;
740 * Get information about an index into an object
741 * Returns false if the index does not exist
743 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
744 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
745 # SHOW INDEX should work for 3.x and up:
746 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
747 $table = $this->tableName( $table );
748 $sql = 'SHOW INDEX FROM '.$table;
749 $res = $this->query( $sql, $fname );
750 if ( !$res ) {
751 return NULL;
754 while ( $row = $this->fetchObject( $res ) ) {
755 if ( $row->Key_name == $index ) {
756 return $row;
759 return false;
763 * Query whether a given table exists
765 function tableExists( $table ) {
766 $table = $this->tableName( $table );
767 $old = $this->ignoreErrors( true );
768 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
769 $this->ignoreErrors( $old );
770 if( $res ) {
771 $this->freeResult( $res );
772 return true;
773 } else {
774 return false;
779 * mysql_fetch_field() wrapper
780 * Returns false if the field doesn't exist
782 * @param $table
783 * @param $field
785 function fieldInfo( $table, $field ) {
786 $table = $this->tableName( $table );
787 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
788 $n = mysql_num_fields( $res );
789 for( $i = 0; $i < $n; $i++ ) {
790 $meta = mysql_fetch_field( $res, $i );
791 if( $field == $meta->name ) {
792 return $meta;
795 return false;
799 * mysql_field_type() wrapper
801 function fieldType( $res, $index ) {
802 return mysql_field_type( $res, $index );
806 * Determines if a given index is unique
808 function indexUnique( $table, $index ) {
809 $indexInfo = $this->indexInfo( $table, $index );
810 if ( !$indexInfo ) {
811 return NULL;
813 return !$indexInfo->Non_unique;
817 * INSERT wrapper, inserts an array into a table
819 * $a may be a single associative array, or an array of these with numeric keys, for
820 * multi-row insert.
822 * Usually aborts on failure
823 * If errors are explicitly ignored, returns success
825 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
826 # No rows to insert, easy just return now
827 if ( !count( $a ) ) {
828 return true;
831 $table = $this->tableName( $table );
832 if ( !is_array( $options ) ) {
833 $options = array( $options );
835 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
836 $multi = true;
837 $keys = array_keys( $a[0] );
838 } else {
839 $multi = false;
840 $keys = array_keys( $a );
843 $sql = 'INSERT ' . implode( ' ', $options ) .
844 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
846 if ( $multi ) {
847 $first = true;
848 foreach ( $a as $row ) {
849 if ( $first ) {
850 $first = false;
851 } else {
852 $sql .= ',';
854 $sql .= '(' . $this->makeList( $row ) . ')';
856 } else {
857 $sql .= '(' . $this->makeList( $a ) . ')';
859 return !!$this->query( $sql, $fname );
863 * UPDATE wrapper, takes a condition array and a SET array
865 function update( $table, $values, $conds, $fname = 'Database::update' ) {
866 $table = $this->tableName( $table );
867 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET );
868 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
869 $this->query( $sql, $fname );
873 * Makes a wfStrencoded list from an array
874 * $mode: LIST_COMMA - comma separated, no field names
875 * LIST_AND - ANDed WHERE clause (without the WHERE)
876 * LIST_SET - comma separated with field names, like a SET clause
877 * LIST_NAMES - comma separated field names
879 function makeList( $a, $mode = LIST_COMMA ) {
880 if ( !is_array( $a ) ) {
881 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
884 $first = true;
885 $list = '';
886 foreach ( $a as $field => $value ) {
887 if ( !$first ) {
888 if ( $mode == LIST_AND ) {
889 $list .= ' AND ';
890 } else {
891 $list .= ',';
893 } else {
894 $first = false;
896 if ( $mode == LIST_AND && is_numeric( $field ) ) {
897 $list .= "($value)";
898 } elseif ( $mode == LIST_AND && is_array ($value) ) {
899 $list .= $field." IN (".$this->makeList($value).") ";
900 } else {
901 if ( $mode == LIST_AND || $mode == LIST_SET ) {
902 $list .= $field.'=';
904 $list .= ($mode==LIST_NAMES?$value:$this->addQuotes( $value ));
907 return $list;
911 * Change the current database
913 function selectDB( $db ) {
914 $this->mDBname = $db;
915 return mysql_select_db( $db, $this->mConn );
919 * Starts a timer which will kill the DB thread after $timeout seconds
921 function startTimer( $timeout ) {
922 global $IP;
923 if( function_exists( 'mysql_thread_id' ) ) {
924 # This will kill the query if it's still running after $timeout seconds.
925 $tid = mysql_thread_id( $this->mConn );
926 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
931 * Stop a timer started by startTimer()
932 * Currently unimplemented.
935 function stopTimer() { }
938 * Format a table name ready for use in constructing an SQL query
940 * This does two important things: it quotes table names which as necessary,
941 * and it adds a table prefix if there is one.
943 * All functions of this object which require a table name call this function
944 * themselves. Pass the canonical name to such functions. This is only needed
945 * when calling query() directly.
947 * @param string $name database table name
949 function tableName( $name ) {
950 global $wgSharedDB;
951 if ( $this->mTablePrefix !== '' ) {
952 if ( strpos( '.', $name ) === false ) {
953 $name = $this->mTablePrefix . $name;
956 if ( isset( $wgSharedDB ) && 'user' == $name ) {
957 $name = $wgSharedDB . '.' . $name;
959 if( $name == 'group' ) {
960 $name = '`' . $name . '`';
962 return $name;
966 * Fetch a number of table names into an array
967 * This is handy when you need to construct SQL for joins
969 * Example:
970 * extract($dbr->tableNames('user','watchlist'));
971 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
972 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
974 function tableNames() {
975 $inArray = func_get_args();
976 $retVal = array();
977 foreach ( $inArray as $name ) {
978 $retVal[$name] = $this->tableName( $name );
980 return $retVal;
984 * Wrapper for addslashes()
985 * @param string $s String to be slashed.
986 * @return string slashed string.
988 function strencode( $s ) {
989 return addslashes( $s );
993 * If it's a string, adds quotes and backslashes
994 * Otherwise returns as-is
996 function addQuotes( $s ) {
997 if ( is_null( $s ) ) {
998 $s = 'NULL';
999 } else {
1000 # This will also quote numeric values. This should be harmless,
1001 # and protects against weird problems that occur when they really
1002 # _are_ strings such as article titles and string->number->string
1003 # conversion is not 1:1.
1004 $s = "'" . $this->strencode( $s ) . "'";
1006 return $s;
1010 * Returns an appropriately quoted sequence value for inserting a new row.
1011 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1012 * subclass will return an integer, and save the value for insertId()
1014 function nextSequenceValue( $seqName ) {
1015 return NULL;
1019 * USE INDEX clause
1020 * PostgreSQL doesn't have them and returns ""
1022 function useIndexClause( $index ) {
1023 return 'USE INDEX ('.$index.')';
1027 * REPLACE query wrapper
1028 * PostgreSQL simulates this with a DELETE followed by INSERT
1029 * $row is the row to insert, an associative array
1030 * $uniqueIndexes is an array of indexes. Each element may be either a
1031 * field name or an array of field names
1033 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1034 * However if you do this, you run the risk of encountering errors which wouldn't have
1035 * occurred in MySQL
1037 * @todo migrate comment to phodocumentor format
1039 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1040 $table = $this->tableName( $table );
1042 # Single row case
1043 if ( !is_array( reset( $rows ) ) ) {
1044 $rows = array( $rows );
1047 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1048 $first = true;
1049 foreach ( $rows as $row ) {
1050 if ( $first ) {
1051 $first = false;
1052 } else {
1053 $sql .= ',';
1055 $sql .= '(' . $this->makeList( $row ) . ')';
1057 return $this->query( $sql, $fname );
1061 * DELETE where the condition is a join
1062 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1064 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1065 * join condition matches, set $conds='*'
1067 * DO NOT put the join condition in $conds
1069 * @param string $delTable The table to delete from.
1070 * @param string $joinTable The other table.
1071 * @param string $delVar The variable to join on, in the first table.
1072 * @param string $joinVar The variable to join on, in the second table.
1073 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1075 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1076 if ( !$conds ) {
1077 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1080 $delTable = $this->tableName( $delTable );
1081 $joinTable = $this->tableName( $joinTable );
1082 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1083 if ( $conds != '*' ) {
1084 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1087 return $this->query( $sql, $fname );
1091 * Returns the size of a text field, or -1 for "unlimited"
1093 function textFieldSize( $table, $field ) {
1094 $table = $this->tableName( $table );
1095 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1096 $res = $this->query( $sql, 'Database::textFieldSize' );
1097 $row = $this->fetchObject( $res );
1098 $this->freeResult( $res );
1100 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1101 $size = $m[1];
1102 } else {
1103 $size = -1;
1105 return $size;
1109 * @return string Always return 'LOW_PRIORITY'
1111 function lowPriorityOption() {
1112 return 'LOW_PRIORITY';
1116 * DELETE query wrapper
1118 * Use $conds == "*" to delete all rows
1120 function delete( $table, $conds, $fname = 'Database::delete' ) {
1121 if ( !$conds ) {
1122 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1124 $table = $this->tableName( $table );
1125 $sql = "DELETE FROM $table ";
1126 if ( $conds != '*' ) {
1127 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
1129 return $this->query( $sql, $fname );
1133 * INSERT SELECT wrapper
1134 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1135 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1136 * $conds may be "*" to copy the whole table
1138 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1139 $destTable = $this->tableName( $destTable );
1140 $srcTable = $this->tableName( $srcTable );
1141 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1142 ' SELECT ' . implode( ',', $varMap ) .
1143 " FROM $srcTable";
1144 if ( $conds != '*' ) {
1145 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1147 return $this->query( $sql, $fname );
1151 * Construct a LIMIT query with optional offset
1152 * This is used for query pages
1154 function limitResult($limit,$offset) {
1155 return ' LIMIT '.(is_numeric($offset)?"{$offset},":"")."{$limit} ";
1159 * Returns an SQL expression for a simple conditional.
1160 * Uses IF on MySQL.
1162 * @param string $cond SQL expression which will result in a boolean value
1163 * @param string $trueVal SQL expression to return if true
1164 * @param string $falseVal SQL expression to return if false
1165 * @return string SQL fragment
1167 function conditional( $cond, $trueVal, $falseVal ) {
1168 return " IF($cond, $trueVal, $falseVal) ";
1172 * Determines if the last failure was due to a deadlock
1174 function wasDeadlock() {
1175 return $this->lastErrno() == 1213;
1179 * Perform a deadlock-prone transaction.
1181 * This function invokes a callback function to perform a set of write
1182 * queries. If a deadlock occurs during the processing, the transaction
1183 * will be rolled back and the callback function will be called again.
1185 * Usage:
1186 * $dbw->deadlockLoop( callback, ... );
1188 * Extra arguments are passed through to the specified callback function.
1190 * Returns whatever the callback function returned on its successful,
1191 * iteration, or false on error, for example if the retry limit was
1192 * reached.
1194 function deadlockLoop() {
1195 $myFname = 'Database::deadlockLoop';
1197 $this->query( 'BEGIN', $myFname );
1198 $args = func_get_args();
1199 $function = array_shift( $args );
1200 $oldIgnore = $dbw->ignoreErrors( true );
1201 $tries = DEADLOCK_TRIES;
1202 if ( is_array( $function ) ) {
1203 $fname = $function[0];
1204 } else {
1205 $fname = $function;
1207 do {
1208 $retVal = call_user_func_array( $function, $args );
1209 $error = $this->lastError();
1210 $errno = $this->lastErrno();
1211 $sql = $this->lastQuery();
1213 if ( $errno ) {
1214 if ( $dbw->wasDeadlock() ) {
1215 # Retry
1216 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1217 } else {
1218 $dbw->reportQueryError( $error, $errno, $sql, $fname );
1221 } while( $dbw->wasDeadlock && --$tries > 0 );
1222 $this->ignoreErrors( $oldIgnore );
1223 if ( $tries <= 0 ) {
1224 $this->query( 'ROLLBACK', $myFname );
1225 $this->reportQueryError( $error, $errno, $sql, $fname );
1226 return false;
1227 } else {
1228 $this->query( 'COMMIT', $myFname );
1229 return $retVal;
1234 * Do a SELECT MASTER_POS_WAIT()
1236 * @param string $file the binlog file
1237 * @param string $pos the binlog position
1238 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1240 function masterPosWait( $file, $pos, $timeout ) {
1241 $encFile = $this->strencode( $file );
1242 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1243 $res = $this->query( $sql, 'Database::masterPosWait' );
1244 if ( $res && $row = $this->fetchRow( $res ) ) {
1245 $this->freeResult( $res );
1246 return $row[0];
1247 } else {
1248 return false;
1253 * Get the position of the master from SHOW SLAVE STATUS
1255 function getSlavePos() {
1256 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1257 $row = $this->fetchObject( $res );
1258 if ( $row ) {
1259 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1260 } else {
1261 return array( false, false );
1266 * Get the position of the master from SHOW MASTER STATUS
1268 function getMasterPos() {
1269 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1270 $row = $this->fetchObject( $res );
1271 if ( $row ) {
1272 return array( $row->File, $row->Position );
1273 } else {
1274 return array( false, false );
1279 * Begin a transaction, or if a transaction has already started, continue it
1281 function begin( $fname = 'Database::begin' ) {
1282 if ( !$this->mTrxLevel ) {
1283 $this->immediateBegin( $fname );
1284 } else {
1285 $this->mTrxLevel++;
1290 * End a transaction, or decrement the nest level if transactions are nested
1292 function commit( $fname = 'Database::commit' ) {
1293 if ( $this->mTrxLevel ) {
1294 $this->mTrxLevel--;
1296 if ( !$this->mTrxLevel ) {
1297 $this->immediateCommit( $fname );
1302 * Rollback a transaction
1304 function rollback( $fname = 'Database::rollback' ) {
1305 $this->query( 'ROLLBACK', $fname );
1306 $this->mTrxLevel = 0;
1310 * Begin a transaction, committing any previously open transaction
1312 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1313 $this->query( 'BEGIN', $fname );
1314 $this->mTrxLevel = 1;
1318 * Commit transaction, if one is open
1320 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1321 $this->query( 'COMMIT', $fname );
1322 $this->mTrxLevel = 0;
1326 * Return MW-style timestamp used for MySQL schema
1328 function timestamp( $ts=0 ) {
1329 return wfTimestamp(TS_MW,$ts);
1333 * @todo document
1335 function &resultObject( &$result ) {
1336 if( empty( $result ) ) {
1337 return NULL;
1338 } else {
1339 return new ResultWrapper( $this, $result );
1344 * Return aggregated value alias
1346 function aggregateValue ($valuedata,$valuename='value') {
1347 return $valuename;
1351 * @return string wikitext of a link to the server software's web site
1353 function getSoftwareLink() {
1354 return "[http://www.mysql.com/ MySQL]";
1358 * @return string Version information from the database
1360 function getServerVersion() {
1361 return mysql_get_server_info();
1366 * Database abstraction object for mySQL
1367 * Inherit all methods and properties of Database::Database()
1369 * @package MediaWiki
1370 * @see Database
1371 * @version # $Id$
1373 class DatabaseMysql extends Database {
1374 # Inherit all
1379 * Result wrapper for grabbing data queried by someone else
1381 * @package MediaWiki
1382 * @version # $Id$
1384 class ResultWrapper {
1385 var $db, $result;
1388 * @todo document
1390 function ResultWrapper( $database, $result ) {
1391 $this->db =& $database;
1392 $this->result =& $result;
1396 * @todo document
1398 function numRows() {
1399 return $this->db->numRows( $this->result );
1403 * @todo document
1405 function &fetchObject() {
1406 return $this->db->fetchObject( $this->result );
1410 * @todo document
1412 function &fetchRow() {
1413 return $this->db->fetchRow( $this->result );
1417 * @todo document
1419 function free() {
1420 $this->db->freeResult( $this->result );
1421 unset( $this->result );
1422 unset( $this->db );
1426 #------------------------------------------------------------------------------
1427 # Global functions
1428 #------------------------------------------------------------------------------
1431 * Standard fail function, called by default when a connection cannot be
1432 * established.
1433 * Displays the file cache if possible
1435 function wfEmergencyAbort( &$conn, $error ) {
1436 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
1438 if( !headers_sent() ) {
1439 header( 'HTTP/1.0 500 Internal Server Error' );
1440 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1441 /* Don't cache error pages! They cause no end of trouble... */
1442 header( 'Cache-control: none' );
1443 header( 'Pragma: nocache' );
1445 $msg = $wgSiteNotice;
1446 if($msg == '') $msg = wfMsgNoDB( 'noconnect', $error );
1447 $text = $msg;
1449 if($wgUseFileCache) {
1450 if($wgTitle) {
1451 $t =& $wgTitle;
1452 } else {
1453 if($title) {
1454 $t = Title::newFromURL( $title );
1455 } elseif (@/**/$_REQUEST['search']) {
1456 $search = $_REQUEST['search'];
1457 echo wfMsgNoDB( 'searchdisabled' );
1458 echo wfMsgNoDB( 'googlesearch', htmlspecialchars( $search ), $wgInputEncoding );
1459 wfErrorExit();
1460 } else {
1461 $t = Title::newFromText( wfMsgNoDBForContent( 'mainpage' ) );
1465 $cache = new CacheManager( $t );
1466 if( $cache->isFileCached() ) {
1467 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1468 wfMsgNoDB( 'cachederror' ) . "</b></p>\n";
1470 $tag = '<div id="article">';
1471 $text = str_replace(
1472 $tag,
1473 $tag . $msg,
1474 $cache->fetchPageText() );
1478 echo $text;
1479 wfErrorExit();