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() {
530 if ( $this->mConn
) {
531 return mysql_errno( $this->mConn
);
533 return mysql_errno();
538 * Get a description of the last error
539 * See mysql_error() for more details
541 function lastError() {
542 if ( $this->mConn
) {
543 $error = mysql_error( $this->mConn
);
545 $error = mysql_error();
548 $error .= ' (' . $this->mServer
. ')';
553 * Get the number of rows affected by the last write query
554 * See mysql_affected_rows() for more details
556 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
557 /**#@-*/ // end of template : @param $result
560 * Simple UPDATE wrapper
561 * Usually aborts on failure
562 * If errors are explicitly ignored, returns success
564 * This function exists for historical reasons, Database::update() has a more standard
565 * calling convention and feature set
567 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
569 $table = $this->tableName( $table );
570 $sql = "UPDATE $table SET $var = '" .
571 $this->strencode( $value ) . "' WHERE ($cond)";
572 return !!$this->query( $sql, DB_MASTER
, $fname );
576 * Simple SELECT wrapper, returns a single field, input must be encoded
577 * Usually aborts on failure
578 * If errors are explicitly ignored, returns FALSE on failure
580 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
581 if ( !is_array( $options ) ) {
582 $options = array( $options );
584 $options['LIMIT'] = 1;
586 $res = $this->select( $table, $var, $cond, $fname, $options );
587 if ( $res === false ||
!$this->numRows( $res ) ) {
590 $row = $this->fetchRow( $res );
591 if ( $row !== false ) {
592 $this->freeResult( $res );
600 * Returns an optional USE INDEX clause to go after the table, and a
601 * string to go at the end of the query
603 function makeSelectOptions( $options ) {
604 if ( !is_array( $options ) ) {
605 $options = array( $options );
610 if ( isset( $options['ORDER BY'] ) ) {
611 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
613 if ( isset( $options['LIMIT'] ) ) {
614 $tailOpts .= " LIMIT {$options['LIMIT']}";
617 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
618 $tailOpts .= ' FOR UPDATE';
621 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
622 $tailOpts .= ' LOCK IN SHARE MODE';
625 if ( isset( $options['USE INDEX'] ) ) {
626 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
630 return array( $useIndex, $tailOpts );
636 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
638 if( is_array( $vars ) ) {
639 $vars = implode( ',', $vars );
641 if( is_array( $table ) ) {
642 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
643 } elseif ($table!='') {
644 $from = ' FROM ' .$this->tableName( $table );
649 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
651 if( !empty( $conds ) ) {
652 if ( is_array( $conds ) ) {
653 $conds = $this->makeList( $conds, LIST_AND
);
655 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
657 $sql = "SELECT $vars $from $useIndex $tailOpts";
659 return $this->query( $sql, $fname );
663 * Single row SELECT wrapper
664 * Aborts or returns FALSE on error
666 * $vars: the selected variables
667 * $conds: a condition map, terms are ANDed together.
668 * Items with numeric keys are taken to be literal conditions
669 * Takes an array of selected variables, and a condition map, which is ANDed
670 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
671 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
672 * $obj- >page_id is the ID of the Astronomy article
674 * @todo migrate documentation to phpdocumentor format
676 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
677 $options['LIMIT'] = 1;
678 $res = $this->select( $table, $vars, $conds, $fname, $options );
679 if ( $res === false ||
!$this->numRows( $res ) ) {
682 $obj = $this->fetchObject( $res );
683 $this->freeResult( $res );
689 * Removes most variables from an SQL query and replaces them with X or N for numbers.
690 * It's only slightly flawed. Don't use for anything important.
692 * @param string $sql A SQL Query
695 function generalizeSQL( $sql ) {
696 # This does the same as the regexp below would do, but in such a way
697 # as to avoid crashing php on some large strings.
698 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
700 $sql = str_replace ( "\\\\", '', $sql);
701 $sql = str_replace ( "\\'", '', $sql);
702 $sql = str_replace ( "\\\"", '', $sql);
703 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
704 $sql = preg_replace ('/".*"/s', "'X'", $sql);
706 # All newlines, tabs, etc replaced by single space
707 $sql = preg_replace ( "/\s+/", ' ', $sql);
710 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
716 * Determines whether a field exists in a table
717 * Usually aborts on failure
718 * If errors are explicitly ignored, returns NULL on failure
720 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
721 $table = $this->tableName( $table );
722 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE
, $fname );
729 while ( $row = $this->fetchObject( $res ) ) {
730 if ( $row->Field
== $field ) {
739 * Determines whether an index exists
740 * Usually aborts on failure
741 * If errors are explicitly ignored, returns NULL on failure
743 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
744 $info = $this->indexInfo( $table, $index, $fname );
745 if ( is_null( $info ) ) {
748 return $info !== false;
754 * Get information about an index into an object
755 * Returns false if the index does not exist
757 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
758 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
759 # SHOW INDEX should work for 3.x and up:
760 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
761 $table = $this->tableName( $table );
762 $sql = 'SHOW INDEX FROM '.$table;
763 $res = $this->query( $sql, $fname );
768 while ( $row = $this->fetchObject( $res ) ) {
769 if ( $row->Key_name
== $index ) {
777 * Query whether a given table exists
779 function tableExists( $table ) {
780 $table = $this->tableName( $table );
781 $old = $this->ignoreErrors( true );
782 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
783 $this->ignoreErrors( $old );
785 $this->freeResult( $res );
793 * mysql_fetch_field() wrapper
794 * Returns false if the field doesn't exist
799 function fieldInfo( $table, $field ) {
800 $table = $this->tableName( $table );
801 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
802 $n = mysql_num_fields( $res );
803 for( $i = 0; $i < $n; $i++
) {
804 $meta = mysql_fetch_field( $res, $i );
805 if( $field == $meta->name
) {
813 * mysql_field_type() wrapper
815 function fieldType( $res, $index ) {
816 return mysql_field_type( $res, $index );
820 * Determines if a given index is unique
822 function indexUnique( $table, $index ) {
823 $indexInfo = $this->indexInfo( $table, $index );
827 return !$indexInfo->Non_unique
;
831 * INSERT wrapper, inserts an array into a table
833 * $a may be a single associative array, or an array of these with numeric keys, for
836 * Usually aborts on failure
837 * If errors are explicitly ignored, returns success
839 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
840 # No rows to insert, easy just return now
841 if ( !count( $a ) ) {
845 $table = $this->tableName( $table );
846 if ( !is_array( $options ) ) {
847 $options = array( $options );
849 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
851 $keys = array_keys( $a[0] );
854 $keys = array_keys( $a );
857 $sql = 'INSERT ' . implode( ' ', $options ) .
858 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
862 foreach ( $a as $row ) {
868 $sql .= '(' . $this->makeList( $row ) . ')';
871 $sql .= '(' . $this->makeList( $a ) . ')';
873 return !!$this->query( $sql, $fname );
877 * UPDATE wrapper, takes a condition array and a SET array
879 function update( $table, $values, $conds, $fname = 'Database::update' ) {
880 $table = $this->tableName( $table );
881 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET
);
882 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
883 $this->query( $sql, $fname );
887 * Makes a wfStrencoded list from an array
888 * $mode: LIST_COMMA - comma separated, no field names
889 * LIST_AND - ANDed WHERE clause (without the WHERE)
890 * LIST_SET - comma separated with field names, like a SET clause
891 * LIST_NAMES - comma separated field names
893 function makeList( $a, $mode = LIST_COMMA
) {
894 if ( !is_array( $a ) ) {
895 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
900 foreach ( $a as $field => $value ) {
902 if ( $mode == LIST_AND
) {
910 if ( $mode == LIST_AND
&& is_numeric( $field ) ) {
912 } elseif ( $mode == LIST_AND
&& is_array ($value) ) {
913 $list .= $field." IN (".$this->makeList($value).") ";
915 if ( $mode == LIST_AND ||
$mode == LIST_SET
) {
918 $list .= ($mode==LIST_NAMES?
$value:$this->addQuotes( $value ));
925 * Change the current database
927 function selectDB( $db ) {
928 $this->mDBname
= $db;
929 return mysql_select_db( $db, $this->mConn
);
933 * Starts a timer which will kill the DB thread after $timeout seconds
935 function startTimer( $timeout ) {
937 if( function_exists( 'mysql_thread_id' ) ) {
938 # This will kill the query if it's still running after $timeout seconds.
939 $tid = mysql_thread_id( $this->mConn
);
940 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
945 * Stop a timer started by startTimer()
946 * Currently unimplemented.
949 function stopTimer() { }
952 * Format a table name ready for use in constructing an SQL query
954 * This does two important things: it quotes table names which as necessary,
955 * and it adds a table prefix if there is one.
957 * All functions of this object which require a table name call this function
958 * themselves. Pass the canonical name to such functions. This is only needed
959 * when calling query() directly.
961 * @param string $name database table name
963 function tableName( $name ) {
965 if ( $this->mTablePrefix
!== '' ) {
966 if ( strpos( '.', $name ) === false ) {
967 $name = $this->mTablePrefix
. $name;
970 if ( isset( $wgSharedDB ) && 'user' == $name ) {
971 $name = $wgSharedDB . '.' . $name;
973 if( $name == 'group' ) {
974 $name = '`' . $name . '`';
980 * Fetch a number of table names into an array
981 * This is handy when you need to construct SQL for joins
984 * extract($dbr->tableNames('user','watchlist'));
985 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
986 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
988 function tableNames() {
989 $inArray = func_get_args();
991 foreach ( $inArray as $name ) {
992 $retVal[$name] = $this->tableName( $name );
998 * Wrapper for addslashes()
999 * @param string $s String to be slashed.
1000 * @return string slashed string.
1002 function strencode( $s ) {
1003 return addslashes( $s );
1007 * If it's a string, adds quotes and backslashes
1008 * Otherwise returns as-is
1010 function addQuotes( $s ) {
1011 if ( is_null( $s ) ) {
1014 # This will also quote numeric values. This should be harmless,
1015 # and protects against weird problems that occur when they really
1016 # _are_ strings such as article titles and string->number->string
1017 # conversion is not 1:1.
1018 $s = "'" . $this->strencode( $s ) . "'";
1024 * Returns an appropriately quoted sequence value for inserting a new row.
1025 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1026 * subclass will return an integer, and save the value for insertId()
1028 function nextSequenceValue( $seqName ) {
1034 * PostgreSQL doesn't have them and returns ""
1036 function useIndexClause( $index ) {
1037 return 'USE INDEX ('.$index.')';
1041 * REPLACE query wrapper
1042 * PostgreSQL simulates this with a DELETE followed by INSERT
1043 * $row is the row to insert, an associative array
1044 * $uniqueIndexes is an array of indexes. Each element may be either a
1045 * field name or an array of field names
1047 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1048 * However if you do this, you run the risk of encountering errors which wouldn't have
1051 * @todo migrate comment to phodocumentor format
1053 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1054 $table = $this->tableName( $table );
1057 if ( !is_array( reset( $rows ) ) ) {
1058 $rows = array( $rows );
1061 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1063 foreach ( $rows as $row ) {
1069 $sql .= '(' . $this->makeList( $row ) . ')';
1071 return $this->query( $sql, $fname );
1075 * DELETE where the condition is a join
1076 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1078 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1079 * join condition matches, set $conds='*'
1081 * DO NOT put the join condition in $conds
1083 * @param string $delTable The table to delete from.
1084 * @param string $joinTable The other table.
1085 * @param string $delVar The variable to join on, in the first table.
1086 * @param string $joinVar The variable to join on, in the second table.
1087 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1089 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1091 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1094 $delTable = $this->tableName( $delTable );
1095 $joinTable = $this->tableName( $joinTable );
1096 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1097 if ( $conds != '*' ) {
1098 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1101 return $this->query( $sql, $fname );
1105 * Returns the size of a text field, or -1 for "unlimited"
1107 function textFieldSize( $table, $field ) {
1108 $table = $this->tableName( $table );
1109 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1110 $res = $this->query( $sql, 'Database::textFieldSize' );
1111 $row = $this->fetchObject( $res );
1112 $this->freeResult( $res );
1114 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
1123 * @return string Always return 'LOW_PRIORITY'
1125 function lowPriorityOption() {
1126 return 'LOW_PRIORITY';
1130 * DELETE query wrapper
1132 * Use $conds == "*" to delete all rows
1134 function delete( $table, $conds, $fname = 'Database::delete' ) {
1136 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1138 $table = $this->tableName( $table );
1139 $sql = "DELETE FROM $table ";
1140 if ( $conds != '*' ) {
1141 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1143 return $this->query( $sql, $fname );
1147 * INSERT SELECT wrapper
1148 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1149 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1150 * $conds may be "*" to copy the whole table
1152 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1153 $destTable = $this->tableName( $destTable );
1154 $srcTable = $this->tableName( $srcTable );
1155 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1156 ' SELECT ' . implode( ',', $varMap ) .
1158 if ( $conds != '*' ) {
1159 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1161 return $this->query( $sql, $fname );
1165 * Construct a LIMIT query with optional offset
1166 * This is used for query pages
1168 function limitResult($limit,$offset) {
1169 return ' LIMIT '.(is_numeric($offset)?
"{$offset},":"")."{$limit} ";
1173 * Returns an SQL expression for a simple conditional.
1176 * @param string $cond SQL expression which will result in a boolean value
1177 * @param string $trueVal SQL expression to return if true
1178 * @param string $falseVal SQL expression to return if false
1179 * @return string SQL fragment
1181 function conditional( $cond, $trueVal, $falseVal ) {
1182 return " IF($cond, $trueVal, $falseVal) ";
1186 * Determines if the last failure was due to a deadlock
1188 function wasDeadlock() {
1189 return $this->lastErrno() == 1213;
1193 * Perform a deadlock-prone transaction.
1195 * This function invokes a callback function to perform a set of write
1196 * queries. If a deadlock occurs during the processing, the transaction
1197 * will be rolled back and the callback function will be called again.
1200 * $dbw->deadlockLoop( callback, ... );
1202 * Extra arguments are passed through to the specified callback function.
1204 * Returns whatever the callback function returned on its successful,
1205 * iteration, or false on error, for example if the retry limit was
1208 function deadlockLoop() {
1209 $myFname = 'Database::deadlockLoop';
1211 $this->query( 'BEGIN', $myFname );
1212 $args = func_get_args();
1213 $function = array_shift( $args );
1214 $oldIgnore = $dbw->ignoreErrors( true );
1215 $tries = DEADLOCK_TRIES
;
1216 if ( is_array( $function ) ) {
1217 $fname = $function[0];
1222 $retVal = call_user_func_array( $function, $args );
1223 $error = $this->lastError();
1224 $errno = $this->lastErrno();
1225 $sql = $this->lastQuery();
1228 if ( $dbw->wasDeadlock() ) {
1230 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1232 $dbw->reportQueryError( $error, $errno, $sql, $fname );
1235 } while( $dbw->wasDeadlock
&& --$tries > 0 );
1236 $this->ignoreErrors( $oldIgnore );
1237 if ( $tries <= 0 ) {
1238 $this->query( 'ROLLBACK', $myFname );
1239 $this->reportQueryError( $error, $errno, $sql, $fname );
1242 $this->query( 'COMMIT', $myFname );
1248 * Do a SELECT MASTER_POS_WAIT()
1250 * @param string $file the binlog file
1251 * @param string $pos the binlog position
1252 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1254 function masterPosWait( $file, $pos, $timeout ) {
1255 $fname = 'Database::masterPosWait';
1256 wfProfileIn( $fname );
1259 # Commit any open transactions
1260 $this->immediateCommit();
1262 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1263 $encFile = $this->strencode( $file );
1264 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1265 $res = $this->doQuery( $sql );
1266 if ( $res && $row = $this->fetchRow( $res ) ) {
1267 $this->freeResult( $res );
1275 * Get the position of the master from SHOW SLAVE STATUS
1277 function getSlavePos() {
1278 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1279 $row = $this->fetchObject( $res );
1281 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1283 return array( false, false );
1288 * Get the position of the master from SHOW MASTER STATUS
1290 function getMasterPos() {
1291 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1292 $row = $this->fetchObject( $res );
1294 return array( $row->File
, $row->Position
);
1296 return array( false, false );
1301 * Begin a transaction, or if a transaction has already started, continue it
1303 function begin( $fname = 'Database::begin' ) {
1304 if ( !$this->mTrxLevel
) {
1305 $this->immediateBegin( $fname );
1312 * End a transaction, or decrement the nest level if transactions are nested
1314 function commit( $fname = 'Database::commit' ) {
1315 if ( $this->mTrxLevel
) {
1318 if ( !$this->mTrxLevel
) {
1319 $this->immediateCommit( $fname );
1324 * Rollback a transaction
1326 function rollback( $fname = 'Database::rollback' ) {
1327 $this->query( 'ROLLBACK', $fname );
1328 $this->mTrxLevel
= 0;
1332 * Begin a transaction, committing any previously open transaction
1334 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1335 $this->query( 'BEGIN', $fname );
1336 $this->mTrxLevel
= 1;
1340 * Commit transaction, if one is open
1342 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1343 $this->query( 'COMMIT', $fname );
1344 $this->mTrxLevel
= 0;
1348 * Return MW-style timestamp used for MySQL schema
1350 function timestamp( $ts=0 ) {
1351 return wfTimestamp(TS_MW
,$ts);
1357 function &resultObject( &$result ) {
1358 if( empty( $result ) ) {
1361 return new ResultWrapper( $this, $result );
1366 * Return aggregated value alias
1368 function aggregateValue ($valuedata,$valuename='value') {
1373 * @return string wikitext of a link to the server software's web site
1375 function getSoftwareLink() {
1376 return "[http://www.mysql.com/ MySQL]";
1380 * @return string Version information from the database
1382 function getServerVersion() {
1383 return mysql_get_server_info();
1388 * Database abstraction object for mySQL
1389 * Inherit all methods and properties of Database::Database()
1391 * @package MediaWiki
1394 class DatabaseMysql
extends Database
{
1400 * Result wrapper for grabbing data queried by someone else
1402 * @package MediaWiki
1404 class ResultWrapper
{
1410 function ResultWrapper( $database, $result ) {
1411 $this->db
=& $database;
1412 $this->result
=& $result;
1418 function numRows() {
1419 return $this->db
->numRows( $this->result
);
1425 function &fetchObject() {
1426 return $this->db
->fetchObject( $this->result
);
1432 function &fetchRow() {
1433 return $this->db
->fetchRow( $this->result
);
1440 $this->db
->freeResult( $this->result
);
1441 unset( $this->result
);
1446 #------------------------------------------------------------------------------
1448 #------------------------------------------------------------------------------
1451 * Standard fail function, called by default when a connection cannot be
1453 * Displays the file cache if possible
1455 function wfEmergencyAbort( &$conn, $error ) {
1456 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
1457 global $wgSitename, $wgServer;
1459 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1460 # Hard coding strings instead.
1462 $noconnect = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server. <br />
1464 $mainpage = 'Main Page';
1465 $searchdisabled = <<<EOT
1466 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1467 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1471 <!-- SiteSearch Google -->
1472 <FORM method=GET action=\"http://www.google.com/search\">
1473 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1474 <A HREF=\"http://www.google.com/\">
1475 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1476 border=\"0\" ALT=\"Google\"></A>
1479 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1480 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1482 <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 />
1483 <input type='hidden' name='ie' value='$2'>
1484 <input type='hidden' name='oe' value='$2'>
1488 <!-- SiteSearch Google -->";
1489 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1492 if( !headers_sent() ) {
1493 header( 'HTTP/1.0 500 Internal Server Error' );
1494 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1495 /* Don't cache error pages! They cause no end of trouble... */
1496 header( 'Cache-control: none' );
1497 header( 'Pragma: nocache' );
1499 $msg = $wgSiteNotice;
1501 $msg = str_replace( '$1', $error, $noconnect );
1505 if($wgUseFileCache) {
1510 $t = Title
::newFromURL( $title );
1511 } elseif (@/**/$_REQUEST['search']) {
1512 $search = $_REQUEST['search'];
1513 echo $searchdisabled;
1514 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1515 $wgInputEncoding ), $googlesearch );
1518 $t = Title
::newFromText( $mainpage );
1522 $cache = new CacheManager( $t );
1523 if( $cache->isFileCached() ) {
1524 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1525 $cachederror . "</b></p>\n";
1527 $tag = '<div id="article">';
1528 $text = str_replace(
1531 $cache->fetchPageText() );