a0fce03a28a7d18b304a5eb0b5a5038fd50e7b0b
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
9 * Depends on the CacheManager
11 require_once( 'CacheManager.php' );
13 /** See Database::makeList() */
14 define( 'LIST_COMMA', 0 );
15 define( 'LIST_AND', 1 );
16 define( 'LIST_SET', 2 );
17 define( 'LIST_NAMES', 3);
18 define( 'LIST_OR', 4);
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 );
30 function DBObject($data) {
44 * Database abstraction object
49 #------------------------------------------------------------------------------
51 #------------------------------------------------------------------------------
57 var $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
58 var $mOut, $mOpened = false;
65 var $mLBInfo = array();
68 #------------------------------------------------------------------------------
70 #------------------------------------------------------------------------------
71 # These optionally set a variable and return the previous state
74 * Fail function, takes a Database as a parameter
75 * Set to false for default, 1 for ignore errors
77 function failFunction( $function = NULL ) {
78 return wfSetVar( $this->mFailFunction
, $function );
82 * Output page, used for reporting errors
83 * FALSE means discard output
85 function &setOutputPage( &$out ) {
90 * Boolean, controls output of large amounts of debug information
92 function debug( $debug = NULL ) {
93 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
97 * Turns buffering of SQL result sets on (true) or off (false).
98 * Default is "on" and it should not be changed without good reasons.
100 function bufferResults( $buffer = NULL ) {
101 if ( is_null( $buffer ) ) {
102 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
104 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
109 * Turns on (false) or off (true) the automatic generation and sending
110 * of a "we're sorry, but there has been a database error" page on
111 * database errors. Default is on (false). When turned off, the
112 * code should use wfLastErrno() and wfLastError() to handle the
113 * situation as appropriate.
115 function ignoreErrors( $ignoreErrors = NULL ) {
116 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
120 * The current depth of nested transactions
121 * @param integer $level
123 function trxLevel( $level = NULL ) {
124 return wfSetVar( $this->mTrxLevel
, $level );
128 * Number of errors logged, only useful when errors are ignored
130 function errorCount( $count = NULL ) {
131 return wfSetVar( $this->mErrorCount
, $count );
135 * Properties passed down from the server info array of the load balancer
137 function getLBInfo( $name = NULL ) {
138 if ( is_null( $name ) ) {
139 return $this->mLBInfo
;
141 if ( array_key_exists( $name, $this->mLBInfo
) ) {
142 return $this->mLBInfo
[$name];
149 function setLBInfo( $name, $value = NULL ) {
150 if ( is_null( $value ) ) {
151 $this->mLBInfo
= $name;
153 $this->mLBInfo
[$name] = $value;
160 function lastQuery() { return $this->mLastQuery
; }
161 function isOpen() { return $this->mOpened
; }
164 function setFlag( $flag ) {
165 $this->mFlags |
= $flag;
168 function clearFlag( $flag ) {
169 $this->mFlags
&= ~
$flag;
172 function getFlag( $flag ) {
173 return !!($this->mFlags
& $flag);
176 #------------------------------------------------------------------------------
178 #------------------------------------------------------------------------------
181 * @param string $server database server host
182 * @param string $user database user name
183 * @param string $password database user password
184 * @param string $dbname database name
188 * @param failFunction
190 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
192 function Database( $server = false, $user = false, $password = false, $dbName = false,
193 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
195 global $wgOut, $wgDBprefix, $wgCommandLineMode;
196 # Can't get a reference if it hasn't been set yet
197 if ( !isset( $wgOut ) ) {
200 $this->mOut
=& $wgOut;
202 $this->mFailFunction
= $failFunction;
203 $this->mFlags
= $flags;
205 if ( $this->mFlags
& DBO_DEFAULT
) {
206 if ( $wgCommandLineMode ) {
207 $this->mFlags
&= ~DBO_TRX
;
209 $this->mFlags |
= DBO_TRX
;
214 // Faster read-only access
215 if ( wfReadOnly() ) {
216 $this->mFlags |= DBO_PERSISTENT;
217 $this->mFlags &= ~DBO_TRX;
220 /** Get the default table prefix*/
221 if ( $tablePrefix == 'get from global' ) {
222 $this->mTablePrefix
= $wgDBprefix;
224 $this->mTablePrefix
= $tablePrefix;
228 $this->open( $server, $user, $password, $dbName );
234 * @param failFunction
237 function newFromParams( $server, $user, $password, $dbName,
238 $failFunction = false, $flags = 0 )
240 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
244 * Usually aborts on failure
245 * If the failFunction is set to a non-zero integer, returns success
247 function open( $server, $user, $password, $dbName ) {
250 # Test for missing mysql.so
251 # First try to load it
252 if (!@extension_loaded
('mysql')) {
256 # Otherwise we get a suppressed fatal error, which is very hard to track down
257 if ( !function_exists( 'mysql_connect' ) ) {
258 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
262 $this->mServer
= $server;
263 $this->mUser
= $user;
264 $this->mPassword
= $password;
265 $this->mDBname
= $dbName;
269 if ( $this->mFlags
& DBO_PERSISTENT
) {
270 @/**/$this->mConn
= mysql_pconnect( $server, $user, $password );
272 # Create a new connection...
273 if( version_compare( PHP_VERSION
, '4.2.0', 'ge' ) ) {
274 @/**/$this->mConn
= mysql_connect( $server, $user, $password, true );
276 # On PHP 4.1 the new_link parameter is not available. We cannot
277 # guarantee that we'll actually get a new connection, and this
278 # may cause some operations to fail possibly.
279 @/**/$this->mConn
= mysql_connect( $server, $user, $password );
283 if ( $dbName != '' ) {
284 if ( $this->mConn
!== false ) {
285 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
287 $error = "Error selecting database $dbName on server {$this->mServer} " .
288 "from client host {$wguname['nodename']}\n";
292 wfDebug( "DB connection error\n" );
293 wfDebug( "Server: $server, User: $user, Password: " .
294 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
299 $success = (bool)$this->mConn
;
303 $this->reportConnectionError();
308 // Tell the server we're communicating with it in UTF-8.
309 // This may engage various charset conversions.
310 $this->query( 'SET NAMES utf8' );
313 $this->mOpened
= $success;
319 * Closes a database connection.
320 * if it is open : commits any open transactions
322 * @return bool operation success. true if already closed.
326 $this->mOpened
= false;
327 if ( $this->mConn
) {
328 if ( $this->trxLevel() ) {
329 $this->immediateCommit();
331 return mysql_close( $this->mConn
);
339 * @param string $error fallback error message, used if none is given by MySQL
341 function reportConnectionError( $error = 'Unknown error' ) {
342 $myError = $this->lastError();
347 if ( $this->mFailFunction
) {
348 if ( !is_int( $this->mFailFunction
) ) {
349 $ff = $this->mFailFunction
;
350 $ff( $this, $error );
353 wfEmergencyAbort( $this, $error );
358 * Usually aborts on failure
359 * If errors are explicitly ignored, returns success
361 function query( $sql, $fname = '', $tempIgnore = false ) {
362 global $wgProfiling, $wgCommandLineMode;
364 if ( wfReadOnly() ) {
365 # This is a quick check for the most common kinds of write query used
366 # in MediaWiki, to provide extra safety in addition to UI-level checks.
367 # It is not intended to prevent every conceivable write query, or even
368 # to handle such queries gracefully.
369 if ( preg_match( '/^(?:update|insert|replace|delete)/i', $sql ) ) {
370 wfDebug( "Write query from $fname blocked\n" );
375 if ( $wgProfiling ) {
376 # generalizeSQL will probably cut down the query to reasonable
377 # logging size most of the time. The substr is really just a sanity check.
379 # Who's been wasting my precious column space? -- TS
380 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
381 $profName = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
383 wfProfileIn( 'Database::query' );
384 wfProfileIn( $profName );
387 $this->mLastQuery
= $sql;
389 # Add a comment for easy SHOW PROCESSLIST interpretation
391 $commentedSql = preg_replace("/\s/", " /* $fname */ ", $sql, 1);
393 $commentedSql = $sql;
396 # If DBO_TRX is set, start a transaction
397 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() && $sql != 'BEGIN' ) {
401 if ( $this->debug() ) {
402 $sqlx = substr( $commentedSql, 0, 500 );
403 $sqlx = strtr( $sqlx, "\t\n", ' ' );
404 wfDebug( "SQL: $sqlx\n" );
407 # Do the query and handle errors
408 $ret = $this->doQuery( $commentedSql );
410 # Try reconnecting if the connection was lost
411 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
412 # Transaction is gone, like it or not
413 $this->mTrxLevel
= 0;
414 wfDebug( "Connection lost, reconnecting...\n" );
415 if ( $this->ping() ) {
416 wfDebug( "Reconnected\n" );
417 $ret = $this->doQuery( $commentedSql );
419 wfDebug( "Failed\n" );
423 if ( false === $ret ) {
424 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
427 if ( $wgProfiling ) {
428 wfProfileOut( $profName );
429 wfProfileOut( 'Database::query' );
435 * The DBMS-dependent part of query()
436 * @param string $sql SQL query.
438 function doQuery( $sql ) {
439 if( $this->bufferResults() ) {
440 $ret = mysql_query( $sql, $this->mConn
);
442 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
451 * @param string $fname
452 * @param bool $tempIgnore
454 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
455 global $wgCommandLineMode, $wgFullyInitialised;
456 # Ignore errors during error handling to avoid infinite recursion
457 $ignore = $this->ignoreErrors( true );
458 ++
$this->mErrorCount
;
460 if( $ignore ||
$tempIgnore ) {
461 wfDebug("SQL ERROR (ignored): $error\n");
463 $sql1line = str_replace( "\n", "\\n", $sql );
464 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
465 wfDebug("SQL ERROR: " . $error . "\n");
466 if ( $wgCommandLineMode ||
!$this->mOut ||
empty( $wgFullyInitialised ) ) {
467 $message = "A database error has occurred\n" .
469 "Function: $fname\n" .
470 "Error: $errno $error\n";
471 if ( !$wgCommandLineMode ) {
472 $message = nl2br( $message );
474 wfDebugDieBacktrace( $message );
476 // this calls wfAbruptExit()
477 $this->mOut
->databaseError( $fname, $sql, $error, $errno );
480 $this->ignoreErrors( $ignore );
485 * Intended to be compatible with the PEAR::DB wrapper functions.
486 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
488 * ? = scalar value, quoted as necessary
489 * ! = raw SQL bit (a function for instance)
490 * & = filename; reads the file and inserts as a blob
491 * (we don't use this though...)
493 function prepare( $sql, $func = 'Database::prepare' ) {
494 /* MySQL doesn't support prepared statements (yet), so just
495 pack up the query for reference. We'll manually replace
497 return array( 'query' => $sql, 'func' => $func );
500 function freePrepared( $prepared ) {
501 /* No-op for MySQL */
505 * Execute a prepared query with the various arguments
506 * @param string $prepared the prepared sql
507 * @param mixed $args Either an array here, or put scalars as varargs
509 function execute( $prepared, $args = null ) {
510 if( !is_array( $args ) ) {
512 $args = func_get_args();
513 array_shift( $args );
515 $sql = $this->fillPrepared( $prepared['query'], $args );
516 return $this->query( $sql, $prepared['func'] );
520 * Prepare & execute an SQL statement, quoting and inserting arguments
521 * in the appropriate places.
522 * @param string $query
523 * @param string $args ...
525 function safeQuery( $query, $args = null ) {
526 $prepared = $this->prepare( $query, 'Database::safeQuery' );
527 if( !is_array( $args ) ) {
529 $args = func_get_args();
530 array_shift( $args );
532 $retval = $this->execute( $prepared, $args );
533 $this->freePrepared( $prepared );
538 * For faking prepared SQL statements on DBs that don't support
540 * @param string $preparedSql - a 'preparable' SQL statement
541 * @param array $args - array of arguments to fill it with
542 * @return string executable SQL
544 function fillPrepared( $preparedQuery, $args ) {
547 $this->preparedArgs
=& $args;
548 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
549 array( &$this, 'fillPreparedArg' ), $preparedQuery );
553 * preg_callback func for fillPrepared()
554 * The arguments should be in $this->preparedArgs and must not be touched
555 * while we're doing this.
557 * @param array $matches
561 function fillPreparedArg( $matches ) {
562 switch( $matches[1] ) {
563 case '\\?': return '?';
564 case '\\!': return '!';
565 case '\\&': return '&';
567 list( $n, $arg ) = each( $this->preparedArgs
);
568 switch( $matches[1] ) {
569 case '?': return $this->addQuotes( $arg );
570 case '!': return $arg;
572 # return $this->addQuotes( file_get_contents( $arg ) );
573 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
575 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
580 * @param mixed $res A SQL result
583 * Free a result object
585 function freeResult( $res ) {
586 if ( !@/**/mysql_free_result( $res ) ) {
587 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
592 * Fetch the next row from the given result object, in object form
594 function fetchObject( $res ) {
595 @/**/$row = mysql_fetch_object( $res );
596 if( mysql_errno() ) {
597 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
603 * Fetch the next row from the given result object
606 function fetchRow( $res ) {
607 @/**/$row = mysql_fetch_array( $res );
608 if (mysql_errno() ) {
609 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
615 * Get the number of rows in a result object
617 function numRows( $res ) {
618 @/**/$n = mysql_num_rows( $res );
619 if( mysql_errno() ) {
620 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
626 * Get the number of fields in a result object
627 * See documentation for mysql_num_fields()
629 function numFields( $res ) { return mysql_num_fields( $res ); }
632 * Get a field name in a result object
633 * See documentation for mysql_field_name()
635 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
638 * Get the inserted value of an auto-increment row
640 * The value inserted should be fetched from nextSequenceValue()
643 * $id = $dbw->nextSequenceValue('page_page_id_seq');
644 * $dbw->insert('page',array('page_id' => $id));
645 * $id = $dbw->insertId();
647 function insertId() { return mysql_insert_id( $this->mConn
); }
650 * Change the position of the cursor in a result object
651 * See mysql_data_seek()
653 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
656 * Get the last error number
659 function lastErrno() {
660 if ( $this->mConn
) {
661 return mysql_errno( $this->mConn
);
663 return mysql_errno();
668 * Get a description of the last error
669 * See mysql_error() for more details
671 function lastError() {
672 if ( $this->mConn
) {
673 # Even if it's non-zero, it can still be invalid
674 wfSuppressWarnings();
675 $error = mysql_error( $this->mConn
);
677 $error = mysql_error();
681 $error = mysql_error();
684 $error .= ' (' . $this->mServer
. ')';
689 * Get the number of rows affected by the last write query
690 * See mysql_affected_rows() for more details
692 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
693 /**#@-*/ // end of template : @param $result
696 * Simple UPDATE wrapper
697 * Usually aborts on failure
698 * If errors are explicitly ignored, returns success
700 * This function exists for historical reasons, Database::update() has a more standard
701 * calling convention and feature set
703 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
705 $table = $this->tableName( $table );
706 $sql = "UPDATE $table SET $var = '" .
707 $this->strencode( $value ) . "' WHERE ($cond)";
708 return (bool)$this->query( $sql, DB_MASTER
, $fname );
712 * Simple SELECT wrapper, returns a single field, input must be encoded
713 * Usually aborts on failure
714 * If errors are explicitly ignored, returns FALSE on failure
716 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
717 if ( !is_array( $options ) ) {
718 $options = array( $options );
720 $options['LIMIT'] = 1;
722 $res = $this->select( $table, $var, $cond, $fname, $options );
723 if ( $res === false ||
!$this->numRows( $res ) ) {
726 $row = $this->fetchRow( $res );
727 if ( $row !== false ) {
728 $this->freeResult( $res );
736 * Returns an optional USE INDEX clause to go after the table, and a
737 * string to go at the end of the query
741 * @param array $options an associative array of options to be turned into
742 * an SQL query, valid keys are listed in the function.
745 function makeSelectOptions( $options ) {
748 if ( isset( $options['GROUP BY'] ) ) {
749 $tailOpts .= " GROUP BY {$options['GROUP BY']}";
751 if ( isset( $options['ORDER BY'] ) ) {
752 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
754 if (isset($options['LIMIT'])) {
755 $tailOpts .= $this->limitResult('', $options['LIMIT'],
756 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
758 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
759 $tailOpts .= ' FOR UPDATE';
762 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
763 $tailOpts .= ' LOCK IN SHARE MODE';
766 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
767 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
771 return array( $useIndex, $tailOpts );
777 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
779 if( is_array( $vars ) ) {
780 $vars = implode( ',', $vars );
782 if( !is_array( $options ) ) {
783 $options = array( $options );
785 if( is_array( $table ) ) {
786 if ( @is_array
( $options['USE INDEX'] ) )
787 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
789 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
790 } elseif ($table!='') {
791 $from = ' FROM ' . $this->tableName( $table );
796 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
798 if( !empty( $conds ) ) {
799 if ( is_array( $conds ) ) {
800 $conds = $this->makeList( $conds, LIST_AND
);
802 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
804 $sql = "SELECT $vars $from $useIndex $tailOpts";
807 return $this->query( $sql, $fname );
811 * Single row SELECT wrapper
812 * Aborts or returns FALSE on error
814 * $vars: the selected variables
815 * $conds: a condition map, terms are ANDed together.
816 * Items with numeric keys are taken to be literal conditions
817 * Takes an array of selected variables, and a condition map, which is ANDed
818 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
819 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
820 * $obj- >page_id is the ID of the Astronomy article
822 * @todo migrate documentation to phpdocumentor format
824 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
825 $options['LIMIT'] = 1;
826 $res = $this->select( $table, $vars, $conds, $fname, $options );
827 if ( $res === false )
829 if ( !$this->numRows($res) ) {
830 $this->freeResult($res);
833 $obj = $this->fetchObject( $res );
834 $this->freeResult( $res );
840 * Removes most variables from an SQL query and replaces them with X or N for numbers.
841 * It's only slightly flawed. Don't use for anything important.
843 * @param string $sql A SQL Query
846 function generalizeSQL( $sql ) {
847 # This does the same as the regexp below would do, but in such a way
848 # as to avoid crashing php on some large strings.
849 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
851 $sql = str_replace ( "\\\\", '', $sql);
852 $sql = str_replace ( "\\'", '', $sql);
853 $sql = str_replace ( "\\\"", '', $sql);
854 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
855 $sql = preg_replace ('/".*"/s', "'X'", $sql);
857 # All newlines, tabs, etc replaced by single space
858 $sql = preg_replace ( "/\s+/", ' ', $sql);
861 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
867 * Determines whether a field exists in a table
868 * Usually aborts on failure
869 * If errors are explicitly ignored, returns NULL on failure
871 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
872 $table = $this->tableName( $table );
873 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE
, $fname );
880 while ( $row = $this->fetchObject( $res ) ) {
881 if ( $row->Field
== $field ) {
890 * Determines whether an index exists
891 * Usually aborts on failure
892 * If errors are explicitly ignored, returns NULL on failure
894 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
895 $info = $this->indexInfo( $table, $index, $fname );
896 if ( is_null( $info ) ) {
899 return $info !== false;
905 * Get information about an index into an object
906 * Returns false if the index does not exist
908 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
909 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
910 # SHOW INDEX should work for 3.x and up:
911 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
912 $table = $this->tableName( $table );
913 $sql = 'SHOW INDEX FROM '.$table;
914 $res = $this->query( $sql, $fname );
919 while ( $row = $this->fetchObject( $res ) ) {
920 if ( $row->Key_name
== $index ) {
928 * Query whether a given table exists
930 function tableExists( $table ) {
931 $table = $this->tableName( $table );
932 $old = $this->ignoreErrors( true );
933 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
934 $this->ignoreErrors( $old );
936 $this->freeResult( $res );
944 * mysql_fetch_field() wrapper
945 * Returns false if the field doesn't exist
950 function fieldInfo( $table, $field ) {
951 $table = $this->tableName( $table );
952 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
953 $n = mysql_num_fields( $res );
954 for( $i = 0; $i < $n; $i++
) {
955 $meta = mysql_fetch_field( $res, $i );
956 if( $field == $meta->name
) {
964 * mysql_field_type() wrapper
966 function fieldType( $res, $index ) {
967 return mysql_field_type( $res, $index );
971 * Determines if a given index is unique
973 function indexUnique( $table, $index ) {
974 $indexInfo = $this->indexInfo( $table, $index );
978 return !$indexInfo->Non_unique
;
982 * INSERT wrapper, inserts an array into a table
984 * $a may be a single associative array, or an array of these with numeric keys, for
987 * Usually aborts on failure
988 * If errors are explicitly ignored, returns success
990 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
991 # No rows to insert, easy just return now
992 if ( !count( $a ) ) {
996 $table = $this->tableName( $table );
997 if ( !is_array( $options ) ) {
998 $options = array( $options );
1000 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1002 $keys = array_keys( $a[0] );
1005 $keys = array_keys( $a );
1008 $sql = 'INSERT ' . implode( ' ', $options ) .
1009 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1013 foreach ( $a as $row ) {
1019 $sql .= '(' . $this->makeList( $row ) . ')';
1022 $sql .= '(' . $this->makeList( $a ) . ')';
1024 return (bool)$this->query( $sql, $fname );
1028 * Make UPDATE options for the Database::update function
1031 * @param array $options The options passed to Database::update
1034 function makeUpdateOptions( $options ) {
1035 if( !is_array( $options ) ) {
1036 $options = array( $options );
1039 if ( in_array( 'LOW_PRIORITY', $options ) )
1040 $opts[] = $this->lowPriorityOption();
1041 if ( in_array( 'IGNORE', $options ) )
1043 return implode(' ', $opts);
1047 * UPDATE wrapper, takes a condition array and a SET array
1049 * @param string $table The table to UPDATE
1050 * @param array $values An array of values to SET
1051 * @param array $conds An array of conditions (WHERE)
1052 * @param string $fname The Class::Function calling this function
1054 * @param array $options An array of UPDATE options, can be one or
1055 * more of IGNORE, LOW_PRIORITY
1057 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1058 $table = $this->tableName( $table );
1059 $opts = $this->makeUpdateOptions( $options );
1060 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1061 if ( $conds != '*' ) {
1062 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1064 $this->query( $sql, $fname );
1068 * Makes a wfStrencoded list from an array
1069 * $mode: LIST_COMMA - comma separated, no field names
1070 * LIST_AND - ANDed WHERE clause (without the WHERE)
1071 * LIST_SET - comma separated with field names, like a SET clause
1072 * LIST_NAMES - comma separated field names
1074 function makeList( $a, $mode = LIST_COMMA
) {
1075 if ( !is_array( $a ) ) {
1076 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
1081 foreach ( $a as $field => $value ) {
1083 if ( $mode == LIST_AND
) {
1085 } elseif($mode == LIST_OR
) {
1093 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1094 $list .= "($value)";
1095 } elseif ( $mode == LIST_AND
&& is_array ($value) ) {
1096 $list .= $field." IN (".$this->makeList($value).") ";
1098 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1099 $list .= "$field = ";
1101 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1108 * Change the current database
1110 function selectDB( $db ) {
1111 $this->mDBname
= $db;
1112 return mysql_select_db( $db, $this->mConn
);
1116 * Starts a timer which will kill the DB thread after $timeout seconds
1118 function startTimer( $timeout ) {
1120 if( function_exists( 'mysql_thread_id' ) ) {
1121 # This will kill the query if it's still running after $timeout seconds.
1122 $tid = mysql_thread_id( $this->mConn
);
1123 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
1128 * Stop a timer started by startTimer()
1129 * Currently unimplemented.
1132 function stopTimer() { }
1135 * Format a table name ready for use in constructing an SQL query
1137 * This does two important things: it quotes table names which as necessary,
1138 * and it adds a table prefix if there is one.
1140 * All functions of this object which require a table name call this function
1141 * themselves. Pass the canonical name to such functions. This is only needed
1142 * when calling query() directly.
1144 * @param string $name database table name
1146 function tableName( $name ) {
1148 # Skip quoted literals
1149 if ( $name{0} != '`' ) {
1150 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
1151 $name = "{$this->mTablePrefix}$name";
1153 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1154 $name = "`$wgSharedDB`.`$name`";
1164 * Fetch a number of table names into an array
1165 * This is handy when you need to construct SQL for joins
1168 * extract($dbr->tableNames('user','watchlist'));
1169 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1170 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1172 function tableNames() {
1173 $inArray = func_get_args();
1175 foreach ( $inArray as $name ) {
1176 $retVal[$name] = $this->tableName( $name );
1184 function tableNamesWithUseIndex( $tables, $use_index ) {
1187 foreach ( $tables as $table )
1188 if ( @$use_index[$table] !== null )
1189 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1191 $ret[] = $this->tableName( $table );
1193 return implode( ',', $ret );
1197 * Wrapper for addslashes()
1198 * @param string $s String to be slashed.
1199 * @return string slashed string.
1201 function strencode( $s ) {
1202 return addslashes( $s );
1206 * If it's a string, adds quotes and backslashes
1207 * Otherwise returns as-is
1209 function addQuotes( $s ) {
1210 if ( is_null( $s ) ) {
1213 # This will also quote numeric values. This should be harmless,
1214 # and protects against weird problems that occur when they really
1215 # _are_ strings such as article titles and string->number->string
1216 # conversion is not 1:1.
1217 return "'" . $this->strencode( $s ) . "'";
1222 * Escape string for safe LIKE usage
1224 function escapeLike( $s ) {
1225 $s=$this->strencode( $s );
1226 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1231 * Returns an appropriately quoted sequence value for inserting a new row.
1232 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1233 * subclass will return an integer, and save the value for insertId()
1235 function nextSequenceValue( $seqName ) {
1241 * PostgreSQL doesn't have them and returns ""
1243 function useIndexClause( $index ) {
1244 return "FORCE INDEX ($index)";
1248 * REPLACE query wrapper
1249 * PostgreSQL simulates this with a DELETE followed by INSERT
1250 * $row is the row to insert, an associative array
1251 * $uniqueIndexes is an array of indexes. Each element may be either a
1252 * field name or an array of field names
1254 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1255 * However if you do this, you run the risk of encountering errors which wouldn't have
1258 * @todo migrate comment to phodocumentor format
1260 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1261 $table = $this->tableName( $table );
1264 if ( !is_array( reset( $rows ) ) ) {
1265 $rows = array( $rows );
1268 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1270 foreach ( $rows as $row ) {
1276 $sql .= '(' . $this->makeList( $row ) . ')';
1278 return $this->query( $sql, $fname );
1282 * DELETE where the condition is a join
1283 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1285 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1286 * join condition matches, set $conds='*'
1288 * DO NOT put the join condition in $conds
1290 * @param string $delTable The table to delete from.
1291 * @param string $joinTable The other table.
1292 * @param string $delVar The variable to join on, in the first table.
1293 * @param string $joinVar The variable to join on, in the second table.
1294 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1296 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1298 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1301 $delTable = $this->tableName( $delTable );
1302 $joinTable = $this->tableName( $joinTable );
1303 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1304 if ( $conds != '*' ) {
1305 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1308 return $this->query( $sql, $fname );
1312 * Returns the size of a text field, or -1 for "unlimited"
1314 function textFieldSize( $table, $field ) {
1315 $table = $this->tableName( $table );
1316 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1317 $res = $this->query( $sql, 'Database::textFieldSize' );
1318 $row = $this->fetchObject( $res );
1319 $this->freeResult( $res );
1321 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
1330 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1332 function lowPriorityOption() {
1333 return 'LOW_PRIORITY';
1337 * DELETE query wrapper
1339 * Use $conds == "*" to delete all rows
1341 function delete( $table, $conds, $fname = 'Database::delete' ) {
1343 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1345 $table = $this->tableName( $table );
1346 $sql = "DELETE FROM $table";
1347 if ( $conds != '*' ) {
1348 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1350 return $this->query( $sql, $fname );
1354 * INSERT SELECT wrapper
1355 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1356 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1357 * $conds may be "*" to copy the whole table
1358 * srcTable may be an array of tables.
1360 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1361 $destTable = $this->tableName( $destTable );
1362 if( is_array( $srcTable ) ) {
1363 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1365 $srcTable = $this->tableName( $srcTable );
1367 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1368 ' SELECT ' . implode( ',', $varMap ) .
1370 if ( $conds != '*' ) {
1371 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1373 return $this->query( $sql, $fname );
1377 * Construct a LIMIT query with optional offset
1378 * This is used for query pages
1379 * $sql string SQL query we will append the limit too
1380 * $limit integer the SQL limit
1381 * $offset integer the SQL offset (default false)
1383 function limitResult($sql, $limit, $offset=false) {
1384 return " $sql LIMIT ".((is_numeric($offset) && $offset != 0)?
"{$offset},":"")."{$limit} ";
1386 function limitResultForUpdate($sql, $num) {
1387 return $this->limitResult($sql, $num, 0);
1391 * Returns an SQL expression for a simple conditional.
1394 * @param string $cond SQL expression which will result in a boolean value
1395 * @param string $trueVal SQL expression to return if true
1396 * @param string $falseVal SQL expression to return if false
1397 * @return string SQL fragment
1399 function conditional( $cond, $trueVal, $falseVal ) {
1400 return " IF($cond, $trueVal, $falseVal) ";
1404 * Determines if the last failure was due to a deadlock
1406 function wasDeadlock() {
1407 return $this->lastErrno() == 1213;
1411 * Perform a deadlock-prone transaction.
1413 * This function invokes a callback function to perform a set of write
1414 * queries. If a deadlock occurs during the processing, the transaction
1415 * will be rolled back and the callback function will be called again.
1418 * $dbw->deadlockLoop( callback, ... );
1420 * Extra arguments are passed through to the specified callback function.
1422 * Returns whatever the callback function returned on its successful,
1423 * iteration, or false on error, for example if the retry limit was
1426 function deadlockLoop() {
1427 $myFname = 'Database::deadlockLoop';
1430 $args = func_get_args();
1431 $function = array_shift( $args );
1432 $oldIgnore = $this->ignoreErrors( true );
1433 $tries = DEADLOCK_TRIES
;
1434 if ( is_array( $function ) ) {
1435 $fname = $function[0];
1440 $retVal = call_user_func_array( $function, $args );
1441 $error = $this->lastError();
1442 $errno = $this->lastErrno();
1443 $sql = $this->lastQuery();
1446 if ( $this->wasDeadlock() ) {
1448 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1450 $this->reportQueryError( $error, $errno, $sql, $fname );
1453 } while( $this->wasDeadlock() && --$tries > 0 );
1454 $this->ignoreErrors( $oldIgnore );
1455 if ( $tries <= 0 ) {
1456 $this->query( 'ROLLBACK', $myFname );
1457 $this->reportQueryError( $error, $errno, $sql, $fname );
1460 $this->query( 'COMMIT', $myFname );
1466 * Do a SELECT MASTER_POS_WAIT()
1468 * @param string $file the binlog file
1469 * @param string $pos the binlog position
1470 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1472 function masterPosWait( $file, $pos, $timeout ) {
1473 $fname = 'Database::masterPosWait';
1474 wfProfileIn( $fname );
1477 # Commit any open transactions
1478 $this->immediateCommit();
1480 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1481 $encFile = $this->strencode( $file );
1482 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1483 $res = $this->doQuery( $sql );
1484 if ( $res && $row = $this->fetchRow( $res ) ) {
1485 $this->freeResult( $res );
1486 wfProfileOut( $fname );
1489 wfProfileOut( $fname );
1495 * Get the position of the master from SHOW SLAVE STATUS
1497 function getSlavePos() {
1498 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1499 $row = $this->fetchObject( $res );
1501 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1503 return array( false, false );
1508 * Get the position of the master from SHOW MASTER STATUS
1510 function getMasterPos() {
1511 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1512 $row = $this->fetchObject( $res );
1514 return array( $row->File
, $row->Position
);
1516 return array( false, false );
1521 * Begin a transaction, or if a transaction has already started, continue it
1523 function begin( $fname = 'Database::begin' ) {
1524 if ( !$this->mTrxLevel
) {
1525 $this->immediateBegin( $fname );
1532 * End a transaction, or decrement the nest level if transactions are nested
1534 function commit( $fname = 'Database::commit' ) {
1535 if ( $this->mTrxLevel
) {
1538 if ( !$this->mTrxLevel
) {
1539 $this->immediateCommit( $fname );
1544 * Rollback a transaction
1546 function rollback( $fname = 'Database::rollback' ) {
1547 $this->query( 'ROLLBACK', $fname );
1548 $this->mTrxLevel
= 0;
1552 * Begin a transaction, committing any previously open transaction
1554 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1555 $this->query( 'BEGIN', $fname );
1556 $this->mTrxLevel
= 1;
1560 * Commit transaction, if one is open
1562 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1563 $this->query( 'COMMIT', $fname );
1564 $this->mTrxLevel
= 0;
1568 * Return MW-style timestamp used for MySQL schema
1570 function timestamp( $ts=0 ) {
1571 return wfTimestamp(TS_MW
,$ts);
1575 * Local database timestamp format or null
1577 function timestampOrNull( $ts = null ) {
1578 if( is_null( $ts ) ) {
1581 return $this->timestamp( $ts );
1588 function resultObject( $result ) {
1589 if( empty( $result ) ) {
1592 return new ResultWrapper( $this, $result );
1597 * Return aggregated value alias
1599 function aggregateValue ($valuedata,$valuename='value') {
1604 * @return string wikitext of a link to the server software's web site
1606 function getSoftwareLink() {
1607 return "[http://www.mysql.com/ MySQL]";
1611 * @return string Version information from the database
1613 function getServerVersion() {
1614 return mysql_get_server_info();
1618 * Ping the server and try to reconnect if it there is no connection
1621 if( function_exists( 'mysql_ping' ) ) {
1622 return mysql_ping( $this->mConn
);
1624 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1631 * At the moment, this will only work if the DB user has the PROCESS privilege
1634 $res = $this->query( 'SHOW PROCESSLIST' );
1635 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1636 # dubious, but unfortunately there's no easy rigorous way
1638 while ( $row = $this->fetchObject( $res ) ) {
1639 if ( $row->User
== 'system user' ) {
1640 if ( ++
$slaveThreads == 2 ) {
1641 # This is it, return the time (except -ve)
1642 if ( $row->Time
> 1>>31 ) {
1654 * Get status information from SHOW STATUS in an associative array
1656 function getStatus() {
1657 $res = $this->query( 'SHOW STATUS' );
1659 while ( $row = $this->fetchObject( $res ) ) {
1660 $status[$row->Variable_name
] = $row->Value
;
1666 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1668 function maxListLen() {
1672 function encodeBlob($b) {
1678 * Database abstraction object for mySQL
1679 * Inherit all methods and properties of Database::Database()
1681 * @package MediaWiki
1684 class DatabaseMysql
extends Database
{
1690 * Result wrapper for grabbing data queried by someone else
1692 * @package MediaWiki
1694 class ResultWrapper
{
1700 function ResultWrapper( &$database, $result ) {
1701 $this->db
=& $database;
1702 $this->result
=& $result;
1708 function numRows() {
1709 return $this->db
->numRows( $this->result
);
1715 function fetchObject() {
1716 return $this->db
->fetchObject( $this->result
);
1722 function &fetchRow() {
1723 return $this->db
->fetchRow( $this->result
);
1730 $this->db
->freeResult( $this->result
);
1731 unset( $this->result
);
1735 function seek( $row ) {
1736 $this->db
->dataSeek( $this->result
, $row );
1740 #------------------------------------------------------------------------------
1742 #------------------------------------------------------------------------------
1745 * Standard fail function, called by default when a connection cannot be
1747 * Displays the file cache if possible
1749 function wfEmergencyAbort( &$conn, $error ) {
1750 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1751 global $wgSitename, $wgServer, $wgMessageCache, $wgLogo;
1753 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1754 # Hard coding strings instead.
1756 $noconnect = "<h1><img src='$wgLogo' style='float:left;margin-right:1em' alt=''>$wgSitename has a problem</h1><p><strong>Sorry! This site is experiencing technical difficulties.</strong></p><p>Try waiting a few minutes and reloading.</p><p><small>(Can't contact the database server: $1)</small></p>";
1757 $mainpage = 'Main Page';
1758 $searchdisabled = <<<EOT
1759 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1760 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1764 <!-- SiteSearch Google -->
1765 <FORM method=GET action=\"http://www.google.com/search\">
1766 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1767 <A HREF=\"http://www.google.com/\">
1768 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1769 border=\"0\" ALT=\"Google\"></A>
1772 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1773 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1775 <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 />
1776 <input type='hidden' name='ie' value='$2'>
1777 <input type='hidden' name='oe' value='$2'>
1781 <!-- SiteSearch Google -->";
1782 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1785 if( !headers_sent() ) {
1786 header( 'HTTP/1.0 500 Internal Server Error' );
1787 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1788 /* Don't cache error pages! They cause no end of trouble... */
1789 header( 'Cache-control: none' );
1790 header( 'Pragma: nocache' );
1793 # No database access
1794 if ( is_object( $wgMessageCache ) ) {
1795 $wgMessageCache->disable();
1798 if ( trim( $error ) == '' ) {
1799 $error = $this->mServer
;
1802 wfLogDBError( "Connection error: $error\n" );
1804 $text = str_replace( '$1', $error, $noconnect );
1805 $text .= wfGetSiteNotice();
1807 if($wgUseFileCache) {
1812 $t = Title
::newFromURL( $title );
1813 } elseif (@/**/$_REQUEST['search']) {
1814 $search = $_REQUEST['search'];
1815 echo $searchdisabled;
1816 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1817 $wgInputEncoding ), $googlesearch );
1820 $t = Title
::newFromText( $mainpage );
1824 $cache = new CacheManager( $t );
1825 if( $cache->isFileCached() ) {
1826 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1827 $cachederror . "</b></p>\n";
1829 $tag = '<div id="article">';
1830 $text = str_replace(
1833 $cache->fetchPageText() );