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 # Add a comment for easy SHOW PROCESSLIST interpretation
279 $commentedSql = "/* $fname */ $sql";
281 $commentedSql = $sql;
284 # If DBO_TRX is set, start a transaction
285 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() && $sql != 'BEGIN' ) {
289 if ( $this->debug() ) {
290 $sqlx = substr( $sql, 0, 500 );
291 $sqlx = strtr($sqlx,"\t\n",' ');
292 wfDebug( "SQL: $sqlx\n" );
295 # Do the query and handle errors
296 $ret = $this->doQuery( $commentedSql );
297 if ( false === $ret ) {
298 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
301 if ( $wgProfiling ) {
302 wfProfileOut( $profName );
308 * The DBMS-dependent part of query()
309 * @param string $sql SQL query.
311 function doQuery( $sql ) {
312 if( $this->bufferResults() ) {
313 $ret = mysql_query( $sql, $this->mConn
);
315 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
324 * @param string $fname
325 * @param bool $tempIgnore
327 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
328 global $wgCommandLineMode, $wgFullyInitialised;
329 # Ignore errors during error handling to avoid infinite recursion
330 $ignore = $this->ignoreErrors( true );
332 if( $ignore ||
$tempIgnore ) {
333 wfDebug("SQL ERROR (ignored): " . $error . "\n");
335 $sql1line = str_replace( "\n", "\\n", $sql );
336 wfLogDBError("$fname\t$errno\t$error\t$sql1line\n");
337 wfDebug("SQL ERROR: " . $error . "\n");
338 if ( $wgCommandLineMode ||
!$this->mOut ||
empty( $wgFullyInitialised ) ) {
339 $message = "A database error has occurred\n" .
341 "Function: $fname\n" .
342 "Error: $errno $error\n";
343 if ( !$wgCommandLineMode ) {
344 $message = nl2br( $message );
346 wfDebugDieBacktrace( $message );
348 // this calls wfAbruptExit()
349 $this->mOut
->databaseError( $fname, $sql, $error, $errno );
352 $this->ignoreErrors( $ignore );
357 * Intended to be compatible with the PEAR::DB wrapper functions.
358 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
360 * ? = scalar value, quoted as necessary
361 * ! = raw SQL bit (a function for instance)
362 * & = filename; reads the file and inserts as a blob
363 * (we don't use this though...)
365 function prepare( $sql, $func = 'Database::prepare' ) {
366 /* MySQL doesn't support prepared statements (yet), so just
367 pack up the query for reference. We'll manually replace
369 return array( 'query' => $sql, 'func' => $func );
372 function freePrepared( $prepared ) {
373 /* No-op for MySQL */
377 * Execute a prepared query with the various arguments
378 * @param string $prepared the prepared sql
379 * @param mixed $args Either an array here, or put scalars as varargs
381 function execute( $prepared, $args = null ) {
382 if( !is_array( $args ) ) {
384 $args = func_get_args();
385 array_shift( $args );
387 $sql = $this->fillPrepared( $prepared['query'], $args );
388 return $this->query( $sql, $prepared['func'] );
392 * Prepare & execute an SQL statement, quoting and inserting arguments
393 * in the appropriate places.
394 * @param string $query
395 * @param string $args (default null)
397 function safeQuery( $query, $args = null ) {
398 $prepared = $this->prepare( $query, 'Database::safeQuery' );
399 if( !is_array( $args ) ) {
401 $args = func_get_args();
402 array_shift( $args );
404 $retval = $this->execute( $prepared, $args );
405 $this->freePrepared( $prepared );
410 * For faking prepared SQL statements on DBs that don't support
412 * @param string $preparedSql - a 'preparable' SQL statement
413 * @param array $args - array of arguments to fill it with
414 * @return string executable SQL
416 function fillPrepared( $preparedQuery, $args ) {
419 $this->preparedArgs
=& $args;
420 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
421 array( &$this, 'fillPreparedArg' ), $preparedQuery );
425 * preg_callback func for fillPrepared()
426 * The arguments should be in $this->preparedArgs and must not be touched
427 * while we're doing this.
429 * @param array $matches
433 function fillPreparedArg( $matches ) {
434 switch( $matches[1] ) {
435 case '\\?': return '?';
436 case '\\!': return '!';
437 case '\\&': return '&';
439 list( $n, $arg ) = each( $this->preparedArgs
);
440 switch( $matches[1] ) {
441 case '?': return $this->addQuotes( $arg );
442 case '!': return $arg;
444 # return $this->addQuotes( file_get_contents( $arg ) );
445 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
447 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
452 * @param mixed $res A SQL result
455 * Free a result object
457 function freeResult( $res ) {
458 if ( !@/**/mysql_free_result( $res ) ) {
459 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
464 * Fetch the next row from the given result object, in object form
466 function fetchObject( $res ) {
467 @/**/$row = mysql_fetch_object( $res );
468 if( mysql_errno() ) {
469 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
475 * Fetch the next row from the given result object
478 function fetchRow( $res ) {
479 @/**/$row = mysql_fetch_array( $res );
480 if (mysql_errno() ) {
481 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
487 * Get the number of rows in a result object
489 function numRows( $res ) {
490 @/**/$n = mysql_num_rows( $res );
491 if( mysql_errno() ) {
492 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
498 * Get the number of fields in a result object
499 * See documentation for mysql_num_fields()
501 function numFields( $res ) { return mysql_num_fields( $res ); }
504 * Get a field name in a result object
505 * See documentation for mysql_field_name()
507 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
510 * Get the inserted value of an auto-increment row
512 * The value inserted should be fetched from nextSequenceValue()
515 * $id = $dbw->nextSequenceValue('page_page_id_seq');
516 * $dbw->insert('page',array('page_id' => $id));
517 * $id = $dbw->insertId();
519 function insertId() { return mysql_insert_id( $this->mConn
); }
522 * Change the position of the cursor in a result object
523 * See mysql_data_seek()
525 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
528 * Get the last error number
531 function lastErrno() {
532 if ( $this->mConn
) {
533 return mysql_errno( $this->mConn
);
535 return mysql_errno();
540 * Get a description of the last error
541 * See mysql_error() for more details
543 function lastError() {
544 if ( $this->mConn
) {
545 $error = mysql_error( $this->mConn
);
547 $error = mysql_error();
550 $error .= ' (' . $this->mServer
. ')';
555 * Get the number of rows affected by the last write query
556 * See mysql_affected_rows() for more details
558 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
559 /**#@-*/ // end of template : @param $result
562 * Simple UPDATE wrapper
563 * Usually aborts on failure
564 * If errors are explicitly ignored, returns success
566 * This function exists for historical reasons, Database::update() has a more standard
567 * calling convention and feature set
569 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
571 $table = $this->tableName( $table );
572 $sql = "UPDATE $table SET $var = '" .
573 $this->strencode( $value ) . "' WHERE ($cond)";
574 return !!$this->query( $sql, DB_MASTER
, $fname );
578 * Simple SELECT wrapper, returns a single field, input must be encoded
579 * Usually aborts on failure
580 * If errors are explicitly ignored, returns FALSE on failure
582 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
583 if ( !is_array( $options ) ) {
584 $options = array( $options );
586 $options['LIMIT'] = 1;
588 $res = $this->select( $table, $var, $cond, $fname, $options );
589 if ( $res === false ||
!$this->numRows( $res ) ) {
592 $row = $this->fetchRow( $res );
593 if ( $row !== false ) {
594 $this->freeResult( $res );
602 * Returns an optional USE INDEX clause to go after the table, and a
603 * string to go at the end of the query
605 function makeSelectOptions( $options ) {
606 if ( !is_array( $options ) ) {
607 $options = array( $options );
612 if ( isset( $options['ORDER BY'] ) ) {
613 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
615 if ( isset( $options['LIMIT'] ) ) {
616 $tailOpts .= " LIMIT {$options['LIMIT']}";
619 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
620 $tailOpts .= ' FOR UPDATE';
623 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
624 $tailOpts .= ' LOCK IN SHARE MODE';
627 if ( isset( $options['USE INDEX'] ) ) {
628 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
632 return array( $useIndex, $tailOpts );
638 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
640 if( is_array( $vars ) ) {
641 $vars = implode( ',', $vars );
643 if( is_array( $table ) ) {
644 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
645 } elseif ($table!='') {
646 $from = ' FROM ' .$this->tableName( $table );
651 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
653 if( !empty( $conds ) ) {
654 if ( is_array( $conds ) ) {
655 $conds = $this->makeList( $conds, LIST_AND
);
657 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
659 $sql = "SELECT $vars $from $useIndex $tailOpts";
661 return $this->query( $sql, $fname );
665 * Single row SELECT wrapper
666 * Aborts or returns FALSE on error
668 * $vars: the selected variables
669 * $conds: a condition map, terms are ANDed together.
670 * Items with numeric keys are taken to be literal conditions
671 * Takes an array of selected variables, and a condition map, which is ANDed
672 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
673 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
674 * $obj- >page_id is the ID of the Astronomy article
676 * @todo migrate documentation to phpdocumentor format
678 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
679 $options['LIMIT'] = 1;
680 $res = $this->select( $table, $vars, $conds, $fname, $options );
681 if ( $res === false ||
!$this->numRows( $res ) ) {
684 $obj = $this->fetchObject( $res );
685 $this->freeResult( $res );
691 * Removes most variables from an SQL query and replaces them with X or N for numbers.
692 * It's only slightly flawed. Don't use for anything important.
694 * @param string $sql A SQL Query
697 function generalizeSQL( $sql ) {
698 # This does the same as the regexp below would do, but in such a way
699 # as to avoid crashing php on some large strings.
700 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
702 $sql = str_replace ( "\\\\", '', $sql);
703 $sql = str_replace ( "\\'", '', $sql);
704 $sql = str_replace ( "\\\"", '', $sql);
705 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
706 $sql = preg_replace ('/".*"/s', "'X'", $sql);
708 # All newlines, tabs, etc replaced by single space
709 $sql = preg_replace ( "/\s+/", ' ', $sql);
712 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
718 * Determines whether a field exists in a table
719 * Usually aborts on failure
720 * If errors are explicitly ignored, returns NULL on failure
722 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
723 $table = $this->tableName( $table );
724 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE
, $fname );
731 while ( $row = $this->fetchObject( $res ) ) {
732 if ( $row->Field
== $field ) {
741 * Determines whether an index exists
742 * Usually aborts on failure
743 * If errors are explicitly ignored, returns NULL on failure
745 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
746 $info = $this->indexInfo( $table, $index, $fname );
747 if ( is_null( $info ) ) {
750 return $info !== false;
756 * Get information about an index into an object
757 * Returns false if the index does not exist
759 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
760 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
761 # SHOW INDEX should work for 3.x and up:
762 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
763 $table = $this->tableName( $table );
764 $sql = 'SHOW INDEX FROM '.$table;
765 $res = $this->query( $sql, $fname );
770 while ( $row = $this->fetchObject( $res ) ) {
771 if ( $row->Key_name
== $index ) {
779 * Query whether a given table exists
781 function tableExists( $table ) {
782 $table = $this->tableName( $table );
783 $old = $this->ignoreErrors( true );
784 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
785 $this->ignoreErrors( $old );
787 $this->freeResult( $res );
795 * mysql_fetch_field() wrapper
796 * Returns false if the field doesn't exist
801 function fieldInfo( $table, $field ) {
802 $table = $this->tableName( $table );
803 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
804 $n = mysql_num_fields( $res );
805 for( $i = 0; $i < $n; $i++
) {
806 $meta = mysql_fetch_field( $res, $i );
807 if( $field == $meta->name
) {
815 * mysql_field_type() wrapper
817 function fieldType( $res, $index ) {
818 return mysql_field_type( $res, $index );
822 * Determines if a given index is unique
824 function indexUnique( $table, $index ) {
825 $indexInfo = $this->indexInfo( $table, $index );
829 return !$indexInfo->Non_unique
;
833 * INSERT wrapper, inserts an array into a table
835 * $a may be a single associative array, or an array of these with numeric keys, for
838 * Usually aborts on failure
839 * If errors are explicitly ignored, returns success
841 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
842 # No rows to insert, easy just return now
843 if ( !count( $a ) ) {
847 $table = $this->tableName( $table );
848 if ( !is_array( $options ) ) {
849 $options = array( $options );
851 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
853 $keys = array_keys( $a[0] );
856 $keys = array_keys( $a );
859 $sql = 'INSERT ' . implode( ' ', $options ) .
860 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
864 foreach ( $a as $row ) {
870 $sql .= '(' . $this->makeList( $row ) . ')';
873 $sql .= '(' . $this->makeList( $a ) . ')';
875 return !!$this->query( $sql, $fname );
879 * UPDATE wrapper, takes a condition array and a SET array
881 function update( $table, $values, $conds, $fname = 'Database::update' ) {
882 $table = $this->tableName( $table );
883 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET
);
884 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
885 $this->query( $sql, $fname );
889 * Makes a wfStrencoded list from an array
890 * $mode: LIST_COMMA - comma separated, no field names
891 * LIST_AND - ANDed WHERE clause (without the WHERE)
892 * LIST_SET - comma separated with field names, like a SET clause
893 * LIST_NAMES - comma separated field names
895 function makeList( $a, $mode = LIST_COMMA
) {
896 if ( !is_array( $a ) ) {
897 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
902 foreach ( $a as $field => $value ) {
904 if ( $mode == LIST_AND
) {
912 if ( $mode == LIST_AND
&& is_numeric( $field ) ) {
914 } elseif ( $mode == LIST_AND
&& is_array ($value) ) {
915 $list .= $field." IN (".$this->makeList($value).") ";
917 if ( $mode == LIST_AND ||
$mode == LIST_SET
) {
920 $list .= ($mode==LIST_NAMES?
$value:$this->addQuotes( $value ));
927 * Change the current database
929 function selectDB( $db ) {
930 $this->mDBname
= $db;
931 return mysql_select_db( $db, $this->mConn
);
935 * Starts a timer which will kill the DB thread after $timeout seconds
937 function startTimer( $timeout ) {
939 if( function_exists( 'mysql_thread_id' ) ) {
940 # This will kill the query if it's still running after $timeout seconds.
941 $tid = mysql_thread_id( $this->mConn
);
942 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
947 * Stop a timer started by startTimer()
948 * Currently unimplemented.
951 function stopTimer() { }
954 * Format a table name ready for use in constructing an SQL query
956 * This does two important things: it quotes table names which as necessary,
957 * and it adds a table prefix if there is one.
959 * All functions of this object which require a table name call this function
960 * themselves. Pass the canonical name to such functions. This is only needed
961 * when calling query() directly.
963 * @param string $name database table name
965 function tableName( $name ) {
967 if ( $this->mTablePrefix
!== '' ) {
968 if ( strpos( '.', $name ) === false ) {
969 $name = $this->mTablePrefix
. $name;
972 if ( isset( $wgSharedDB ) && 'user' == $name ) {
973 $name = $wgSharedDB . '.' . $name;
975 if( $name == 'group' ) {
976 $name = '`' . $name . '`';
982 * Fetch a number of table names into an array
983 * This is handy when you need to construct SQL for joins
986 * extract($dbr->tableNames('user','watchlist'));
987 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
988 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
990 function tableNames() {
991 $inArray = func_get_args();
993 foreach ( $inArray as $name ) {
994 $retVal[$name] = $this->tableName( $name );
1000 * Wrapper for addslashes()
1001 * @param string $s String to be slashed.
1002 * @return string slashed string.
1004 function strencode( $s ) {
1005 return addslashes( $s );
1009 * If it's a string, adds quotes and backslashes
1010 * Otherwise returns as-is
1012 function addQuotes( $s ) {
1013 if ( is_null( $s ) ) {
1016 # This will also quote numeric values. This should be harmless,
1017 # and protects against weird problems that occur when they really
1018 # _are_ strings such as article titles and string->number->string
1019 # conversion is not 1:1.
1020 $s = "'" . $this->strencode( $s ) . "'";
1026 * Returns an appropriately quoted sequence value for inserting a new row.
1027 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1028 * subclass will return an integer, and save the value for insertId()
1030 function nextSequenceValue( $seqName ) {
1036 * PostgreSQL doesn't have them and returns ""
1038 function useIndexClause( $index ) {
1039 return 'USE INDEX ('.$index.')';
1043 * REPLACE query wrapper
1044 * PostgreSQL simulates this with a DELETE followed by INSERT
1045 * $row is the row to insert, an associative array
1046 * $uniqueIndexes is an array of indexes. Each element may be either a
1047 * field name or an array of field names
1049 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1050 * However if you do this, you run the risk of encountering errors which wouldn't have
1053 * @todo migrate comment to phodocumentor format
1055 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1056 $table = $this->tableName( $table );
1059 if ( !is_array( reset( $rows ) ) ) {
1060 $rows = array( $rows );
1063 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1065 foreach ( $rows as $row ) {
1071 $sql .= '(' . $this->makeList( $row ) . ')';
1073 return $this->query( $sql, $fname );
1077 * DELETE where the condition is a join
1078 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1080 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1081 * join condition matches, set $conds='*'
1083 * DO NOT put the join condition in $conds
1085 * @param string $delTable The table to delete from.
1086 * @param string $joinTable The other table.
1087 * @param string $delVar The variable to join on, in the first table.
1088 * @param string $joinVar The variable to join on, in the second table.
1089 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1091 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1093 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1096 $delTable = $this->tableName( $delTable );
1097 $joinTable = $this->tableName( $joinTable );
1098 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1099 if ( $conds != '*' ) {
1100 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1103 return $this->query( $sql, $fname );
1107 * Returns the size of a text field, or -1 for "unlimited"
1109 function textFieldSize( $table, $field ) {
1110 $table = $this->tableName( $table );
1111 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1112 $res = $this->query( $sql, 'Database::textFieldSize' );
1113 $row = $this->fetchObject( $res );
1114 $this->freeResult( $res );
1116 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
1125 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1127 function lowPriorityOption() {
1128 return 'LOW_PRIORITY';
1132 * DELETE query wrapper
1134 * Use $conds == "*" to delete all rows
1136 function delete( $table, $conds, $fname = 'Database::delete' ) {
1138 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1140 $table = $this->tableName( $table );
1141 $sql = "DELETE FROM $table ";
1142 if ( $conds != '*' ) {
1143 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1145 return $this->query( $sql, $fname );
1149 * INSERT SELECT wrapper
1150 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1151 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1152 * $conds may be "*" to copy the whole table
1153 * srcTable may be an array of tables.
1155 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1156 $destTable = $this->tableName( $destTable );
1157 if( is_array( $srcTable ) ) {
1158 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1160 $srcTable = $this->tableName( $srcTable );
1162 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1163 ' SELECT ' . implode( ',', $varMap ) .
1165 if ( $conds != '*' ) {
1166 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1168 return $this->query( $sql, $fname );
1172 * Construct a LIMIT query with optional offset
1173 * This is used for query pages
1175 function limitResult($limit,$offset) {
1176 return ' LIMIT '.(is_numeric($offset)?
"{$offset},":"")."{$limit} ";
1180 * Returns an SQL expression for a simple conditional.
1183 * @param string $cond SQL expression which will result in a boolean value
1184 * @param string $trueVal SQL expression to return if true
1185 * @param string $falseVal SQL expression to return if false
1186 * @return string SQL fragment
1188 function conditional( $cond, $trueVal, $falseVal ) {
1189 return " IF($cond, $trueVal, $falseVal) ";
1193 * Determines if the last failure was due to a deadlock
1195 function wasDeadlock() {
1196 return $this->lastErrno() == 1213;
1200 * Perform a deadlock-prone transaction.
1202 * This function invokes a callback function to perform a set of write
1203 * queries. If a deadlock occurs during the processing, the transaction
1204 * will be rolled back and the callback function will be called again.
1207 * $dbw->deadlockLoop( callback, ... );
1209 * Extra arguments are passed through to the specified callback function.
1211 * Returns whatever the callback function returned on its successful,
1212 * iteration, or false on error, for example if the retry limit was
1215 function deadlockLoop() {
1216 $myFname = 'Database::deadlockLoop';
1218 $this->query( 'BEGIN', $myFname );
1219 $args = func_get_args();
1220 $function = array_shift( $args );
1221 $oldIgnore = $this->ignoreErrors( true );
1222 $tries = DEADLOCK_TRIES
;
1223 if ( is_array( $function ) ) {
1224 $fname = $function[0];
1229 $retVal = call_user_func_array( $function, $args );
1230 $error = $this->lastError();
1231 $errno = $this->lastErrno();
1232 $sql = $this->lastQuery();
1235 if ( $this->wasDeadlock() ) {
1237 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1239 $this->reportQueryError( $error, $errno, $sql, $fname );
1242 } while( $this->wasDeadlock() && --$tries > 0 );
1243 $this->ignoreErrors( $oldIgnore );
1244 if ( $tries <= 0 ) {
1245 $this->query( 'ROLLBACK', $myFname );
1246 $this->reportQueryError( $error, $errno, $sql, $fname );
1249 $this->query( 'COMMIT', $myFname );
1255 * Do a SELECT MASTER_POS_WAIT()
1257 * @param string $file the binlog file
1258 * @param string $pos the binlog position
1259 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1261 function masterPosWait( $file, $pos, $timeout ) {
1262 $fname = 'Database::masterPosWait';
1263 wfProfileIn( $fname );
1266 # Commit any open transactions
1267 $this->immediateCommit();
1269 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1270 $encFile = $this->strencode( $file );
1271 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1272 $res = $this->doQuery( $sql );
1273 if ( $res && $row = $this->fetchRow( $res ) ) {
1274 $this->freeResult( $res );
1282 * Get the position of the master from SHOW SLAVE STATUS
1284 function getSlavePos() {
1285 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1286 $row = $this->fetchObject( $res );
1288 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1290 return array( false, false );
1295 * Get the position of the master from SHOW MASTER STATUS
1297 function getMasterPos() {
1298 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1299 $row = $this->fetchObject( $res );
1301 return array( $row->File
, $row->Position
);
1303 return array( false, false );
1308 * Begin a transaction, or if a transaction has already started, continue it
1310 function begin( $fname = 'Database::begin' ) {
1311 if ( !$this->mTrxLevel
) {
1312 $this->immediateBegin( $fname );
1319 * End a transaction, or decrement the nest level if transactions are nested
1321 function commit( $fname = 'Database::commit' ) {
1322 if ( $this->mTrxLevel
) {
1325 if ( !$this->mTrxLevel
) {
1326 $this->immediateCommit( $fname );
1331 * Rollback a transaction
1333 function rollback( $fname = 'Database::rollback' ) {
1334 $this->query( 'ROLLBACK', $fname );
1335 $this->mTrxLevel
= 0;
1339 * Begin a transaction, committing any previously open transaction
1341 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1342 $this->query( 'BEGIN', $fname );
1343 $this->mTrxLevel
= 1;
1347 * Commit transaction, if one is open
1349 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1350 $this->query( 'COMMIT', $fname );
1351 $this->mTrxLevel
= 0;
1355 * Return MW-style timestamp used for MySQL schema
1357 function timestamp( $ts=0 ) {
1358 return wfTimestamp(TS_MW
,$ts);
1364 function &resultObject( &$result ) {
1365 if( empty( $result ) ) {
1368 return new ResultWrapper( $this, $result );
1373 * Return aggregated value alias
1375 function aggregateValue ($valuedata,$valuename='value') {
1380 * @return string wikitext of a link to the server software's web site
1382 function getSoftwareLink() {
1383 return "[http://www.mysql.com/ MySQL]";
1387 * @return string Version information from the database
1389 function getServerVersion() {
1390 return mysql_get_server_info();
1395 * Database abstraction object for mySQL
1396 * Inherit all methods and properties of Database::Database()
1398 * @package MediaWiki
1401 class DatabaseMysql
extends Database
{
1407 * Result wrapper for grabbing data queried by someone else
1409 * @package MediaWiki
1411 class ResultWrapper
{
1417 function ResultWrapper( $database, $result ) {
1418 $this->db
=& $database;
1419 $this->result
=& $result;
1425 function numRows() {
1426 return $this->db
->numRows( $this->result
);
1432 function &fetchObject() {
1433 return $this->db
->fetchObject( $this->result
);
1439 function &fetchRow() {
1440 return $this->db
->fetchRow( $this->result
);
1447 $this->db
->freeResult( $this->result
);
1448 unset( $this->result
);
1452 function seek( $row ) {
1453 $this->db
->dataSeek( $this->result
, $row );
1457 #------------------------------------------------------------------------------
1459 #------------------------------------------------------------------------------
1462 * Standard fail function, called by default when a connection cannot be
1464 * Displays the file cache if possible
1466 function wfEmergencyAbort( &$conn, $error ) {
1467 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1468 global $wgSitename, $wgServer;
1470 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1471 # Hard coding strings instead.
1473 $noconnect = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server. <br />
1475 $mainpage = 'Main Page';
1476 $searchdisabled = <<<EOT
1477 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1478 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1482 <!-- SiteSearch Google -->
1483 <FORM method=GET action=\"http://www.google.com/search\">
1484 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1485 <A HREF=\"http://www.google.com/\">
1486 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1487 border=\"0\" ALT=\"Google\"></A>
1490 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1491 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1493 <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 />
1494 <input type='hidden' name='ie' value='$2'>
1495 <input type='hidden' name='oe' value='$2'>
1499 <!-- SiteSearch Google -->";
1500 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1503 if( !headers_sent() ) {
1504 header( 'HTTP/1.0 500 Internal Server Error' );
1505 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1506 /* Don't cache error pages! They cause no end of trouble... */
1507 header( 'Cache-control: none' );
1508 header( 'Pragma: nocache' );
1510 $msg = wfGetSiteNotice();
1512 $msg = str_replace( '$1', $error, $noconnect );
1516 if($wgUseFileCache) {
1521 $t = Title
::newFromURL( $title );
1522 } elseif (@/**/$_REQUEST['search']) {
1523 $search = $_REQUEST['search'];
1524 echo $searchdisabled;
1525 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1526 $wgInputEncoding ), $googlesearch );
1529 $t = Title
::newFromText( $mainpage );
1533 $cache = new CacheManager( $t );
1534 if( $cache->isFileCached() ) {
1535 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1536 $cachederror . "</b></p>\n";
1538 $tag = '<div id="article">';
1539 $text = str_replace(
1542 $cache->fetchPageText() );