Full URLs are not necessary on longdesc; use short URLs like everywhere else.
[mediawiki.git] / includes / Database.php
blob75440d64fbfcc92b51dcb88d55d4973156be9a2e
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 # Otherwise we get a suppressed fatal error, which is very hard to track down
184 if ( !function_exists( 'mysql_connect' ) ) {
185 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
188 $this->close();
189 $this->mServer = $server;
190 $this->mUser = $user;
191 $this->mPassword = $password;
192 $this->mDBname = $dbName;
194 $success = false;
196 @/**/$this->mConn = mysql_connect( $server, $user, $password );
197 if ( $dbName != '' ) {
198 if ( $this->mConn !== false ) {
199 $success = @/**/mysql_select_db( $dbName, $this->mConn );
200 if ( !$success ) {
201 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
203 } else {
204 wfDebug( "DB connection error\n" );
205 wfDebug( "Server: $server, User: $user, Password: " .
206 substr( $password, 0, 3 ) . "...\n" );
207 $success = false;
209 } else {
210 # Delay USE query
211 $success = !!$this->mConn;
214 if ( !$success ) {
215 $this->reportConnectionError();
216 $this->close();
218 $this->mOpened = $success;
219 return $success;
221 /**#@-*/
224 * Closes a database connection.
225 * if it is open : commits any open transactions
227 * @return bool operation success. true if already closed.
229 function close()
231 $this->mOpened = false;
232 if ( $this->mConn ) {
233 if ( $this->trxLevel() ) {
234 $this->immediateCommit();
236 return mysql_close( $this->mConn );
237 } else {
238 return true;
243 * @access private
244 * @param string $msg error message ?
245 * @todo parameter $msg is not used
247 function reportConnectionError( $msg = '') {
248 if ( $this->mFailFunction ) {
249 if ( !is_int( $this->mFailFunction ) ) {
250 $ff = $this->mFailFunction;
251 $ff( $this, mysql_error() );
253 } else {
254 wfEmergencyAbort( $this, mysql_error() );
259 * Usually aborts on failure
260 * If errors are explicitly ignored, returns success
262 function query( $sql, $fname = '', $tempIgnore = false ) {
263 global $wgProfiling, $wgCommandLineMode;
265 if ( $wgProfiling ) {
266 # generalizeSQL will probably cut down the query to reasonable
267 # logging size most of the time. The substr is really just a sanity check.
268 $profName = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
269 wfProfileIn( $profName );
272 $this->mLastQuery = $sql;
274 if ( $this->debug() ) {
275 $sqlx = substr( $sql, 0, 500 );
276 $sqlx = wordwrap(strtr($sqlx,"\t\n",' '));
277 wfDebug( "SQL: $sqlx\n" );
279 # Add a comment for easy SHOW PROCESSLIST interpretation
280 if ( $fname ) {
281 $commentedSql = "/* $fname */ $sql";
282 } else {
283 $commentedSql = $sql;
286 # If DBO_TRX is set, start a transaction
287 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() && $sql != 'BEGIN' ) {
288 $this->begin();
291 # Do the query and handle errors
292 $ret = $this->doQuery( $commentedSql );
293 if ( false === $ret ) {
294 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
297 if ( $wgProfiling ) {
298 wfProfileOut( $profName );
300 return $ret;
304 * The DBMS-dependent part of query()
305 * @param string $sql SQL query.
307 function doQuery( $sql ) {
308 if( $this->bufferResults() ) {
309 $ret = mysql_query( $sql, $this->mConn );
310 } else {
311 $ret = mysql_unbuffered_query( $sql, $this->mConn );
313 return $ret;
317 * @param $error
318 * @param $errno
319 * @param $sql
320 * @param string $fname
321 * @param bool $tempIgnore
323 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
324 global $wgCommandLineMode, $wgFullyInitialised;
325 # Ignore errors during error handling to avoid infinite recursion
326 $ignore = $this->ignoreErrors( true );
328 if( $ignore || $tempIgnore ) {
329 wfDebug("SQL ERROR (ignored): " . $error . "\n");
330 } else {
331 $sql1line = str_replace( "\n", "\\n", $sql );
332 wfLogDBError("$fname\t$errno\t$error\t$sql1line\n");
333 wfDebug("SQL ERROR: " . $error . "\n");
334 if ( $wgCommandLineMode || !$this->mOut || empty( $wgFullyInitialised ) ) {
335 $message = "A database error has occurred\n" .
336 "Query: $sql\n" .
337 "Function: $fname\n" .
338 "Error: $errno $error\n";
339 if ( !$wgCommandLineMode ) {
340 $message = nl2br( $message );
342 wfDebugDieBacktrace( $message );
343 } else {
344 // this calls wfAbruptExit()
345 $this->mOut->databaseError( $fname, $sql, $error, $errno );
348 $this->ignoreErrors( $ignore );
353 * Intended to be compatible with the PEAR::DB wrapper functions.
354 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
356 * ? = scalar value, quoted as necessary
357 * ! = raw SQL bit (a function for instance)
358 * & = filename; reads the file and inserts as a blob
359 * (we don't use this though...)
361 function prepare( $sql, $func = 'Database::prepare' ) {
362 /* MySQL doesn't support prepared statements (yet), so just
363 pack up the query for reference. We'll manually replace
364 the bits later. */
365 return array( 'query' => $sql, 'func' => $func );
368 function freePrepared( $prepared ) {
369 /* No-op for MySQL */
373 * Execute a prepared query with the various arguments
374 * @param string $prepared the prepared sql
375 * @param mixed $args Either an array here, or put scalars as varargs
377 function execute( $prepared, $args = null ) {
378 if( !is_array( $args ) ) {
379 # Pull the var args
380 $args = func_get_args();
381 array_shift( $args );
383 $sql = $this->fillPrepared( $prepared['query'], $args );
384 return $this->query( $sql, $prepared['func'] );
388 * Prepare & execute an SQL statement, quoting and inserting arguments
389 * in the appropriate places.
390 * @param
392 function safeQuery( $query, $args = null ) {
393 $prepared = $this->prepare( $query, 'Database::safeQuery' );
394 if( !is_array( $args ) ) {
395 # Pull the var args
396 $args = func_get_args();
397 array_shift( $args );
399 $retval = $this->execute( $prepared, $args );
400 $this->freePrepared( $prepared );
401 return $retval;
405 * For faking prepared SQL statements on DBs that don't support
406 * it directly.
407 * @param string $preparedSql - a 'preparable' SQL statement
408 * @param array $args - array of arguments to fill it with
409 * @return string executable SQL
411 function fillPrepared( $preparedQuery, $args ) {
412 $n = 0;
413 reset( $args );
414 $this->preparedArgs =& $args;
415 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
416 array( &$this, 'fillPreparedArg' ), $preparedQuery );
420 * preg_callback func for fillPrepared()
421 * The arguments should be in $this->preparedArgs and must not be touched
422 * while we're doing this.
424 * @param array $matches
425 * @return string
426 * @access private
428 function fillPreparedArg( $matches ) {
429 switch( $matches[1] ) {
430 case '\\?': return '?';
431 case '\\!': return '!';
432 case '\\&': return '&';
434 list( $n, $arg ) = each( $this->preparedArgs );
435 switch( $matches[1] ) {
436 case '?': return $this->addQuotes( $arg );
437 case '!': return $arg;
438 case '&':
439 # return $this->addQuotes( file_get_contents( $arg ) );
440 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
441 default:
442 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
446 /**#@+
447 * @param mixed $res A SQL result
450 * Free a result object
452 function freeResult( $res ) {
453 if ( !@/**/mysql_free_result( $res ) ) {
454 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
459 * Fetch the next row from the given result object, in object form
461 function fetchObject( $res ) {
462 @/**/$row = mysql_fetch_object( $res );
463 if( mysql_errno() ) {
464 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
466 return $row;
470 * Fetch the next row from the given result object
471 * Returns an array
473 function fetchRow( $res ) {
474 @/**/$row = mysql_fetch_array( $res );
475 if (mysql_errno() ) {
476 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
478 return $row;
482 * Get the number of rows in a result object
484 function numRows( $res ) {
485 @/**/$n = mysql_num_rows( $res );
486 if( mysql_errno() ) {
487 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
489 return $n;
493 * Get the number of fields in a result object
494 * See documentation for mysql_num_fields()
496 function numFields( $res ) { return mysql_num_fields( $res ); }
499 * Get a field name in a result object
500 * See documentation for mysql_field_name()
502 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
505 * Get the inserted value of an auto-increment row
507 * The value inserted should be fetched from nextSequenceValue()
509 * Example:
510 * $id = $dbw->nextSequenceValue('cur_cur_id_seq');
511 * $dbw->insert('cur',array('cur_id' => $id));
512 * $id = $dbw->insertId();
514 function insertId() { return mysql_insert_id( $this->mConn ); }
517 * Change the position of the cursor in a result object
518 * See mysql_data_seek()
520 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
523 * Get the last error number
524 * See mysql_errno()
526 function lastErrno() { return mysql_errno(); }
529 * Get a description of the last error
530 * See mysql_error() for more details
532 function lastError() { return mysql_error(); }
535 * Get the number of rows affected by the last write query
536 * See mysql_affected_rows() for more details
538 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
539 /**#@-*/ // end of template : @param $result
542 * Simple UPDATE wrapper
543 * Usually aborts on failure
544 * If errors are explicitly ignored, returns success
546 * This function exists for historical reasons, Database::update() has a more standard
547 * calling convention and feature set
549 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
551 $table = $this->tableName( $table );
552 $sql = "UPDATE $table SET $var = '" .
553 $this->strencode( $value ) . "' WHERE ($cond)";
554 return !!$this->query( $sql, DB_MASTER, $fname );
558 * Simple SELECT wrapper, returns a single field, input must be encoded
559 * Usually aborts on failure
560 * If errors are explicitly ignored, returns FALSE on failure
562 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
563 if ( !is_array( $options ) ) {
564 $options = array( $options );
566 $options['LIMIT'] = 1;
568 $res = $this->select( $table, $var, $cond, $fname, $options );
569 if ( $res === false || !$this->numRows( $res ) ) {
570 return false;
572 $row = $this->fetchRow( $res );
573 if ( $row !== false ) {
574 $this->freeResult( $res );
575 return $row[0];
576 } else {
577 return false;
582 * Returns an optional USE INDEX clause to go after the table, and a
583 * string to go at the end of the query
585 function makeSelectOptions( $options ) {
586 if ( !is_array( $options ) ) {
587 $options = array( $options );
590 $tailOpts = '';
592 if ( isset( $options['ORDER BY'] ) ) {
593 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
595 if ( isset( $options['LIMIT'] ) ) {
596 $tailOpts .= " LIMIT {$options['LIMIT']}";
599 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
600 $tailOpts .= ' FOR UPDATE';
603 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
604 $tailOpts .= ' LOCK IN SHARE MODE';
607 if ( isset( $options['USE INDEX'] ) ) {
608 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
609 } else {
610 $useIndex = '';
612 return array( $useIndex, $tailOpts );
616 * SELECT wrapper
618 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
620 if ( is_array( $vars ) ) {
621 $vars = implode( ',', $vars );
623 if( is_array( $table ) ) {
624 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
625 } elseif ($table!='') {
626 $from = ' FROM ' .$this->tableName( $table );
627 } else {
628 $from = '';
631 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
633 if ( $conds !== false && $conds != '' ) {
634 if ( is_array( $conds ) ) {
635 $conds = $this->makeList( $conds, LIST_AND );
637 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
638 } else {
639 $sql = "SELECT $vars $from $useIndex $tailOpts";
641 return $this->query( $sql, $fname );
645 * Single row SELECT wrapper
646 * Aborts or returns FALSE on error
648 * $vars: the selected variables
649 * $conds: a condition map, terms are ANDed together.
650 * Items with numeric keys are taken to be literal conditions
651 * Takes an array of selected variables, and a condition map, which is ANDed
652 * e.g. selectRow( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
653 * would return an object where $obj->cur_id is the ID of the Astronomy article
655 * @todo migrate documentation to phpdocumentor format
657 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
658 $options['LIMIT'] = 1;
659 $res = $this->select( $table, $vars, $conds, $fname, $options );
660 if ( $res === false || !$this->numRows( $res ) ) {
661 return false;
663 $obj = $this->fetchObject( $res );
664 $this->freeResult( $res );
665 return $obj;
670 * Removes most variables from an SQL query and replaces them with X or N for numbers.
671 * It's only slightly flawed. Don't use for anything important.
673 * @param string $sql A SQL Query
674 * @static
676 function generalizeSQL( $sql ) {
677 # This does the same as the regexp below would do, but in such a way
678 # as to avoid crashing php on some large strings.
679 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
681 $sql = str_replace ( "\\\\", '', $sql);
682 $sql = str_replace ( "\\'", '', $sql);
683 $sql = str_replace ( "\\\"", '', $sql);
684 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
685 $sql = preg_replace ('/".*"/s', "'X'", $sql);
687 # All newlines, tabs, etc replaced by single space
688 $sql = preg_replace ( "/\s+/", ' ', $sql);
690 # All numbers => N
691 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
693 return $sql;
697 * Determines whether a field exists in a table
698 * Usually aborts on failure
699 * If errors are explicitly ignored, returns NULL on failure
701 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
702 $table = $this->tableName( $table );
703 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE, $fname );
704 if ( !$res ) {
705 return NULL;
708 $found = false;
710 while ( $row = $this->fetchObject( $res ) ) {
711 if ( $row->Field == $field ) {
712 $found = true;
713 break;
716 return $found;
720 * Determines whether an index exists
721 * Usually aborts on failure
722 * If errors are explicitly ignored, returns NULL on failure
724 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
725 $info = $this->indexInfo( $table, $index, $fname );
726 if ( is_null( $info ) ) {
727 return NULL;
728 } else {
729 return $info !== false;
735 * Get information about an index into an object
736 * Returns false if the index does not exist
738 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
739 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
740 # SHOW INDEX should work for 3.x and up:
741 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
742 $table = $this->tableName( $table );
743 $sql = 'SHOW INDEX FROM '.$table;
744 $res = $this->query( $sql, $fname );
745 if ( !$res ) {
746 return NULL;
749 while ( $row = $this->fetchObject( $res ) ) {
750 if ( $row->Key_name == $index ) {
751 return $row;
754 return false;
758 * Query whether a given table exists
760 function tableExists( $table ) {
761 $table = $this->tableName( $table );
762 $old = $this->ignoreErrors( true );
763 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
764 $this->ignoreErrors( $old );
765 if( $res ) {
766 $this->freeResult( $res );
767 return true;
768 } else {
769 return false;
774 * mysql_fetch_field() wrapper
775 * Returns false if the field doesn't exist
777 * @param $table
778 * @param $field
780 function fieldInfo( $table, $field ) {
781 $table = $this->tableName( $table );
782 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
783 $n = mysql_num_fields( $res );
784 for( $i = 0; $i < $n; $i++ ) {
785 $meta = mysql_fetch_field( $res, $i );
786 if( $field == $meta->name ) {
787 return $meta;
790 return false;
794 * mysql_field_type() wrapper
796 function fieldType( $res, $index ) {
797 return mysql_field_type( $res, $index );
801 * Determines if a given index is unique
803 function indexUnique( $table, $index ) {
804 $indexInfo = $this->indexInfo( $table, $index );
805 if ( !$indexInfo ) {
806 return NULL;
808 return !$indexInfo->Non_unique;
812 * INSERT wrapper, inserts an array into a table
814 * $a may be a single associative array, or an array of these with numeric keys, for
815 * multi-row insert.
817 * Usually aborts on failure
818 * If errors are explicitly ignored, returns success
820 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
821 # No rows to insert, easy just return now
822 if ( !count( $a ) ) {
823 return true;
826 $table = $this->tableName( $table );
827 if ( !is_array( $options ) ) {
828 $options = array( $options );
830 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
831 $multi = true;
832 $keys = array_keys( $a[0] );
833 } else {
834 $multi = false;
835 $keys = array_keys( $a );
838 $sql = 'INSERT ' . implode( ' ', $options ) .
839 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
841 if ( $multi ) {
842 $first = true;
843 foreach ( $a as $row ) {
844 if ( $first ) {
845 $first = false;
846 } else {
847 $sql .= ',';
849 $sql .= '(' . $this->makeList( $row ) . ')';
851 } else {
852 $sql .= '(' . $this->makeList( $a ) . ')';
854 return !!$this->query( $sql, $fname );
858 * UPDATE wrapper, takes a condition array and a SET array
860 function update( $table, $values, $conds, $fname = 'Database::update' ) {
861 $table = $this->tableName( $table );
862 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET );
863 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
864 $this->query( $sql, $fname );
868 * Makes a wfStrencoded list from an array
869 * $mode: LIST_COMMA - comma separated, no field names
870 * LIST_AND - ANDed WHERE clause (without the WHERE)
871 * LIST_SET - comma separated with field names, like a SET clause
872 * LIST_NAMES - comma separated field names
874 function makeList( $a, $mode = LIST_COMMA ) {
875 if ( !is_array( $a ) ) {
876 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
879 $first = true;
880 $list = '';
881 foreach ( $a as $field => $value ) {
882 if ( !$first ) {
883 if ( $mode == LIST_AND ) {
884 $list .= ' AND ';
885 } else {
886 $list .= ',';
888 } else {
889 $first = false;
891 if ( $mode == LIST_AND && is_numeric( $field ) ) {
892 $list .= "($value)";
893 } elseif ( $mode == LIST_AND && is_array ($value) ) {
894 $list .= $field." IN (".$this->makeList($value).") ";
895 } else {
896 if ( $mode == LIST_AND || $mode == LIST_SET ) {
897 $list .= $field.'=';
899 $list .= ($mode==LIST_NAMES?$value:$this->addQuotes( $value ));
902 return $list;
906 * Change the current database
908 function selectDB( $db ) {
909 $this->mDBname = $db;
910 return mysql_select_db( $db, $this->mConn );
914 * Starts a timer which will kill the DB thread after $timeout seconds
916 function startTimer( $timeout ) {
917 global $IP;
918 if( function_exists( 'mysql_thread_id' ) ) {
919 # This will kill the query if it's still running after $timeout seconds.
920 $tid = mysql_thread_id( $this->mConn );
921 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
926 * Stop a timer started by startTimer()
927 * Currently unimplemented.
930 function stopTimer() { }
933 * Format a table name ready for use in constructing an SQL query
935 * This does two important things: it quotes table names which as necessary,
936 * and it adds a table prefix if there is one.
938 * All functions of this object which require a table name call this function
939 * themselves. Pass the canonical name to such functions. This is only needed
940 * when calling query() directly.
942 * @param string $name database table name
944 function tableName( $name ) {
945 global $wgSharedDB;
946 if ( $this->mTablePrefix !== '' ) {
947 if ( strpos( '.', $name ) === false ) {
948 $name = $this->mTablePrefix . $name;
951 if ( isset( $wgSharedDB ) && 'user' == $name ) {
952 $name = $wgSharedDB . '.' . $name;
954 if( $name == 'group' ) {
955 $name = '`' . $name . '`';
957 return $name;
961 * Fetch a number of table names into an array
962 * This is handy when you need to construct SQL for joins
964 * Example:
965 * extract($dbr->tableNames('user','watchlist'));
966 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
967 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
969 function tableNames() {
970 $inArray = func_get_args();
971 $retVal = array();
972 foreach ( $inArray as $name ) {
973 $retVal[$name] = $this->tableName( $name );
975 return $retVal;
979 * Wrapper for addslashes()
980 * @param string $s String to be slashed.
981 * @return string slashed string.
983 function strencode( $s ) {
984 return addslashes( $s );
988 * If it's a string, adds quotes and backslashes
989 * Otherwise returns as-is
991 function addQuotes( $s ) {
992 if ( is_null( $s ) ) {
993 $s = 'NULL';
994 } else {
995 # This will also quote numeric values. This should be harmless,
996 # and protects against weird problems that occur when they really
997 # _are_ strings such as article titles and string->number->string
998 # conversion is not 1:1.
999 $s = "'" . $this->strencode( $s ) . "'";
1001 return $s;
1005 * Returns an appropriately quoted sequence value for inserting a new row.
1006 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1007 * subclass will return an integer, and save the value for insertId()
1009 function nextSequenceValue( $seqName ) {
1010 return NULL;
1014 * USE INDEX clause
1015 * PostgreSQL doesn't have them and returns ""
1017 function useIndexClause( $index ) {
1018 return 'USE INDEX ('.$index.')';
1022 * REPLACE query wrapper
1023 * PostgreSQL simulates this with a DELETE followed by INSERT
1024 * $row is the row to insert, an associative array
1025 * $uniqueIndexes is an array of indexes. Each element may be either a
1026 * field name or an array of field names
1028 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1029 * However if you do this, you run the risk of encountering errors which wouldn't have
1030 * occurred in MySQL
1032 * @todo migrate comment to phodocumentor format
1034 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1035 $table = $this->tableName( $table );
1037 # Single row case
1038 if ( !is_array( reset( $rows ) ) ) {
1039 $rows = array( $rows );
1042 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1043 $first = true;
1044 foreach ( $rows as $row ) {
1045 if ( $first ) {
1046 $first = false;
1047 } else {
1048 $sql .= ',';
1050 $sql .= '(' . $this->makeList( $row ) . ')';
1052 return $this->query( $sql, $fname );
1056 * DELETE where the condition is a join
1057 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1059 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1060 * join condition matches, set $conds='*'
1062 * DO NOT put the join condition in $conds
1064 * @param string $delTable The table to delete from.
1065 * @param string $joinTable The other table.
1066 * @param string $delVar The variable to join on, in the first table.
1067 * @param string $joinVar The variable to join on, in the second table.
1068 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1070 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1071 if ( !$conds ) {
1072 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1075 $delTable = $this->tableName( $delTable );
1076 $joinTable = $this->tableName( $joinTable );
1077 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1078 if ( $conds != '*' ) {
1079 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1082 return $this->query( $sql, $fname );
1086 * Returns the size of a text field, or -1 for "unlimited"
1088 function textFieldSize( $table, $field ) {
1089 $table = $this->tableName( $table );
1090 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1091 $res = $this->query( $sql, 'Database::textFieldSize' );
1092 $row = $this->fetchObject( $res );
1093 $this->freeResult( $res );
1095 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1096 $size = $m[1];
1097 } else {
1098 $size = -1;
1100 return $size;
1104 * @return string Always return 'LOW_PRIORITY'
1106 function lowPriorityOption() {
1107 return 'LOW_PRIORITY';
1111 * DELETE query wrapper
1113 * Use $conds == "*" to delete all rows
1115 function delete( $table, $conds, $fname = 'Database::delete' ) {
1116 if ( !$conds ) {
1117 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1119 $table = $this->tableName( $table );
1120 $sql = "DELETE FROM $table ";
1121 if ( $conds != '*' ) {
1122 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
1124 return $this->query( $sql, $fname );
1128 * INSERT SELECT wrapper
1129 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1130 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1131 * $conds may be "*" to copy the whole table
1133 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1134 $destTable = $this->tableName( $destTable );
1135 $srcTable = $this->tableName( $srcTable );
1136 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1137 ' SELECT ' . implode( ',', $varMap ) .
1138 " FROM $srcTable";
1139 if ( $conds != '*' ) {
1140 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1142 return $this->query( $sql, $fname );
1146 * Construct a LIMIT query with optional offset
1147 * This is used for query pages
1149 function limitResult($limit,$offset) {
1150 return ' LIMIT '.(is_numeric($offset)?"{$offset},":"")."{$limit} ";
1154 * Returns an SQL expression for a simple conditional.
1155 * Uses IF on MySQL.
1157 * @param string $cond SQL expression which will result in a boolean value
1158 * @param string $trueVal SQL expression to return if true
1159 * @param string $falseVal SQL expression to return if false
1160 * @return string SQL fragment
1162 function conditional( $cond, $trueVal, $falseVal ) {
1163 return " IF($cond, $trueVal, $falseVal) ";
1167 * Determines if the last failure was due to a deadlock
1169 function wasDeadlock() {
1170 return $this->lastErrno() == 1213;
1174 * Perform a deadlock-prone transaction.
1176 * This function invokes a callback function to perform a set of write
1177 * queries. If a deadlock occurs during the processing, the transaction
1178 * will be rolled back and the callback function will be called again.
1180 * Usage:
1181 * $dbw->deadlockLoop( callback, ... );
1183 * Extra arguments are passed through to the specified callback function.
1185 * Returns whatever the callback function returned on its successful,
1186 * iteration, or false on error, for example if the retry limit was
1187 * reached.
1189 function deadlockLoop() {
1190 $myFname = 'Database::deadlockLoop';
1192 $this->query( 'BEGIN', $myFname );
1193 $args = func_get_args();
1194 $function = array_shift( $args );
1195 $oldIgnore = $dbw->ignoreErrors( true );
1196 $tries = DEADLOCK_TRIES;
1197 if ( is_array( $function ) ) {
1198 $fname = $function[0];
1199 } else {
1200 $fname = $function;
1202 do {
1203 $retVal = call_user_func_array( $function, $args );
1204 $error = $this->lastError();
1205 $errno = $this->lastErrno();
1206 $sql = $this->lastQuery();
1208 if ( $errno ) {
1209 if ( $dbw->wasDeadlock() ) {
1210 # Retry
1211 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1212 } else {
1213 $dbw->reportQueryError( $error, $errno, $sql, $fname );
1216 } while( $dbw->wasDeadlock && --$tries > 0 );
1217 $this->ignoreErrors( $oldIgnore );
1218 if ( $tries <= 0 ) {
1219 $this->query( 'ROLLBACK', $myFname );
1220 $this->reportQueryError( $error, $errno, $sql, $fname );
1221 return false;
1222 } else {
1223 $this->query( 'COMMIT', $myFname );
1224 return $retVal;
1229 * Do a SELECT MASTER_POS_WAIT()
1231 * @param string $file the binlog file
1232 * @param string $pos the binlog position
1233 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1235 function masterPosWait( $file, $pos, $timeout ) {
1236 $encFile = $this->strencode( $file );
1237 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1238 $res = $this->query( $sql, 'Database::masterPosWait' );
1239 if ( $res && $row = $this->fetchRow( $res ) ) {
1240 $this->freeResult( $res );
1241 return $row[0];
1242 } else {
1243 return false;
1248 * Get the position of the master from SHOW SLAVE STATUS
1250 function getSlavePos() {
1251 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1252 $row = $this->fetchObject( $res );
1253 if ( $row ) {
1254 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1255 } else {
1256 return array( false, false );
1261 * Get the position of the master from SHOW MASTER STATUS
1263 function getMasterPos() {
1264 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1265 $row = $this->fetchObject( $res );
1266 if ( $row ) {
1267 return array( $row->File, $row->Position );
1268 } else {
1269 return array( false, false );
1274 * Begin a transaction, or if a transaction has already started, continue it
1276 function begin( $fname = 'Database::begin' ) {
1277 if ( !$this->mTrxLevel ) {
1278 $this->immediateBegin( $fname );
1279 } else {
1280 $this->mTrxLevel++;
1285 * End a transaction, or decrement the nest level if transactions are nested
1287 function commit( $fname = 'Database::commit' ) {
1288 if ( $this->mTrxLevel ) {
1289 $this->mTrxLevel--;
1291 if ( !$this->mTrxLevel ) {
1292 $this->immediateCommit( $fname );
1297 * Rollback a transaction
1299 function rollback( $fname = 'Database::rollback' ) {
1300 $this->query( 'ROLLBACK', $fname );
1301 $this->mTrxLevel = 0;
1305 * Begin a transaction, committing any previously open transaction
1307 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1308 $this->query( 'BEGIN', $fname );
1309 $this->mTrxLevel = 1;
1313 * Commit transaction, if one is open
1315 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1316 $this->query( 'COMMIT', $fname );
1317 $this->mTrxLevel = 0;
1321 * Return MW-style timestamp used for MySQL schema
1323 function timestamp( $ts=0 ) {
1324 return wfTimestamp(TS_MW,$ts);
1328 * @todo document
1330 function &resultObject( &$result ) {
1331 if( empty( $result ) ) {
1332 return NULL;
1333 } else {
1334 return new ResultWrapper( $this, $result );
1339 * Return aggregated value alias
1341 function aggregateValue ($valuedata,$valuename='value') {
1342 return $valuename;
1346 * @return string wikitext of a link to the server software's web site
1348 function getSoftwareLink() {
1349 return "[http://www.mysql.com/ MySQL]";
1353 * @return string Version information from the database
1355 function getServerVersion() {
1356 return mysql_get_server_info();
1361 * Database abstraction object for mySQL
1362 * Inherit all methods and properties of Database::Database()
1364 * @package MediaWiki
1365 * @see Database
1366 * @version # $Id$
1368 class DatabaseMysql extends Database {
1369 # Inherit all
1374 * Result wrapper for grabbing data queried by someone else
1376 * @package MediaWiki
1377 * @version # $Id$
1379 class ResultWrapper {
1380 var $db, $result;
1383 * @todo document
1385 function ResultWrapper( $database, $result ) {
1386 $this->db =& $database;
1387 $this->result =& $result;
1391 * @todo document
1393 function numRows() {
1394 return $this->db->numRows( $this->result );
1398 * @todo document
1400 function &fetchObject() {
1401 return $this->db->fetchObject( $this->result );
1405 * @todo document
1407 function &fetchRow() {
1408 return $this->db->fetchRow( $this->result );
1412 * @todo document
1414 function free() {
1415 $this->db->freeResult( $this->result );
1416 unset( $this->result );
1417 unset( $this->db );
1421 #------------------------------------------------------------------------------
1422 # Global functions
1423 #------------------------------------------------------------------------------
1426 * Standard fail function, called by default when a connection cannot be
1427 * established.
1428 * Displays the file cache if possible
1430 function wfEmergencyAbort( &$conn, $error ) {
1431 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
1433 if( !headers_sent() ) {
1434 header( 'HTTP/1.0 500 Internal Server Error' );
1435 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1436 /* Don't cache error pages! They cause no end of trouble... */
1437 header( 'Cache-control: none' );
1438 header( 'Pragma: nocache' );
1440 $msg = $wgSiteNotice;
1441 if($msg == '') $msg = wfMsgNoDB( 'noconnect', $error );
1442 $text = $msg;
1444 if($wgUseFileCache) {
1445 if($wgTitle) {
1446 $t =& $wgTitle;
1447 } else {
1448 if($title) {
1449 $t = Title::newFromURL( $title );
1450 } elseif (@/**/$_REQUEST['search']) {
1451 $search = $_REQUEST['search'];
1452 echo wfMsgNoDB( 'searchdisabled' );
1453 echo wfMsgNoDB( 'googlesearch', htmlspecialchars( $search ), $wgInputEncoding );
1454 wfErrorExit();
1455 } else {
1456 $t = Title::newFromText( wfMsgNoDBForContent( 'mainpage' ) );
1460 $cache = new CacheManager( $t );
1461 if( $cache->isFileCached() ) {
1462 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1463 wfMsgNoDB( 'cachederror' ) . "</b></p>\n";
1465 $tag = '<div id="article">';
1466 $text = str_replace(
1467 $tag,
1468 $tag . $msg,
1469 $cache->fetchPageText() );
1473 echo $text;
1474 wfErrorExit();