1dc6c1ae81998e073c9ff1d9afa2a9735921fd69
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
9 * Depends on the CacheManager
11 require_once( 'CacheManager.php' );
13 /** See Database::makeList() */
14 define( 'LIST_COMMA', 0 );
15 define( 'LIST_AND', 1 );
16 define( 'LIST_SET', 2 );
17 define( 'LIST_NAMES', 3);
19 /** Number of times to re-try an operation in case of deadlock */
20 define( 'DEADLOCK_TRIES', 4 );
21 /** Minimum time to wait before retry, in microseconds */
22 define( 'DEADLOCK_DELAY_MIN', 500000 );
23 /** Maximum time to wait before retry */
24 define( 'DEADLOCK_DELAY_MAX', 1500000 );
27 * Database abstraction object
32 #------------------------------------------------------------------------------
34 #------------------------------------------------------------------------------
40 var $mServer, $mUser, $mPassword, $mConn, $mDBname;
41 var $mOut, $mOpened = false;
49 #------------------------------------------------------------------------------
51 #------------------------------------------------------------------------------
52 # These optionally set a variable and return the previous state
55 * Fail function, takes a Database as a parameter
56 * Set to false for default, 1 for ignore errors
58 function failFunction( $function = NULL ) {
59 return wfSetVar( $this->mFailFunction
, $function );
63 * Output page, used for reporting errors
64 * FALSE means discard output
66 function &setOutputPage( &$out ) {
71 * Boolean, controls output of large amounts of debug information
73 function debug( $debug = NULL ) {
74 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
78 * Turns buffering of SQL result sets on (true) or off (false).
79 * Default is "on" and it should not be changed without good reasons.
81 function bufferResults( $buffer = NULL ) {
82 if ( is_null( $buffer ) ) {
83 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
85 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
90 * Turns on (false) or off (true) the automatic generation and sending
91 * of a "we're sorry, but there has been a database error" page on
92 * database errors. Default is on (false). When turned off, the
93 * code should use wfLastErrno() and wfLastError() to handle the
94 * situation as appropriate.
96 function ignoreErrors( $ignoreErrors = NULL ) {
97 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
101 * The current depth of nested transactions
102 * @param integer $level
104 function trxLevel( $level = NULL ) {
105 return wfSetVar( $this->mTrxLevel
, $level );
111 function lastQuery() { return $this->mLastQuery
; }
112 function isOpen() { return $this->mOpened
; }
115 #------------------------------------------------------------------------------
117 #------------------------------------------------------------------------------
120 * @param string $server database server host
121 * @param string $user database user name
122 * @param string $password database user password
123 * @param string $dbname database name
127 * @param failFunction
129 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
131 function Database( $server = false, $user = false, $password = false, $dbName = false,
132 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
134 global $wgOut, $wgDBprefix, $wgCommandLineMode;
135 # Can't get a reference if it hasn't been set yet
136 if ( !isset( $wgOut ) ) {
139 $this->mOut
=& $wgOut;
141 $this->mFailFunction
= $failFunction;
142 $this->mFlags
= $flags;
144 if ( $this->mFlags
& DBO_DEFAULT
) {
145 if ( $wgCommandLineMode ) {
146 $this->mFlags
&= ~DBO_TRX
;
148 $this->mFlags |
= DBO_TRX
;
152 /** Get the default table prefix*/
153 if ( $tablePrefix == 'get from global' ) {
154 $this->mTablePrefix
= $wgDBprefix;
156 $this->mTablePrefix
= $tablePrefix;
160 $this->open( $server, $user, $password, $dbName );
166 * @param failFunction
169 function newFromParams( $server, $user, $password, $dbName,
170 $failFunction = false, $flags = 0 )
172 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
176 * Usually aborts on failure
177 * If the failFunction is set to a non-zero integer, returns success
179 function open( $server, $user, $password, $dbName ) {
180 # Test for missing mysql.so
181 # First try to load it
182 if (!@extension_loaded
('mysql')) {
186 # Otherwise we get a suppressed fatal error, which is very hard to track down
187 if ( !function_exists( 'mysql_connect' ) ) {
188 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
192 $this->mServer
= $server;
193 $this->mUser
= $user;
194 $this->mPassword
= $password;
195 $this->mDBname
= $dbName;
199 @/**/$this->mConn
= mysql_connect( $server, $user, $password );
200 if ( $dbName != '' ) {
201 if ( $this->mConn
!== false ) {
202 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
204 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
207 wfDebug( "DB connection error\n" );
208 wfDebug( "Server: $server, User: $user, Password: " .
209 substr( $password, 0, 3 ) . "...\n" );
214 $success = !!$this->mConn
;
218 $this->reportConnectionError();
221 $this->mOpened
= $success;
227 * Closes a database connection.
228 * if it is open : commits any open transactions
230 * @return bool operation success. true if already closed.
234 $this->mOpened
= false;
235 if ( $this->mConn
) {
236 if ( $this->trxLevel() ) {
237 $this->immediateCommit();
239 return mysql_close( $this->mConn
);
247 * @param string $msg error message ?
248 * @todo parameter $msg is not used
250 function reportConnectionError( $msg = '') {
251 if ( $this->mFailFunction
) {
252 if ( !is_int( $this->mFailFunction
) ) {
253 $ff = $this->mFailFunction
;
254 $ff( $this, mysql_error() );
257 wfEmergencyAbort( $this, mysql_error() );
262 * Usually aborts on failure
263 * If errors are explicitly ignored, returns success
265 function query( $sql, $fname = '', $tempIgnore = false ) {
266 global $wgProfiling, $wgCommandLineMode;
268 if ( $wgProfiling ) {
269 # generalizeSQL will probably cut down the query to reasonable
270 # logging size most of the time. The substr is really just a sanity check.
271 $profName = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
272 wfProfileIn( $profName );
275 $this->mLastQuery
= $sql;
277 if ( $this->debug() ) {
278 $sqlx = substr( $sql, 0, 500 );
279 $sqlx = wordwrap(strtr($sqlx,"\t\n",' '));
280 wfDebug( "SQL: $sqlx\n" );
282 # Add a comment for easy SHOW PROCESSLIST interpretation
284 $commentedSql = "/* $fname */ $sql";
286 $commentedSql = $sql;
289 # If DBO_TRX is set, start a transaction
290 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() && $sql != 'BEGIN' ) {
294 # Do the query and handle errors
295 $ret = $this->doQuery( $commentedSql );
296 if ( false === $ret ) {
297 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
300 if ( $wgProfiling ) {
301 wfProfileOut( $profName );
307 * The DBMS-dependent part of query()
308 * @param string $sql SQL query.
310 function doQuery( $sql ) {
311 if( $this->bufferResults() ) {
312 $ret = mysql_query( $sql, $this->mConn
);
314 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
323 * @param string $fname
324 * @param bool $tempIgnore
326 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
327 global $wgCommandLineMode, $wgFullyInitialised;
328 # Ignore errors during error handling to avoid infinite recursion
329 $ignore = $this->ignoreErrors( true );
331 if( $ignore ||
$tempIgnore ) {
332 wfDebug("SQL ERROR (ignored): " . $error . "\n");
334 $sql1line = str_replace( "\n", "\\n", $sql );
335 wfLogDBError("$fname\t$errno\t$error\t$sql1line\n");
336 wfDebug("SQL ERROR: " . $error . "\n");
337 if ( $wgCommandLineMode ||
!$this->mOut ||
empty( $wgFullyInitialised ) ) {
338 $message = "A database error has occurred\n" .
340 "Function: $fname\n" .
341 "Error: $errno $error\n";
342 if ( !$wgCommandLineMode ) {
343 $message = nl2br( $message );
345 wfDebugDieBacktrace( $message );
347 // this calls wfAbruptExit()
348 $this->mOut
->databaseError( $fname, $sql, $error, $errno );
351 $this->ignoreErrors( $ignore );
356 * Intended to be compatible with the PEAR::DB wrapper functions.
357 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
359 * ? = scalar value, quoted as necessary
360 * ! = raw SQL bit (a function for instance)
361 * & = filename; reads the file and inserts as a blob
362 * (we don't use this though...)
364 function prepare( $sql, $func = 'Database::prepare' ) {
365 /* MySQL doesn't support prepared statements (yet), so just
366 pack up the query for reference. We'll manually replace
368 return array( 'query' => $sql, 'func' => $func );
371 function freePrepared( $prepared ) {
372 /* No-op for MySQL */
376 * Execute a prepared query with the various arguments
377 * @param string $prepared the prepared sql
378 * @param mixed $args Either an array here, or put scalars as varargs
380 function execute( $prepared, $args = null ) {
381 if( !is_array( $args ) ) {
383 $args = func_get_args();
384 array_shift( $args );
386 $sql = $this->fillPrepared( $prepared['query'], $args );
387 return $this->query( $sql, $prepared['func'] );
391 * Prepare & execute an SQL statement, quoting and inserting arguments
392 * in the appropriate places.
395 function safeQuery( $query, $args = null ) {
396 $prepared = $this->prepare( $query, 'Database::safeQuery' );
397 if( !is_array( $args ) ) {
399 $args = func_get_args();
400 array_shift( $args );
402 $retval = $this->execute( $prepared, $args );
403 $this->freePrepared( $prepared );
408 * For faking prepared SQL statements on DBs that don't support
410 * @param string $preparedSql - a 'preparable' SQL statement
411 * @param array $args - array of arguments to fill it with
412 * @return string executable SQL
414 function fillPrepared( $preparedQuery, $args ) {
417 $this->preparedArgs
=& $args;
418 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
419 array( &$this, 'fillPreparedArg' ), $preparedQuery );
423 * preg_callback func for fillPrepared()
424 * The arguments should be in $this->preparedArgs and must not be touched
425 * while we're doing this.
427 * @param array $matches
431 function fillPreparedArg( $matches ) {
432 switch( $matches[1] ) {
433 case '\\?': return '?';
434 case '\\!': return '!';
435 case '\\&': return '&';
437 list( $n, $arg ) = each( $this->preparedArgs
);
438 switch( $matches[1] ) {
439 case '?': return $this->addQuotes( $arg );
440 case '!': return $arg;
442 # return $this->addQuotes( file_get_contents( $arg ) );
443 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
445 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
450 * @param mixed $res A SQL result
453 * Free a result object
455 function freeResult( $res ) {
456 if ( !@/**/mysql_free_result( $res ) ) {
457 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
462 * Fetch the next row from the given result object, in object form
464 function fetchObject( $res ) {
465 @/**/$row = mysql_fetch_object( $res );
466 if( mysql_errno() ) {
467 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
473 * Fetch the next row from the given result object
476 function fetchRow( $res ) {
477 @/**/$row = mysql_fetch_array( $res );
478 if (mysql_errno() ) {
479 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
485 * Get the number of rows in a result object
487 function numRows( $res ) {
488 @/**/$n = mysql_num_rows( $res );
489 if( mysql_errno() ) {
490 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
496 * Get the number of fields in a result object
497 * See documentation for mysql_num_fields()
499 function numFields( $res ) { return mysql_num_fields( $res ); }
502 * Get a field name in a result object
503 * See documentation for mysql_field_name()
505 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
508 * Get the inserted value of an auto-increment row
510 * The value inserted should be fetched from nextSequenceValue()
513 * $id = $dbw->nextSequenceValue('cur_cur_id_seq');
514 * $dbw->insert('cur',array('cur_id' => $id));
515 * $id = $dbw->insertId();
517 function insertId() { return mysql_insert_id( $this->mConn
); }
520 * Change the position of the cursor in a result object
521 * See mysql_data_seek()
523 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
526 * Get the last error number
529 function lastErrno() { return mysql_errno(); }
532 * Get a description of the last error
533 * See mysql_error() for more details
535 function lastError() { return mysql_error(); }
538 * Get the number of rows affected by the last write query
539 * See mysql_affected_rows() for more details
541 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
542 /**#@-*/ // end of template : @param $result
545 * Simple UPDATE wrapper
546 * Usually aborts on failure
547 * If errors are explicitly ignored, returns success
549 * This function exists for historical reasons, Database::update() has a more standard
550 * calling convention and feature set
552 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
554 $table = $this->tableName( $table );
555 $sql = "UPDATE $table SET $var = '" .
556 $this->strencode( $value ) . "' WHERE ($cond)";
557 return !!$this->query( $sql, DB_MASTER
, $fname );
561 * Simple SELECT wrapper, returns a single field, input must be encoded
562 * Usually aborts on failure
563 * If errors are explicitly ignored, returns FALSE on failure
565 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
566 if ( !is_array( $options ) ) {
567 $options = array( $options );
569 $options['LIMIT'] = 1;
571 $res = $this->select( $table, $var, $cond, $fname, $options );
572 if ( $res === false ||
!$this->numRows( $res ) ) {
575 $row = $this->fetchRow( $res );
576 if ( $row !== false ) {
577 $this->freeResult( $res );
585 * Returns an optional USE INDEX clause to go after the table, and a
586 * string to go at the end of the query
588 function makeSelectOptions( $options ) {
589 if ( !is_array( $options ) ) {
590 $options = array( $options );
595 if ( isset( $options['ORDER BY'] ) ) {
596 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
598 if ( isset( $options['LIMIT'] ) ) {
599 $tailOpts .= " LIMIT {$options['LIMIT']}";
602 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
603 $tailOpts .= ' FOR UPDATE';
606 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
607 $tailOpts .= ' LOCK IN SHARE MODE';
610 if ( isset( $options['USE INDEX'] ) ) {
611 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
615 return array( $useIndex, $tailOpts );
621 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
623 if ( is_array( $vars ) ) {
624 $vars = implode( ',', $vars );
626 if( is_array( $table ) ) {
627 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
628 } elseif ($table!='') {
629 $from = ' FROM ' .$this->tableName( $table );
634 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
636 if ( $conds !== false && $conds != '' ) {
637 if ( is_array( $conds ) ) {
638 $conds = $this->makeList( $conds, LIST_AND
);
640 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
642 $sql = "SELECT $vars $from $useIndex $tailOpts";
644 return $this->query( $sql, $fname );
648 * Single row SELECT wrapper
649 * Aborts or returns FALSE on error
651 * $vars: the selected variables
652 * $conds: a condition map, terms are ANDed together.
653 * Items with numeric keys are taken to be literal conditions
654 * Takes an array of selected variables, and a condition map, which is ANDed
655 * e.g. selectRow( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
656 * would return an object where $obj->cur_id is the ID of the Astronomy article
658 * @todo migrate documentation to phpdocumentor format
660 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
661 $options['LIMIT'] = 1;
662 $res = $this->select( $table, $vars, $conds, $fname, $options );
663 if ( $res === false ||
!$this->numRows( $res ) ) {
666 $obj = $this->fetchObject( $res );
667 $this->freeResult( $res );
673 * Removes most variables from an SQL query and replaces them with X or N for numbers.
674 * It's only slightly flawed. Don't use for anything important.
676 * @param string $sql A SQL Query
679 function generalizeSQL( $sql ) {
680 # This does the same as the regexp below would do, but in such a way
681 # as to avoid crashing php on some large strings.
682 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
684 $sql = str_replace ( "\\\\", '', $sql);
685 $sql = str_replace ( "\\'", '', $sql);
686 $sql = str_replace ( "\\\"", '', $sql);
687 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
688 $sql = preg_replace ('/".*"/s', "'X'", $sql);
690 # All newlines, tabs, etc replaced by single space
691 $sql = preg_replace ( "/\s+/", ' ', $sql);
694 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
700 * Determines whether a field exists in a table
701 * Usually aborts on failure
702 * If errors are explicitly ignored, returns NULL on failure
704 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
705 $table = $this->tableName( $table );
706 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE
, $fname );
713 while ( $row = $this->fetchObject( $res ) ) {
714 if ( $row->Field
== $field ) {
723 * Determines whether an index exists
724 * Usually aborts on failure
725 * If errors are explicitly ignored, returns NULL on failure
727 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
728 $info = $this->indexInfo( $table, $index, $fname );
729 if ( is_null( $info ) ) {
732 return $info !== false;
738 * Get information about an index into an object
739 * Returns false if the index does not exist
741 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
742 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
743 # SHOW INDEX should work for 3.x and up:
744 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
745 $table = $this->tableName( $table );
746 $sql = 'SHOW INDEX FROM '.$table;
747 $res = $this->query( $sql, $fname );
752 while ( $row = $this->fetchObject( $res ) ) {
753 if ( $row->Key_name
== $index ) {
761 * Query whether a given table exists
763 function tableExists( $table ) {
764 $table = $this->tableName( $table );
765 $old = $this->ignoreErrors( true );
766 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
767 $this->ignoreErrors( $old );
769 $this->freeResult( $res );
777 * mysql_fetch_field() wrapper
778 * Returns false if the field doesn't exist
783 function fieldInfo( $table, $field ) {
784 $table = $this->tableName( $table );
785 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
786 $n = mysql_num_fields( $res );
787 for( $i = 0; $i < $n; $i++
) {
788 $meta = mysql_fetch_field( $res, $i );
789 if( $field == $meta->name
) {
797 * mysql_field_type() wrapper
799 function fieldType( $res, $index ) {
800 return mysql_field_type( $res, $index );
804 * Determines if a given index is unique
806 function indexUnique( $table, $index ) {
807 $indexInfo = $this->indexInfo( $table, $index );
811 return !$indexInfo->Non_unique
;
815 * INSERT wrapper, inserts an array into a table
817 * $a may be a single associative array, or an array of these with numeric keys, for
820 * Usually aborts on failure
821 * If errors are explicitly ignored, returns success
823 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
824 # No rows to insert, easy just return now
825 if ( !count( $a ) ) {
829 $table = $this->tableName( $table );
830 if ( !is_array( $options ) ) {
831 $options = array( $options );
833 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
835 $keys = array_keys( $a[0] );
838 $keys = array_keys( $a );
841 $sql = 'INSERT ' . implode( ' ', $options ) .
842 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
846 foreach ( $a as $row ) {
852 $sql .= '(' . $this->makeList( $row ) . ')';
855 $sql .= '(' . $this->makeList( $a ) . ')';
857 return !!$this->query( $sql, $fname );
861 * UPDATE wrapper, takes a condition array and a SET array
863 function update( $table, $values, $conds, $fname = 'Database::update' ) {
864 $table = $this->tableName( $table );
865 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET
);
866 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
867 $this->query( $sql, $fname );
871 * Makes a wfStrencoded list from an array
872 * $mode: LIST_COMMA - comma separated, no field names
873 * LIST_AND - ANDed WHERE clause (without the WHERE)
874 * LIST_SET - comma separated with field names, like a SET clause
875 * LIST_NAMES - comma separated field names
877 function makeList( $a, $mode = LIST_COMMA
) {
878 if ( !is_array( $a ) ) {
879 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
884 foreach ( $a as $field => $value ) {
886 if ( $mode == LIST_AND
) {
894 if ( $mode == LIST_AND
&& is_numeric( $field ) ) {
896 } elseif ( $mode == LIST_AND
&& is_array ($value) ) {
897 $list .= $field." IN (".$this->makeList($value).") ";
899 if ( $mode == LIST_AND ||
$mode == LIST_SET
) {
902 $list .= ($mode==LIST_NAMES?
$value:$this->addQuotes( $value ));
909 * Change the current database
911 function selectDB( $db ) {
912 $this->mDBname
= $db;
913 return mysql_select_db( $db, $this->mConn
);
917 * Starts a timer which will kill the DB thread after $timeout seconds
919 function startTimer( $timeout ) {
921 if( function_exists( 'mysql_thread_id' ) ) {
922 # This will kill the query if it's still running after $timeout seconds.
923 $tid = mysql_thread_id( $this->mConn
);
924 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
929 * Stop a timer started by startTimer()
930 * Currently unimplemented.
933 function stopTimer() { }
936 * Format a table name ready for use in constructing an SQL query
938 * This does two important things: it quotes table names which as necessary,
939 * and it adds a table prefix if there is one.
941 * All functions of this object which require a table name call this function
942 * themselves. Pass the canonical name to such functions. This is only needed
943 * when calling query() directly.
945 * @param string $name database table name
947 function tableName( $name ) {
949 if ( $this->mTablePrefix
!== '' ) {
950 if ( strpos( '.', $name ) === false ) {
951 $name = $this->mTablePrefix
. $name;
954 if ( isset( $wgSharedDB ) && 'user' == $name ) {
955 $name = $wgSharedDB . '.' . $name;
957 if( $name == 'group' ) {
958 $name = '`' . $name . '`';
964 * Fetch a number of table names into an array
965 * This is handy when you need to construct SQL for joins
968 * extract($dbr->tableNames('user','watchlist'));
969 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
970 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
972 function tableNames() {
973 $inArray = func_get_args();
975 foreach ( $inArray as $name ) {
976 $retVal[$name] = $this->tableName( $name );
982 * Wrapper for addslashes()
983 * @param string $s String to be slashed.
984 * @return string slashed string.
986 function strencode( $s ) {
987 return addslashes( $s );
991 * If it's a string, adds quotes and backslashes
992 * Otherwise returns as-is
994 function addQuotes( $s ) {
995 if ( is_null( $s ) ) {
998 # This will also quote numeric values. This should be harmless,
999 # and protects against weird problems that occur when they really
1000 # _are_ strings such as article titles and string->number->string
1001 # conversion is not 1:1.
1002 $s = "'" . $this->strencode( $s ) . "'";
1008 * Returns an appropriately quoted sequence value for inserting a new row.
1009 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1010 * subclass will return an integer, and save the value for insertId()
1012 function nextSequenceValue( $seqName ) {
1018 * PostgreSQL doesn't have them and returns ""
1020 function useIndexClause( $index ) {
1021 return 'USE INDEX ('.$index.')';
1025 * REPLACE query wrapper
1026 * PostgreSQL simulates this with a DELETE followed by INSERT
1027 * $row is the row to insert, an associative array
1028 * $uniqueIndexes is an array of indexes. Each element may be either a
1029 * field name or an array of field names
1031 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1032 * However if you do this, you run the risk of encountering errors which wouldn't have
1035 * @todo migrate comment to phodocumentor format
1037 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1038 $table = $this->tableName( $table );
1041 if ( !is_array( reset( $rows ) ) ) {
1042 $rows = array( $rows );
1045 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1047 foreach ( $rows as $row ) {
1053 $sql .= '(' . $this->makeList( $row ) . ')';
1055 return $this->query( $sql, $fname );
1059 * DELETE where the condition is a join
1060 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1062 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1063 * join condition matches, set $conds='*'
1065 * DO NOT put the join condition in $conds
1067 * @param string $delTable The table to delete from.
1068 * @param string $joinTable The other table.
1069 * @param string $delVar The variable to join on, in the first table.
1070 * @param string $joinVar The variable to join on, in the second table.
1071 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1073 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1075 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1078 $delTable = $this->tableName( $delTable );
1079 $joinTable = $this->tableName( $joinTable );
1080 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1081 if ( $conds != '*' ) {
1082 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1085 return $this->query( $sql, $fname );
1089 * Returns the size of a text field, or -1 for "unlimited"
1091 function textFieldSize( $table, $field ) {
1092 $table = $this->tableName( $table );
1093 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1094 $res = $this->query( $sql, 'Database::textFieldSize' );
1095 $row = $this->fetchObject( $res );
1096 $this->freeResult( $res );
1098 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
1107 * @return string Always return 'LOW_PRIORITY'
1109 function lowPriorityOption() {
1110 return 'LOW_PRIORITY';
1114 * DELETE query wrapper
1116 * Use $conds == "*" to delete all rows
1118 function delete( $table, $conds, $fname = 'Database::delete' ) {
1120 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1122 $table = $this->tableName( $table );
1123 $sql = "DELETE FROM $table ";
1124 if ( $conds != '*' ) {
1125 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1127 return $this->query( $sql, $fname );
1131 * INSERT SELECT wrapper
1132 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1133 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1134 * $conds may be "*" to copy the whole table
1136 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1137 $destTable = $this->tableName( $destTable );
1138 $srcTable = $this->tableName( $srcTable );
1139 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1140 ' SELECT ' . implode( ',', $varMap ) .
1142 if ( $conds != '*' ) {
1143 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1145 return $this->query( $sql, $fname );
1149 * Construct a LIMIT query with optional offset
1150 * This is used for query pages
1152 function limitResult($limit,$offset) {
1153 return ' LIMIT '.(is_numeric($offset)?
"{$offset},":"")."{$limit} ";
1157 * Returns an SQL expression for a simple conditional.
1160 * @param string $cond SQL expression which will result in a boolean value
1161 * @param string $trueVal SQL expression to return if true
1162 * @param string $falseVal SQL expression to return if false
1163 * @return string SQL fragment
1165 function conditional( $cond, $trueVal, $falseVal ) {
1166 return " IF($cond, $trueVal, $falseVal) ";
1170 * Determines if the last failure was due to a deadlock
1172 function wasDeadlock() {
1173 return $this->lastErrno() == 1213;
1177 * Perform a deadlock-prone transaction.
1179 * This function invokes a callback function to perform a set of write
1180 * queries. If a deadlock occurs during the processing, the transaction
1181 * will be rolled back and the callback function will be called again.
1184 * $dbw->deadlockLoop( callback, ... );
1186 * Extra arguments are passed through to the specified callback function.
1188 * Returns whatever the callback function returned on its successful,
1189 * iteration, or false on error, for example if the retry limit was
1192 function deadlockLoop() {
1193 $myFname = 'Database::deadlockLoop';
1195 $this->query( 'BEGIN', $myFname );
1196 $args = func_get_args();
1197 $function = array_shift( $args );
1198 $oldIgnore = $dbw->ignoreErrors( true );
1199 $tries = DEADLOCK_TRIES
;
1200 if ( is_array( $function ) ) {
1201 $fname = $function[0];
1206 $retVal = call_user_func_array( $function, $args );
1207 $error = $this->lastError();
1208 $errno = $this->lastErrno();
1209 $sql = $this->lastQuery();
1212 if ( $dbw->wasDeadlock() ) {
1214 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1216 $dbw->reportQueryError( $error, $errno, $sql, $fname );
1219 } while( $dbw->wasDeadlock
&& --$tries > 0 );
1220 $this->ignoreErrors( $oldIgnore );
1221 if ( $tries <= 0 ) {
1222 $this->query( 'ROLLBACK', $myFname );
1223 $this->reportQueryError( $error, $errno, $sql, $fname );
1226 $this->query( 'COMMIT', $myFname );
1232 * Do a SELECT MASTER_POS_WAIT()
1234 * @param string $file the binlog file
1235 * @param string $pos the binlog position
1236 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1238 function masterPosWait( $file, $pos, $timeout ) {
1239 $encFile = $this->strencode( $file );
1240 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1241 $res = $this->query( $sql, 'Database::masterPosWait' );
1242 if ( $res && $row = $this->fetchRow( $res ) ) {
1243 $this->freeResult( $res );
1251 * Get the position of the master from SHOW SLAVE STATUS
1253 function getSlavePos() {
1254 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1255 $row = $this->fetchObject( $res );
1257 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1259 return array( false, false );
1264 * Get the position of the master from SHOW MASTER STATUS
1266 function getMasterPos() {
1267 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1268 $row = $this->fetchObject( $res );
1270 return array( $row->File
, $row->Position
);
1272 return array( false, false );
1277 * Begin a transaction, or if a transaction has already started, continue it
1279 function begin( $fname = 'Database::begin' ) {
1280 if ( !$this->mTrxLevel
) {
1281 $this->immediateBegin( $fname );
1288 * End a transaction, or decrement the nest level if transactions are nested
1290 function commit( $fname = 'Database::commit' ) {
1291 if ( $this->mTrxLevel
) {
1294 if ( !$this->mTrxLevel
) {
1295 $this->immediateCommit( $fname );
1300 * Rollback a transaction
1302 function rollback( $fname = 'Database::rollback' ) {
1303 $this->query( 'ROLLBACK', $fname );
1304 $this->mTrxLevel
= 0;
1308 * Begin a transaction, committing any previously open transaction
1310 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1311 $this->query( 'BEGIN', $fname );
1312 $this->mTrxLevel
= 1;
1316 * Commit transaction, if one is open
1318 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1319 $this->query( 'COMMIT', $fname );
1320 $this->mTrxLevel
= 0;
1324 * Return MW-style timestamp used for MySQL schema
1326 function timestamp( $ts=0 ) {
1327 return wfTimestamp(TS_MW
,$ts);
1333 function &resultObject( &$result ) {
1334 if( empty( $result ) ) {
1337 return new ResultWrapper( $this, $result );
1342 * Return aggregated value alias
1344 function aggregateValue ($valuedata,$valuename='value') {
1349 * @return string wikitext of a link to the server software's web site
1351 function getSoftwareLink() {
1352 return "[http://www.mysql.com/ MySQL]";
1356 * @return string Version information from the database
1358 function getServerVersion() {
1359 return mysql_get_server_info();
1364 * Database abstraction object for mySQL
1365 * Inherit all methods and properties of Database::Database()
1367 * @package MediaWiki
1370 class DatabaseMysql
extends Database
{
1376 * Result wrapper for grabbing data queried by someone else
1378 * @package MediaWiki
1380 class ResultWrapper
{
1386 function ResultWrapper( $database, $result ) {
1387 $this->db
=& $database;
1388 $this->result
=& $result;
1394 function numRows() {
1395 return $this->db
->numRows( $this->result
);
1401 function &fetchObject() {
1402 return $this->db
->fetchObject( $this->result
);
1408 function &fetchRow() {
1409 return $this->db
->fetchRow( $this->result
);
1416 $this->db
->freeResult( $this->result
);
1417 unset( $this->result
);
1422 #------------------------------------------------------------------------------
1424 #------------------------------------------------------------------------------
1427 * Standard fail function, called by default when a connection cannot be
1429 * Displays the file cache if possible
1431 function wfEmergencyAbort( &$conn, $error ) {
1432 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
1434 if( !headers_sent() ) {
1435 header( 'HTTP/1.0 500 Internal Server Error' );
1436 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1437 /* Don't cache error pages! They cause no end of trouble... */
1438 header( 'Cache-control: none' );
1439 header( 'Pragma: nocache' );
1441 $msg = $wgSiteNotice;
1442 if($msg == '') $msg = wfMsgNoDB( 'noconnect', $error );
1445 if($wgUseFileCache) {
1450 $t = Title
::newFromURL( $title );
1451 } elseif (@/**/$_REQUEST['search']) {
1452 $search = $_REQUEST['search'];
1453 echo wfMsgNoDB( 'searchdisabled' );
1454 echo wfMsgNoDB( 'googlesearch', htmlspecialchars( $search ), $wgInputEncoding );
1457 $t = Title
::newFromText( wfMsgNoDBForContent( 'mainpage' ) );
1461 $cache = new CacheManager( $t );
1462 if( $cache->isFileCached() ) {
1463 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1464 wfMsgNoDB( 'cachederror' ) . "</b></p>\n";
1466 $tag = '<div id="article">';
1467 $text = str_replace(
1470 $cache->fetchPageText() );