tyop in mrakup
[mediawiki.git] / includes / Database.php
blob375756facf7666a9207ca2e56687aa5bfb40d1e3
1 <?php
2 /**
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
5 * @package MediaWiki
6 */
8 /**
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 );
26 /**
27 * Database abstraction object
28 * @package MediaWiki
30 class Database {
32 #------------------------------------------------------------------------------
33 # Variables
34 #------------------------------------------------------------------------------
35 /**#@+
36 * @access private
38 var $mLastQuery = '';
40 var $mServer, $mUser, $mPassword, $mConn, $mDBname;
41 var $mOut, $mOpened = false;
43 var $mFailFunction;
44 var $mTablePrefix;
45 var $mFlags;
46 var $mTrxLevel = 0;
47 var $mErrorCount = 0;
48 /**#@-*/
50 #------------------------------------------------------------------------------
51 # Accessors
52 #------------------------------------------------------------------------------
53 # These optionally set a variable and return the previous state
55 /**
56 * Fail function, takes a Database as a parameter
57 * Set to false for default, 1 for ignore errors
59 function failFunction( $function = NULL ) {
60 return wfSetVar( $this->mFailFunction, $function );
63 /**
64 * Output page, used for reporting errors
65 * FALSE means discard output
67 function &setOutputPage( &$out ) {
68 $this->mOut =& $out;
71 /**
72 * Boolean, controls output of large amounts of debug information
74 function debug( $debug = NULL ) {
75 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
78 /**
79 * Turns buffering of SQL result sets on (true) or off (false).
80 * Default is "on" and it should not be changed without good reasons.
82 function bufferResults( $buffer = NULL ) {
83 if ( is_null( $buffer ) ) {
84 return !(bool)( $this->mFlags & DBO_NOBUFFER );
85 } else {
86 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
90 /**
91 * Turns on (false) or off (true) the automatic generation and sending
92 * of a "we're sorry, but there has been a database error" page on
93 * database errors. Default is on (false). When turned off, the
94 * code should use wfLastErrno() and wfLastError() to handle the
95 * situation as appropriate.
97 function ignoreErrors( $ignoreErrors = NULL ) {
98 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
102 * The current depth of nested transactions
103 * @param integer $level
105 function trxLevel( $level = NULL ) {
106 return wfSetVar( $this->mTrxLevel, $level );
109 /**
110 * Number of errors logged, only useful when errors are ignored
112 function errorCount( $count = NULL ) {
113 return wfSetVar( $this->mErrorCount, $count );
116 /**#@+
117 * Get function
119 function lastQuery() { return $this->mLastQuery; }
120 function isOpen() { return $this->mOpened; }
121 /**#@-*/
123 #------------------------------------------------------------------------------
124 # Other functions
125 #------------------------------------------------------------------------------
127 /**#@+
128 * @param string $server database server host
129 * @param string $user database user name
130 * @param string $password database user password
131 * @param string $dbname database name
135 * @param failFunction
136 * @param $flags
137 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
139 function Database( $server = false, $user = false, $password = false, $dbName = false,
140 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
142 global $wgOut, $wgDBprefix, $wgCommandLineMode;
143 # Can't get a reference if it hasn't been set yet
144 if ( !isset( $wgOut ) ) {
145 $wgOut = NULL;
147 $this->mOut =& $wgOut;
149 $this->mFailFunction = $failFunction;
150 $this->mFlags = $flags;
152 if ( $this->mFlags & DBO_DEFAULT ) {
153 if ( $wgCommandLineMode ) {
154 $this->mFlags &= ~DBO_TRX;
155 } else {
156 $this->mFlags |= DBO_TRX;
161 // Faster read-only access
162 if ( wfReadOnly() ) {
163 $this->mFlags |= DBO_PERSISTENT;
164 $this->mFlags &= ~DBO_TRX;
167 /** Get the default table prefix*/
168 if ( $tablePrefix == 'get from global' ) {
169 $this->mTablePrefix = $wgDBprefix;
170 } else {
171 $this->mTablePrefix = $tablePrefix;
174 if ( $server ) {
175 $this->open( $server, $user, $password, $dbName );
180 * @static
181 * @param failFunction
182 * @param $flags
184 function newFromParams( $server, $user, $password, $dbName,
185 $failFunction = false, $flags = 0 )
187 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
191 * Usually aborts on failure
192 * If the failFunction is set to a non-zero integer, returns success
194 function open( $server, $user, $password, $dbName ) {
195 # Test for missing mysql.so
196 # First try to load it
197 if (!@extension_loaded('mysql')) {
198 @dl('mysql.so');
201 # Otherwise we get a suppressed fatal error, which is very hard to track down
202 if ( !function_exists( 'mysql_connect' ) ) {
203 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
206 $this->close();
207 $this->mServer = $server;
208 $this->mUser = $user;
209 $this->mPassword = $password;
210 $this->mDBname = $dbName;
212 $success = false;
214 if ( $this->mFlags & DBO_PERSISTENT ) {
215 @/**/$this->mConn = mysql_pconnect( $server, $user, $password );
216 } else {
217 # Create a new connection...
218 @/**/$this->mConn = mysql_connect( $server, $user, $password, true );
221 if ( $dbName != '' ) {
222 if ( $this->mConn !== false ) {
223 $success = @/**/mysql_select_db( $dbName, $this->mConn );
224 if ( !$success ) {
225 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
227 } else {
228 wfDebug( "DB connection error\n" );
229 wfDebug( "Server: $server, User: $user, Password: " .
230 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
231 $success = false;
233 } else {
234 # Delay USE query
235 $success = (bool)$this->mConn;
238 if ( !$success ) {
239 $this->reportConnectionError();
240 $this->close();
242 $this->mOpened = $success;
243 return $success;
245 /**#@-*/
248 * Closes a database connection.
249 * if it is open : commits any open transactions
251 * @return bool operation success. true if already closed.
253 function close()
255 $this->mOpened = false;
256 if ( $this->mConn ) {
257 if ( $this->trxLevel() ) {
258 $this->immediateCommit();
260 return mysql_close( $this->mConn );
261 } else {
262 return true;
267 * @access private
268 * @param string $msg error message ?
269 * @todo parameter $msg is not used
271 function reportConnectionError( $msg = '') {
272 if ( $this->mFailFunction ) {
273 if ( !is_int( $this->mFailFunction ) ) {
274 $ff = $this->mFailFunction;
275 $ff( $this, mysql_error() );
277 } else {
278 wfEmergencyAbort( $this, mysql_error() );
283 * Usually aborts on failure
284 * If errors are explicitly ignored, returns success
286 function query( $sql, $fname = '', $tempIgnore = false ) {
287 global $wgProfiling, $wgCommandLineMode;
289 if ( wfReadOnly() ) {
290 # This is a quick check for the most common kinds of write query used
291 # in MediaWiki, to provide extra safety in addition to UI-level checks.
292 # It is not intended to prevent every conceivable write query, or even
293 # to handle such queries gracefully.
294 if ( preg_match( '/^(update|insert|replace|delete)/i', $sql ) ) {
295 wfDebug( "Write query from $fname blocked\n" );
296 return false;
300 if ( $wgProfiling ) {
301 # generalizeSQL will probably cut down the query to reasonable
302 # logging size most of the time. The substr is really just a sanity check.
303 $profName = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
304 wfProfileIn( 'Database::query' );
305 wfProfileIn( $profName );
308 $this->mLastQuery = $sql;
310 # Add a comment for easy SHOW PROCESSLIST interpretation
311 if ( $fname ) {
312 $commentedSql = "/* $fname */ $sql";
313 } else {
314 $commentedSql = $sql;
317 # If DBO_TRX is set, start a transaction
318 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() && $sql != 'BEGIN' ) {
319 $this->begin();
322 if ( $this->debug() ) {
323 $sqlx = substr( $commentedSql, 0, 500 );
324 $sqlx = strtr( $sqlx, "\t\n", ' ' );
325 wfDebug( "SQL: $sqlx\n" );
328 # Do the query and handle errors
329 $ret = $this->doQuery( $commentedSql );
331 # Try reconnecting if the connection was lost
332 if ( false === $ret && ( $this->lastErrno() == 2013 || $this->lastErrno() == 2006 ) ) {
333 # Transaction is gone, like it or not
334 $this->mTrxLevel = 0;
335 wfDebug( "Connection lost, reconnecting...\n" );
336 if ( $this->ping() ) {
337 wfDebug( "Reconnected\n" );
338 $ret = $this->doQuery( $commentedSql );
339 } else {
340 wfDebug( "Failed\n" );
344 if ( false === $ret ) {
345 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
348 if ( $wgProfiling ) {
349 wfProfileOut( $profName );
350 wfProfileOut( 'Database::query' );
352 return $ret;
356 * The DBMS-dependent part of query()
357 * @param string $sql SQL query.
359 function doQuery( $sql ) {
360 if( $this->bufferResults() ) {
361 $ret = mysql_query( $sql, $this->mConn );
362 } else {
363 $ret = mysql_unbuffered_query( $sql, $this->mConn );
365 return $ret;
369 * @param $error
370 * @param $errno
371 * @param $sql
372 * @param string $fname
373 * @param bool $tempIgnore
375 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
376 global $wgCommandLineMode, $wgFullyInitialised;
377 # Ignore errors during error handling to avoid infinite recursion
378 $ignore = $this->ignoreErrors( true );
379 $this->mErrorCount ++;
381 if( $ignore || $tempIgnore ) {
382 wfDebug("SQL ERROR (ignored): " . $error . "\n");
383 } else {
384 $sql1line = str_replace( "\n", "\\n", $sql );
385 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
386 wfDebug("SQL ERROR: " . $error . "\n");
387 if ( $wgCommandLineMode || !$this->mOut || empty( $wgFullyInitialised ) ) {
388 $message = "A database error has occurred\n" .
389 "Query: $sql\n" .
390 "Function: $fname\n" .
391 "Error: $errno $error\n";
392 if ( !$wgCommandLineMode ) {
393 $message = nl2br( $message );
395 wfDebugDieBacktrace( $message );
396 } else {
397 // this calls wfAbruptExit()
398 $this->mOut->databaseError( $fname, $sql, $error, $errno );
401 $this->ignoreErrors( $ignore );
406 * Intended to be compatible with the PEAR::DB wrapper functions.
407 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
409 * ? = scalar value, quoted as necessary
410 * ! = raw SQL bit (a function for instance)
411 * & = filename; reads the file and inserts as a blob
412 * (we don't use this though...)
414 function prepare( $sql, $func = 'Database::prepare' ) {
415 /* MySQL doesn't support prepared statements (yet), so just
416 pack up the query for reference. We'll manually replace
417 the bits later. */
418 return array( 'query' => $sql, 'func' => $func );
421 function freePrepared( $prepared ) {
422 /* No-op for MySQL */
426 * Execute a prepared query with the various arguments
427 * @param string $prepared the prepared sql
428 * @param mixed $args Either an array here, or put scalars as varargs
430 function execute( $prepared, $args = null ) {
431 if( !is_array( $args ) ) {
432 # Pull the var args
433 $args = func_get_args();
434 array_shift( $args );
436 $sql = $this->fillPrepared( $prepared['query'], $args );
437 return $this->query( $sql, $prepared['func'] );
441 * Prepare & execute an SQL statement, quoting and inserting arguments
442 * in the appropriate places.
443 * @param string $query
444 * @param string $args ...
446 function safeQuery( $query, $args = null ) {
447 $prepared = $this->prepare( $query, 'Database::safeQuery' );
448 if( !is_array( $args ) ) {
449 # Pull the var args
450 $args = func_get_args();
451 array_shift( $args );
453 $retval = $this->execute( $prepared, $args );
454 $this->freePrepared( $prepared );
455 return $retval;
459 * For faking prepared SQL statements on DBs that don't support
460 * it directly.
461 * @param string $preparedSql - a 'preparable' SQL statement
462 * @param array $args - array of arguments to fill it with
463 * @return string executable SQL
465 function fillPrepared( $preparedQuery, $args ) {
466 $n = 0;
467 reset( $args );
468 $this->preparedArgs =& $args;
469 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
470 array( &$this, 'fillPreparedArg' ), $preparedQuery );
474 * preg_callback func for fillPrepared()
475 * The arguments should be in $this->preparedArgs and must not be touched
476 * while we're doing this.
478 * @param array $matches
479 * @return string
480 * @access private
482 function fillPreparedArg( $matches ) {
483 switch( $matches[1] ) {
484 case '\\?': return '?';
485 case '\\!': return '!';
486 case '\\&': return '&';
488 list( $n, $arg ) = each( $this->preparedArgs );
489 switch( $matches[1] ) {
490 case '?': return $this->addQuotes( $arg );
491 case '!': return $arg;
492 case '&':
493 # return $this->addQuotes( file_get_contents( $arg ) );
494 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
495 default:
496 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
500 /**#@+
501 * @param mixed $res A SQL result
504 * Free a result object
506 function freeResult( $res ) {
507 if ( !@/**/mysql_free_result( $res ) ) {
508 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
513 * Fetch the next row from the given result object, in object form
515 function fetchObject( $res ) {
516 @/**/$row = mysql_fetch_object( $res );
517 if( mysql_errno() ) {
518 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
520 return $row;
524 * Fetch the next row from the given result object
525 * Returns an array
527 function fetchRow( $res ) {
528 @/**/$row = mysql_fetch_array( $res );
529 if (mysql_errno() ) {
530 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
532 return $row;
536 * Get the number of rows in a result object
538 function numRows( $res ) {
539 @/**/$n = mysql_num_rows( $res );
540 if( mysql_errno() ) {
541 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
543 return $n;
547 * Get the number of fields in a result object
548 * See documentation for mysql_num_fields()
550 function numFields( $res ) { return mysql_num_fields( $res ); }
553 * Get a field name in a result object
554 * See documentation for mysql_field_name()
556 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
559 * Get the inserted value of an auto-increment row
561 * The value inserted should be fetched from nextSequenceValue()
563 * Example:
564 * $id = $dbw->nextSequenceValue('page_page_id_seq');
565 * $dbw->insert('page',array('page_id' => $id));
566 * $id = $dbw->insertId();
568 function insertId() { return mysql_insert_id( $this->mConn ); }
571 * Change the position of the cursor in a result object
572 * See mysql_data_seek()
574 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
577 * Get the last error number
578 * See mysql_errno()
580 function lastErrno() {
581 if ( $this->mConn ) {
582 return mysql_errno( $this->mConn );
583 } else {
584 return mysql_errno();
589 * Get a description of the last error
590 * See mysql_error() for more details
592 function lastError() {
593 if ( $this->mConn ) {
594 $error = mysql_error( $this->mConn );
595 } else {
596 $error = mysql_error();
598 if( $error ) {
599 $error .= ' (' . $this->mServer . ')';
601 return $error;
604 * Get the number of rows affected by the last write query
605 * See mysql_affected_rows() for more details
607 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
608 /**#@-*/ // end of template : @param $result
611 * Simple UPDATE wrapper
612 * Usually aborts on failure
613 * If errors are explicitly ignored, returns success
615 * This function exists for historical reasons, Database::update() has a more standard
616 * calling convention and feature set
618 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
620 $table = $this->tableName( $table );
621 $sql = "UPDATE $table SET $var = '" .
622 $this->strencode( $value ) . "' WHERE ($cond)";
623 return (bool)$this->query( $sql, DB_MASTER, $fname );
627 * Simple SELECT wrapper, returns a single field, input must be encoded
628 * Usually aborts on failure
629 * If errors are explicitly ignored, returns FALSE on failure
631 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
632 if ( !is_array( $options ) ) {
633 $options = array( $options );
635 $options['LIMIT'] = 1;
637 $res = $this->select( $table, $var, $cond, $fname, $options );
638 if ( $res === false || !$this->numRows( $res ) ) {
639 return false;
641 $row = $this->fetchRow( $res );
642 if ( $row !== false ) {
643 $this->freeResult( $res );
644 return $row[0];
645 } else {
646 return false;
651 * Returns an optional USE INDEX clause to go after the table, and a
652 * string to go at the end of the query
654 * @access private
656 * @param array $options an associative array of options to be turned into
657 * an SQL query, valid keys are listed in the function.
658 * @return array
660 function makeSelectOptions( $options ) {
661 $tailOpts = '';
663 if ( isset( $options['ORDER BY'] ) ) {
664 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
666 if ( isset( $options['LIMIT'] ) ) {
667 $tailOpts .= " LIMIT {$options['LIMIT']}";
670 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
671 $tailOpts .= ' FOR UPDATE';
674 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
675 $tailOpts .= ' LOCK IN SHARE MODE';
678 if ( isset( $options['USE INDEX'] ) ) {
679 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
680 } else {
681 $useIndex = '';
683 return array( $useIndex, $tailOpts );
687 * SELECT wrapper
689 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
691 if( is_array( $vars ) ) {
692 $vars = implode( ',', $vars );
694 if( is_array( $table ) ) {
695 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
696 } elseif ($table!='') {
697 $from = ' FROM ' .$this->tableName( $table );
698 } else {
699 $from = '';
702 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( (array)$options );
704 if( !empty( $conds ) ) {
705 if ( is_array( $conds ) ) {
706 $conds = $this->makeList( $conds, LIST_AND );
708 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
709 } else {
710 $sql = "SELECT $vars $from $useIndex $tailOpts";
712 return $this->query( $sql, $fname );
716 * Single row SELECT wrapper
717 * Aborts or returns FALSE on error
719 * $vars: the selected variables
720 * $conds: a condition map, terms are ANDed together.
721 * Items with numeric keys are taken to be literal conditions
722 * Takes an array of selected variables, and a condition map, which is ANDed
723 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
724 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
725 * $obj- >page_id is the ID of the Astronomy article
727 * @todo migrate documentation to phpdocumentor format
729 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
730 $options['LIMIT'] = 1;
731 $res = $this->select( $table, $vars, $conds, $fname, $options );
732 if ( $res === false || !$this->numRows( $res ) ) {
733 return false;
735 $obj = $this->fetchObject( $res );
736 $this->freeResult( $res );
737 return $obj;
742 * Removes most variables from an SQL query and replaces them with X or N for numbers.
743 * It's only slightly flawed. Don't use for anything important.
745 * @param string $sql A SQL Query
746 * @static
748 function generalizeSQL( $sql ) {
749 # This does the same as the regexp below would do, but in such a way
750 # as to avoid crashing php on some large strings.
751 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
753 $sql = str_replace ( "\\\\", '', $sql);
754 $sql = str_replace ( "\\'", '', $sql);
755 $sql = str_replace ( "\\\"", '', $sql);
756 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
757 $sql = preg_replace ('/".*"/s', "'X'", $sql);
759 # All newlines, tabs, etc replaced by single space
760 $sql = preg_replace ( "/\s+/", ' ', $sql);
762 # All numbers => N
763 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
765 return $sql;
769 * Determines whether a field exists in a table
770 * Usually aborts on failure
771 * If errors are explicitly ignored, returns NULL on failure
773 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
774 $table = $this->tableName( $table );
775 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE, $fname );
776 if ( !$res ) {
777 return NULL;
780 $found = false;
782 while ( $row = $this->fetchObject( $res ) ) {
783 if ( $row->Field == $field ) {
784 $found = true;
785 break;
788 return $found;
792 * Determines whether an index exists
793 * Usually aborts on failure
794 * If errors are explicitly ignored, returns NULL on failure
796 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
797 $info = $this->indexInfo( $table, $index, $fname );
798 if ( is_null( $info ) ) {
799 return NULL;
800 } else {
801 return $info !== false;
807 * Get information about an index into an object
808 * Returns false if the index does not exist
810 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
811 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
812 # SHOW INDEX should work for 3.x and up:
813 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
814 $table = $this->tableName( $table );
815 $sql = 'SHOW INDEX FROM '.$table;
816 $res = $this->query( $sql, $fname );
817 if ( !$res ) {
818 return NULL;
821 while ( $row = $this->fetchObject( $res ) ) {
822 if ( $row->Key_name == $index ) {
823 return $row;
826 return false;
830 * Query whether a given table exists
832 function tableExists( $table ) {
833 $table = $this->tableName( $table );
834 $old = $this->ignoreErrors( true );
835 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
836 $this->ignoreErrors( $old );
837 if( $res ) {
838 $this->freeResult( $res );
839 return true;
840 } else {
841 return false;
846 * mysql_fetch_field() wrapper
847 * Returns false if the field doesn't exist
849 * @param $table
850 * @param $field
852 function fieldInfo( $table, $field ) {
853 $table = $this->tableName( $table );
854 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
855 $n = mysql_num_fields( $res );
856 for( $i = 0; $i < $n; $i++ ) {
857 $meta = mysql_fetch_field( $res, $i );
858 if( $field == $meta->name ) {
859 return $meta;
862 return false;
866 * mysql_field_type() wrapper
868 function fieldType( $res, $index ) {
869 return mysql_field_type( $res, $index );
873 * Determines if a given index is unique
875 function indexUnique( $table, $index ) {
876 $indexInfo = $this->indexInfo( $table, $index );
877 if ( !$indexInfo ) {
878 return NULL;
880 return !$indexInfo->Non_unique;
884 * INSERT wrapper, inserts an array into a table
886 * $a may be a single associative array, or an array of these with numeric keys, for
887 * multi-row insert.
889 * Usually aborts on failure
890 * If errors are explicitly ignored, returns success
892 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
893 # No rows to insert, easy just return now
894 if ( !count( $a ) ) {
895 return true;
898 $table = $this->tableName( $table );
899 if ( !is_array( $options ) ) {
900 $options = array( $options );
902 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
903 $multi = true;
904 $keys = array_keys( $a[0] );
905 } else {
906 $multi = false;
907 $keys = array_keys( $a );
910 $sql = 'INSERT ' . implode( ' ', $options ) .
911 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
913 if ( $multi ) {
914 $first = true;
915 foreach ( $a as $row ) {
916 if ( $first ) {
917 $first = false;
918 } else {
919 $sql .= ',';
921 $sql .= '(' . $this->makeList( $row ) . ')';
923 } else {
924 $sql .= '(' . $this->makeList( $a ) . ')';
926 return (bool)$this->query( $sql, $fname );
930 * UPDATE wrapper, takes a condition array and a SET array
932 function update( $table, $values, $conds, $fname = 'Database::update' ) {
933 $table = $this->tableName( $table );
934 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET );
935 if ( $conds != '*' ) {
936 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
938 $this->query( $sql, $fname );
942 * Makes a wfStrencoded list from an array
943 * $mode: LIST_COMMA - comma separated, no field names
944 * LIST_AND - ANDed WHERE clause (without the WHERE)
945 * LIST_SET - comma separated with field names, like a SET clause
946 * LIST_NAMES - comma separated field names
948 function makeList( $a, $mode = LIST_COMMA ) {
949 if ( !is_array( $a ) ) {
950 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
953 $first = true;
954 $list = '';
955 foreach ( $a as $field => $value ) {
956 if ( !$first ) {
957 if ( $mode == LIST_AND ) {
958 $list .= ' AND ';
959 } else {
960 $list .= ',';
962 } else {
963 $first = false;
965 if ( $mode == LIST_AND && is_numeric( $field ) ) {
966 $list .= "($value)";
967 } elseif ( $mode == LIST_AND && is_array ($value) ) {
968 $list .= $field." IN (".$this->makeList($value).") ";
969 } else {
970 if ( $mode == LIST_AND || $mode == LIST_SET ) {
971 $list .= $field.'=';
973 $list .= ($mode==LIST_NAMES?$value:$this->addQuotes( $value ));
976 return $list;
980 * Change the current database
982 function selectDB( $db ) {
983 $this->mDBname = $db;
984 return mysql_select_db( $db, $this->mConn );
988 * Starts a timer which will kill the DB thread after $timeout seconds
990 function startTimer( $timeout ) {
991 global $IP;
992 if( function_exists( 'mysql_thread_id' ) ) {
993 # This will kill the query if it's still running after $timeout seconds.
994 $tid = mysql_thread_id( $this->mConn );
995 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
1000 * Stop a timer started by startTimer()
1001 * Currently unimplemented.
1004 function stopTimer() { }
1007 * Format a table name ready for use in constructing an SQL query
1009 * This does two important things: it quotes table names which as necessary,
1010 * and it adds a table prefix if there is one.
1012 * All functions of this object which require a table name call this function
1013 * themselves. Pass the canonical name to such functions. This is only needed
1014 * when calling query() directly.
1016 * @param string $name database table name
1018 function tableName( $name ) {
1019 global $wgSharedDB;
1020 # Skip quoted literals
1021 if ( $name{0} != '`' ) {
1022 if ( $this->mTablePrefix !== '' && strpos( '.', $name ) === false ) {
1023 $name = "{$this->mTablePrefix}$name";
1025 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1026 $name = "`$wgSharedDB`.`$name`";
1027 } else {
1028 # Standard quoting
1029 $name = "`$name`";
1032 return $name;
1036 * Fetch a number of table names into an array
1037 * This is handy when you need to construct SQL for joins
1039 * Example:
1040 * extract($dbr->tableNames('user','watchlist'));
1041 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1042 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1044 function tableNames() {
1045 $inArray = func_get_args();
1046 $retVal = array();
1047 foreach ( $inArray as $name ) {
1048 $retVal[$name] = $this->tableName( $name );
1050 return $retVal;
1054 * Wrapper for addslashes()
1055 * @param string $s String to be slashed.
1056 * @return string slashed string.
1058 function strencode( $s ) {
1059 return addslashes( $s );
1063 * If it's a string, adds quotes and backslashes
1064 * Otherwise returns as-is
1066 function addQuotes( $s ) {
1067 if ( is_null( $s ) ) {
1068 return 'NULL';
1069 } else {
1070 # This will also quote numeric values. This should be harmless,
1071 # and protects against weird problems that occur when they really
1072 # _are_ strings such as article titles and string->number->string
1073 # conversion is not 1:1.
1074 return "'" . $this->strencode( $s ) . "'";
1079 * Returns an appropriately quoted sequence value for inserting a new row.
1080 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1081 * subclass will return an integer, and save the value for insertId()
1083 function nextSequenceValue( $seqName ) {
1084 return NULL;
1088 * USE INDEX clause
1089 * PostgreSQL doesn't have them and returns ""
1091 function useIndexClause( $index ) {
1092 return "USE INDEX ($index)";
1096 * REPLACE query wrapper
1097 * PostgreSQL simulates this with a DELETE followed by INSERT
1098 * $row is the row to insert, an associative array
1099 * $uniqueIndexes is an array of indexes. Each element may be either a
1100 * field name or an array of field names
1102 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1103 * However if you do this, you run the risk of encountering errors which wouldn't have
1104 * occurred in MySQL
1106 * @todo migrate comment to phodocumentor format
1108 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1109 $table = $this->tableName( $table );
1111 # Single row case
1112 if ( !is_array( reset( $rows ) ) ) {
1113 $rows = array( $rows );
1116 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1117 $first = true;
1118 foreach ( $rows as $row ) {
1119 if ( $first ) {
1120 $first = false;
1121 } else {
1122 $sql .= ',';
1124 $sql .= '(' . $this->makeList( $row ) . ')';
1126 return $this->query( $sql, $fname );
1130 * DELETE where the condition is a join
1131 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1133 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1134 * join condition matches, set $conds='*'
1136 * DO NOT put the join condition in $conds
1138 * @param string $delTable The table to delete from.
1139 * @param string $joinTable The other table.
1140 * @param string $delVar The variable to join on, in the first table.
1141 * @param string $joinVar The variable to join on, in the second table.
1142 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1144 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1145 if ( !$conds ) {
1146 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1149 $delTable = $this->tableName( $delTable );
1150 $joinTable = $this->tableName( $joinTable );
1151 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1152 if ( $conds != '*' ) {
1153 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1156 return $this->query( $sql, $fname );
1160 * Returns the size of a text field, or -1 for "unlimited"
1162 function textFieldSize( $table, $field ) {
1163 $table = $this->tableName( $table );
1164 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1165 $res = $this->query( $sql, 'Database::textFieldSize' );
1166 $row = $this->fetchObject( $res );
1167 $this->freeResult( $res );
1169 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1170 $size = $m[1];
1171 } else {
1172 $size = -1;
1174 return $size;
1178 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1180 function lowPriorityOption() {
1181 return 'LOW_PRIORITY';
1185 * DELETE query wrapper
1187 * Use $conds == "*" to delete all rows
1189 function delete( $table, $conds, $fname = 'Database::delete' ) {
1190 if ( !$conds ) {
1191 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1193 $table = $this->tableName( $table );
1194 $sql = "DELETE FROM $table";
1195 if ( $conds != '*' ) {
1196 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1198 return $this->query( $sql, $fname );
1202 * INSERT SELECT wrapper
1203 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1204 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1205 * $conds may be "*" to copy the whole table
1206 * srcTable may be an array of tables.
1208 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1209 $destTable = $this->tableName( $destTable );
1210 if( is_array( $srcTable ) ) {
1211 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1212 } else {
1213 $srcTable = $this->tableName( $srcTable );
1215 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1216 ' SELECT ' . implode( ',', $varMap ) .
1217 " FROM $srcTable";
1218 if ( $conds != '*' ) {
1219 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1221 return $this->query( $sql, $fname );
1225 * Construct a LIMIT query with optional offset
1226 * This is used for query pages
1228 function limitResult($limit,$offset) {
1229 return ' LIMIT '.(is_numeric($offset)?"{$offset},":"")."{$limit} ";
1233 * Returns an SQL expression for a simple conditional.
1234 * Uses IF on MySQL.
1236 * @param string $cond SQL expression which will result in a boolean value
1237 * @param string $trueVal SQL expression to return if true
1238 * @param string $falseVal SQL expression to return if false
1239 * @return string SQL fragment
1241 function conditional( $cond, $trueVal, $falseVal ) {
1242 return " IF($cond, $trueVal, $falseVal) ";
1246 * Determines if the last failure was due to a deadlock
1248 function wasDeadlock() {
1249 return $this->lastErrno() == 1213;
1253 * Perform a deadlock-prone transaction.
1255 * This function invokes a callback function to perform a set of write
1256 * queries. If a deadlock occurs during the processing, the transaction
1257 * will be rolled back and the callback function will be called again.
1259 * Usage:
1260 * $dbw->deadlockLoop( callback, ... );
1262 * Extra arguments are passed through to the specified callback function.
1264 * Returns whatever the callback function returned on its successful,
1265 * iteration, or false on error, for example if the retry limit was
1266 * reached.
1268 function deadlockLoop() {
1269 $myFname = 'Database::deadlockLoop';
1271 $this->query( 'BEGIN', $myFname );
1272 $args = func_get_args();
1273 $function = array_shift( $args );
1274 $oldIgnore = $this->ignoreErrors( true );
1275 $tries = DEADLOCK_TRIES;
1276 if ( is_array( $function ) ) {
1277 $fname = $function[0];
1278 } else {
1279 $fname = $function;
1281 do {
1282 $retVal = call_user_func_array( $function, $args );
1283 $error = $this->lastError();
1284 $errno = $this->lastErrno();
1285 $sql = $this->lastQuery();
1287 if ( $errno ) {
1288 if ( $this->wasDeadlock() ) {
1289 # Retry
1290 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1291 } else {
1292 $this->reportQueryError( $error, $errno, $sql, $fname );
1295 } while( $this->wasDeadlock() && --$tries > 0 );
1296 $this->ignoreErrors( $oldIgnore );
1297 if ( $tries <= 0 ) {
1298 $this->query( 'ROLLBACK', $myFname );
1299 $this->reportQueryError( $error, $errno, $sql, $fname );
1300 return false;
1301 } else {
1302 $this->query( 'COMMIT', $myFname );
1303 return $retVal;
1308 * Do a SELECT MASTER_POS_WAIT()
1310 * @param string $file the binlog file
1311 * @param string $pos the binlog position
1312 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1314 function masterPosWait( $file, $pos, $timeout ) {
1315 $fname = 'Database::masterPosWait';
1316 wfProfileIn( $fname );
1319 # Commit any open transactions
1320 $this->immediateCommit();
1322 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1323 $encFile = $this->strencode( $file );
1324 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1325 $res = $this->doQuery( $sql );
1326 if ( $res && $row = $this->fetchRow( $res ) ) {
1327 $this->freeResult( $res );
1328 return $row[0];
1329 } else {
1330 return false;
1335 * Get the position of the master from SHOW SLAVE STATUS
1337 function getSlavePos() {
1338 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1339 $row = $this->fetchObject( $res );
1340 if ( $row ) {
1341 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1342 } else {
1343 return array( false, false );
1348 * Get the position of the master from SHOW MASTER STATUS
1350 function getMasterPos() {
1351 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1352 $row = $this->fetchObject( $res );
1353 if ( $row ) {
1354 return array( $row->File, $row->Position );
1355 } else {
1356 return array( false, false );
1361 * Begin a transaction, or if a transaction has already started, continue it
1363 function begin( $fname = 'Database::begin' ) {
1364 if ( !$this->mTrxLevel ) {
1365 $this->immediateBegin( $fname );
1366 } else {
1367 $this->mTrxLevel++;
1372 * End a transaction, or decrement the nest level if transactions are nested
1374 function commit( $fname = 'Database::commit' ) {
1375 if ( $this->mTrxLevel ) {
1376 $this->mTrxLevel--;
1378 if ( !$this->mTrxLevel ) {
1379 $this->immediateCommit( $fname );
1384 * Rollback a transaction
1386 function rollback( $fname = 'Database::rollback' ) {
1387 $this->query( 'ROLLBACK', $fname );
1388 $this->mTrxLevel = 0;
1392 * Begin a transaction, committing any previously open transaction
1394 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1395 $this->query( 'BEGIN', $fname );
1396 $this->mTrxLevel = 1;
1400 * Commit transaction, if one is open
1402 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1403 $this->query( 'COMMIT', $fname );
1404 $this->mTrxLevel = 0;
1408 * Return MW-style timestamp used for MySQL schema
1410 function timestamp( $ts=0 ) {
1411 return wfTimestamp(TS_MW,$ts);
1415 * Local database timestamp format or null
1417 function timestampOrNull( $ts = null ) {
1418 if( is_null( $ts ) ) {
1419 return null;
1420 } else {
1421 return $this->timestamp( $ts );
1426 * @todo document
1428 function &resultObject( &$result ) {
1429 if( empty( $result ) ) {
1430 return NULL;
1431 } else {
1432 return new ResultWrapper( $this, $result );
1437 * Return aggregated value alias
1439 function aggregateValue ($valuedata,$valuename='value') {
1440 return $valuename;
1444 * @return string wikitext of a link to the server software's web site
1446 function getSoftwareLink() {
1447 return "[http://www.mysql.com/ MySQL]";
1451 * @return string Version information from the database
1453 function getServerVersion() {
1454 return mysql_get_server_info();
1458 * Ping the server and try to reconnect if it there is no connection
1460 function ping() {
1461 if( function_exists( 'mysql_ping' ) ) {
1462 return mysql_ping( $this->mConn );
1463 } else {
1464 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1465 return true;
1470 * Get slave lag.
1471 * At the moment, this will only work if the DB user has the PROCESS privilege
1473 function getLag() {
1474 $res = $this->query( 'SHOW PROCESSLIST' );
1475 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1476 # dubious, but unfortunately there's no easy rigorous way
1477 $slaveThreads = 0;
1478 while ( $row = $this->fetchObject( $res ) ) {
1479 if ( $row->User == 'system user' ) {
1480 if ( ++$slaveThreads == 2 ) {
1481 # This is it, return the time
1482 return $row->Time;
1486 return false;
1490 * Get status information from SHOW STATUS in an associative array
1492 function getStatus() {
1493 $res = $this->query( 'SHOW STATUS' );
1494 $status = array();
1495 while ( $row = $this->fetchObject( $res ) ) {
1496 $status[$row->Variable_name] = $row->Value;
1498 return $status;
1503 * Database abstraction object for mySQL
1504 * Inherit all methods and properties of Database::Database()
1506 * @package MediaWiki
1507 * @see Database
1509 class DatabaseMysql extends Database {
1510 # Inherit all
1515 * Result wrapper for grabbing data queried by someone else
1517 * @package MediaWiki
1519 class ResultWrapper {
1520 var $db, $result;
1523 * @todo document
1525 function ResultWrapper( $database, $result ) {
1526 $this->db =& $database;
1527 $this->result =& $result;
1531 * @todo document
1533 function numRows() {
1534 return $this->db->numRows( $this->result );
1538 * @todo document
1540 function &fetchObject() {
1541 return $this->db->fetchObject( $this->result );
1545 * @todo document
1547 function &fetchRow() {
1548 return $this->db->fetchRow( $this->result );
1552 * @todo document
1554 function free() {
1555 $this->db->freeResult( $this->result );
1556 unset( $this->result );
1557 unset( $this->db );
1560 function seek( $row ) {
1561 $this->db->dataSeek( $this->result, $row );
1565 #------------------------------------------------------------------------------
1566 # Global functions
1567 #------------------------------------------------------------------------------
1570 * Standard fail function, called by default when a connection cannot be
1571 * established.
1572 * Displays the file cache if possible
1574 function wfEmergencyAbort( &$conn, $error ) {
1575 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1576 global $wgSitename, $wgServer;
1578 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1579 # Hard coding strings instead.
1581 $noconnect = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server. <br />
1582 $1';
1583 $mainpage = 'Main Page';
1584 $searchdisabled = <<<EOT
1585 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1586 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1587 EOT;
1589 $googlesearch = "
1590 <!-- SiteSearch Google -->
1591 <FORM method=GET action=\"http://www.google.com/search\">
1592 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1593 <A HREF=\"http://www.google.com/\">
1594 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1595 border=\"0\" ALT=\"Google\"></A>
1596 </td>
1597 <td>
1598 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1599 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1600 <font size=-1>
1601 <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 />
1602 <input type='hidden' name='ie' value='$2'>
1603 <input type='hidden' name='oe' value='$2'>
1604 </font>
1605 </td></tr></TABLE>
1606 </FORM>
1607 <!-- SiteSearch Google -->";
1608 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1611 if( !headers_sent() ) {
1612 header( 'HTTP/1.0 500 Internal Server Error' );
1613 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1614 /* Don't cache error pages! They cause no end of trouble... */
1615 header( 'Cache-control: none' );
1616 header( 'Pragma: nocache' );
1618 $msg = wfGetSiteNotice();
1619 if($msg == '') {
1620 $msg = str_replace( '$1', $error, $noconnect );
1622 $text = $msg;
1624 if($wgUseFileCache) {
1625 if($wgTitle) {
1626 $t =& $wgTitle;
1627 } else {
1628 if($title) {
1629 $t = Title::newFromURL( $title );
1630 } elseif (@/**/$_REQUEST['search']) {
1631 $search = $_REQUEST['search'];
1632 echo $searchdisabled;
1633 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1634 $wgInputEncoding ), $googlesearch );
1635 wfErrorExit();
1636 } else {
1637 $t = Title::newFromText( $mainpage );
1641 $cache = new CacheManager( $t );
1642 if( $cache->isFileCached() ) {
1643 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1644 $cachederror . "</b></p>\n";
1646 $tag = '<div id="article">';
1647 $text = str_replace(
1648 $tag,
1649 $tag . $msg,
1650 $cache->fetchPageText() );
1654 echo $text;
1655 wfErrorExit();