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
;
153 // Faster read-only access
154 if ( wfReadOnly() ) {
155 $this->mFlags |= DBO_PERSISTENT;
156 $this->mFlags &= ~DBO_TRX;
159 /** Get the default table prefix*/
160 if ( $tablePrefix == 'get from global' ) {
161 $this->mTablePrefix
= $wgDBprefix;
163 $this->mTablePrefix
= $tablePrefix;
167 $this->open( $server, $user, $password, $dbName );
173 * @param failFunction
176 function newFromParams( $server, $user, $password, $dbName,
177 $failFunction = false, $flags = 0 )
179 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
183 * Usually aborts on failure
184 * If the failFunction is set to a non-zero integer, returns success
186 function open( $server, $user, $password, $dbName ) {
187 # Test for missing mysql.so
188 # First try to load it
189 if (!@extension_loaded
('mysql')) {
193 # Otherwise we get a suppressed fatal error, which is very hard to track down
194 if ( !function_exists( 'mysql_connect' ) ) {
195 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
199 $this->mServer
= $server;
200 $this->mUser
= $user;
201 $this->mPassword
= $password;
202 $this->mDBname
= $dbName;
206 if ( $this->mFlags
& DBO_PERSISTENT
) {
207 @/**/$this->mConn
= mysql_pconnect( $server, $user, $password );
209 @/**/$this->mConn
= mysql_connect( $server, $user, $password );
212 if ( $dbName != '' ) {
213 if ( $this->mConn
!== false ) {
214 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
216 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
219 wfDebug( "DB connection error\n" );
220 wfDebug( "Server: $server, User: $user, Password: " .
221 substr( $password, 0, 3 ) . "...\n" );
226 $success = !!$this->mConn
;
230 $this->reportConnectionError();
233 $this->mOpened
= $success;
239 * Closes a database connection.
240 * if it is open : commits any open transactions
242 * @return bool operation success. true if already closed.
246 $this->mOpened
= false;
247 if ( $this->mConn
) {
248 if ( $this->trxLevel() ) {
249 $this->immediateCommit();
251 return mysql_close( $this->mConn
);
259 * @param string $msg error message ?
260 * @todo parameter $msg is not used
262 function reportConnectionError( $msg = '') {
263 if ( $this->mFailFunction
) {
264 if ( !is_int( $this->mFailFunction
) ) {
265 $ff = $this->mFailFunction
;
266 $ff( $this, mysql_error() );
269 wfEmergencyAbort( $this, mysql_error() );
274 * Usually aborts on failure
275 * If errors are explicitly ignored, returns success
277 function query( $sql, $fname = '', $tempIgnore = false ) {
278 global $wgProfiling, $wgCommandLineMode;
280 if ( $wgProfiling ) {
281 # generalizeSQL will probably cut down the query to reasonable
282 # logging size most of the time. The substr is really just a sanity check.
283 $profName = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
284 wfProfileIn( $profName );
287 $this->mLastQuery
= $sql;
289 # Add a comment for easy SHOW PROCESSLIST interpretation
291 $commentedSql = "/* $fname */ $sql";
293 $commentedSql = $sql;
296 # If DBO_TRX is set, start a transaction
297 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() && $sql != 'BEGIN' ) {
301 if ( $this->debug() ) {
302 $sqlx = substr( $sql, 0, 500 );
303 $sqlx = strtr($sqlx,"\t\n",' ');
304 wfDebug( "SQL: $sqlx\n" );
307 # Do the query and handle errors
308 $ret = $this->doQuery( $commentedSql );
309 if ( false === $ret ) {
310 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
313 if ( $wgProfiling ) {
314 wfProfileOut( $profName );
320 * The DBMS-dependent part of query()
321 * @param string $sql SQL query.
323 function doQuery( $sql ) {
324 if( $this->bufferResults() ) {
325 $ret = mysql_query( $sql, $this->mConn
);
327 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
336 * @param string $fname
337 * @param bool $tempIgnore
339 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
340 global $wgCommandLineMode, $wgFullyInitialised;
341 # Ignore errors during error handling to avoid infinite recursion
342 $ignore = $this->ignoreErrors( true );
344 if( $ignore ||
$tempIgnore ) {
345 wfDebug("SQL ERROR (ignored): " . $error . "\n");
347 $sql1line = str_replace( "\n", "\\n", $sql );
348 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
349 wfDebug("SQL ERROR: " . $error . "\n");
350 if ( $wgCommandLineMode ||
!$this->mOut ||
empty( $wgFullyInitialised ) ) {
351 $message = "A database error has occurred\n" .
353 "Function: $fname\n" .
354 "Error: $errno $error\n";
355 if ( !$wgCommandLineMode ) {
356 $message = nl2br( $message );
358 wfDebugDieBacktrace( $message );
360 // this calls wfAbruptExit()
361 $this->mOut
->databaseError( $fname, $sql, $error, $errno );
364 $this->ignoreErrors( $ignore );
369 * Intended to be compatible with the PEAR::DB wrapper functions.
370 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
372 * ? = scalar value, quoted as necessary
373 * ! = raw SQL bit (a function for instance)
374 * & = filename; reads the file and inserts as a blob
375 * (we don't use this though...)
377 function prepare( $sql, $func = 'Database::prepare' ) {
378 /* MySQL doesn't support prepared statements (yet), so just
379 pack up the query for reference. We'll manually replace
381 return array( 'query' => $sql, 'func' => $func );
384 function freePrepared( $prepared ) {
385 /* No-op for MySQL */
389 * Execute a prepared query with the various arguments
390 * @param string $prepared the prepared sql
391 * @param mixed $args Either an array here, or put scalars as varargs
393 function execute( $prepared, $args = null ) {
394 if( !is_array( $args ) ) {
396 $args = func_get_args();
397 array_shift( $args );
399 $sql = $this->fillPrepared( $prepared['query'], $args );
400 return $this->query( $sql, $prepared['func'] );
404 * Prepare & execute an SQL statement, quoting and inserting arguments
405 * in the appropriate places.
406 * @param string $query
407 * @param string $args (default null)
409 function safeQuery( $query, $args = null ) {
410 $prepared = $this->prepare( $query, 'Database::safeQuery' );
411 if( !is_array( $args ) ) {
413 $args = func_get_args();
414 array_shift( $args );
416 $retval = $this->execute( $prepared, $args );
417 $this->freePrepared( $prepared );
422 * For faking prepared SQL statements on DBs that don't support
424 * @param string $preparedSql - a 'preparable' SQL statement
425 * @param array $args - array of arguments to fill it with
426 * @return string executable SQL
428 function fillPrepared( $preparedQuery, $args ) {
431 $this->preparedArgs
=& $args;
432 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
433 array( &$this, 'fillPreparedArg' ), $preparedQuery );
437 * preg_callback func for fillPrepared()
438 * The arguments should be in $this->preparedArgs and must not be touched
439 * while we're doing this.
441 * @param array $matches
445 function fillPreparedArg( $matches ) {
446 switch( $matches[1] ) {
447 case '\\?': return '?';
448 case '\\!': return '!';
449 case '\\&': return '&';
451 list( $n, $arg ) = each( $this->preparedArgs
);
452 switch( $matches[1] ) {
453 case '?': return $this->addQuotes( $arg );
454 case '!': return $arg;
456 # return $this->addQuotes( file_get_contents( $arg ) );
457 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
459 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
464 * @param mixed $res A SQL result
467 * Free a result object
469 function freeResult( $res ) {
470 if ( !@/**/mysql_free_result( $res ) ) {
471 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
476 * Fetch the next row from the given result object, in object form
478 function fetchObject( $res ) {
479 @/**/$row = mysql_fetch_object( $res );
480 if( mysql_errno() ) {
481 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
487 * Fetch the next row from the given result object
490 function fetchRow( $res ) {
491 @/**/$row = mysql_fetch_array( $res );
492 if (mysql_errno() ) {
493 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
499 * Get the number of rows in a result object
501 function numRows( $res ) {
502 @/**/$n = mysql_num_rows( $res );
503 if( mysql_errno() ) {
504 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
510 * Get the number of fields in a result object
511 * See documentation for mysql_num_fields()
513 function numFields( $res ) { return mysql_num_fields( $res ); }
516 * Get a field name in a result object
517 * See documentation for mysql_field_name()
519 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
522 * Get the inserted value of an auto-increment row
524 * The value inserted should be fetched from nextSequenceValue()
527 * $id = $dbw->nextSequenceValue('page_page_id_seq');
528 * $dbw->insert('page',array('page_id' => $id));
529 * $id = $dbw->insertId();
531 function insertId() { return mysql_insert_id( $this->mConn
); }
534 * Change the position of the cursor in a result object
535 * See mysql_data_seek()
537 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
540 * Get the last error number
543 function lastErrno() {
544 if ( $this->mConn
) {
545 return mysql_errno( $this->mConn
);
547 return mysql_errno();
552 * Get a description of the last error
553 * See mysql_error() for more details
555 function lastError() {
556 if ( $this->mConn
) {
557 $error = mysql_error( $this->mConn
);
559 $error = mysql_error();
562 $error .= ' (' . $this->mServer
. ')';
567 * Get the number of rows affected by the last write query
568 * See mysql_affected_rows() for more details
570 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
571 /**#@-*/ // end of template : @param $result
574 * Simple UPDATE wrapper
575 * Usually aborts on failure
576 * If errors are explicitly ignored, returns success
578 * This function exists for historical reasons, Database::update() has a more standard
579 * calling convention and feature set
581 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
583 $table = $this->tableName( $table );
584 $sql = "UPDATE $table SET $var = '" .
585 $this->strencode( $value ) . "' WHERE ($cond)";
586 return !!$this->query( $sql, DB_MASTER
, $fname );
590 * Simple SELECT wrapper, returns a single field, input must be encoded
591 * Usually aborts on failure
592 * If errors are explicitly ignored, returns FALSE on failure
594 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
595 if ( !is_array( $options ) ) {
596 $options = array( $options );
598 $options['LIMIT'] = 1;
600 $res = $this->select( $table, $var, $cond, $fname, $options );
601 if ( $res === false ||
!$this->numRows( $res ) ) {
604 $row = $this->fetchRow( $res );
605 if ( $row !== false ) {
606 $this->freeResult( $res );
614 * Returns an optional USE INDEX clause to go after the table, and a
615 * string to go at the end of the query
617 function makeSelectOptions( $options ) {
618 if ( !is_array( $options ) ) {
619 $options = array( $options );
624 if ( isset( $options['ORDER BY'] ) ) {
625 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
627 if ( isset( $options['LIMIT'] ) ) {
628 $tailOpts .= " LIMIT {$options['LIMIT']}";
631 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
632 $tailOpts .= ' FOR UPDATE';
635 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
636 $tailOpts .= ' LOCK IN SHARE MODE';
639 if ( isset( $options['USE INDEX'] ) ) {
640 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
644 return array( $useIndex, $tailOpts );
650 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
652 if( is_array( $vars ) ) {
653 $vars = implode( ',', $vars );
655 if( is_array( $table ) ) {
656 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
657 } elseif ($table!='') {
658 $from = ' FROM ' .$this->tableName( $table );
663 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
665 if( !empty( $conds ) ) {
666 if ( is_array( $conds ) ) {
667 $conds = $this->makeList( $conds, LIST_AND
);
669 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
671 $sql = "SELECT $vars $from $useIndex $tailOpts";
673 return $this->query( $sql, $fname );
677 * Single row SELECT wrapper
678 * Aborts or returns FALSE on error
680 * $vars: the selected variables
681 * $conds: a condition map, terms are ANDed together.
682 * Items with numeric keys are taken to be literal conditions
683 * Takes an array of selected variables, and a condition map, which is ANDed
684 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
685 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
686 * $obj- >page_id is the ID of the Astronomy article
688 * @todo migrate documentation to phpdocumentor format
690 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
691 $options['LIMIT'] = 1;
692 $res = $this->select( $table, $vars, $conds, $fname, $options );
693 if ( $res === false ||
!$this->numRows( $res ) ) {
696 $obj = $this->fetchObject( $res );
697 $this->freeResult( $res );
703 * Removes most variables from an SQL query and replaces them with X or N for numbers.
704 * It's only slightly flawed. Don't use for anything important.
706 * @param string $sql A SQL Query
709 function generalizeSQL( $sql ) {
710 # This does the same as the regexp below would do, but in such a way
711 # as to avoid crashing php on some large strings.
712 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
714 $sql = str_replace ( "\\\\", '', $sql);
715 $sql = str_replace ( "\\'", '', $sql);
716 $sql = str_replace ( "\\\"", '', $sql);
717 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
718 $sql = preg_replace ('/".*"/s', "'X'", $sql);
720 # All newlines, tabs, etc replaced by single space
721 $sql = preg_replace ( "/\s+/", ' ', $sql);
724 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
730 * Determines whether a field exists in a table
731 * Usually aborts on failure
732 * If errors are explicitly ignored, returns NULL on failure
734 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
735 $table = $this->tableName( $table );
736 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE
, $fname );
743 while ( $row = $this->fetchObject( $res ) ) {
744 if ( $row->Field
== $field ) {
753 * Determines whether an index exists
754 * Usually aborts on failure
755 * If errors are explicitly ignored, returns NULL on failure
757 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
758 $info = $this->indexInfo( $table, $index, $fname );
759 if ( is_null( $info ) ) {
762 return $info !== false;
768 * Get information about an index into an object
769 * Returns false if the index does not exist
771 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
772 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
773 # SHOW INDEX should work for 3.x and up:
774 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
775 $table = $this->tableName( $table );
776 $sql = 'SHOW INDEX FROM '.$table;
777 $res = $this->query( $sql, $fname );
782 while ( $row = $this->fetchObject( $res ) ) {
783 if ( $row->Key_name
== $index ) {
791 * Query whether a given table exists
793 function tableExists( $table ) {
794 $table = $this->tableName( $table );
795 $old = $this->ignoreErrors( true );
796 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
797 $this->ignoreErrors( $old );
799 $this->freeResult( $res );
807 * mysql_fetch_field() wrapper
808 * Returns false if the field doesn't exist
813 function fieldInfo( $table, $field ) {
814 $table = $this->tableName( $table );
815 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
816 $n = mysql_num_fields( $res );
817 for( $i = 0; $i < $n; $i++
) {
818 $meta = mysql_fetch_field( $res, $i );
819 if( $field == $meta->name
) {
827 * mysql_field_type() wrapper
829 function fieldType( $res, $index ) {
830 return mysql_field_type( $res, $index );
834 * Determines if a given index is unique
836 function indexUnique( $table, $index ) {
837 $indexInfo = $this->indexInfo( $table, $index );
841 return !$indexInfo->Non_unique
;
845 * INSERT wrapper, inserts an array into a table
847 * $a may be a single associative array, or an array of these with numeric keys, for
850 * Usually aborts on failure
851 * If errors are explicitly ignored, returns success
853 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
854 # No rows to insert, easy just return now
855 if ( !count( $a ) ) {
859 $table = $this->tableName( $table );
860 if ( !is_array( $options ) ) {
861 $options = array( $options );
863 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
865 $keys = array_keys( $a[0] );
868 $keys = array_keys( $a );
871 $sql = 'INSERT ' . implode( ' ', $options ) .
872 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
876 foreach ( $a as $row ) {
882 $sql .= '(' . $this->makeList( $row ) . ')';
885 $sql .= '(' . $this->makeList( $a ) . ')';
887 return !!$this->query( $sql, $fname );
891 * UPDATE wrapper, takes a condition array and a SET array
893 function update( $table, $values, $conds, $fname = 'Database::update' ) {
894 $table = $this->tableName( $table );
895 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET
);
896 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
897 $this->query( $sql, $fname );
901 * Makes a wfStrencoded list from an array
902 * $mode: LIST_COMMA - comma separated, no field names
903 * LIST_AND - ANDed WHERE clause (without the WHERE)
904 * LIST_SET - comma separated with field names, like a SET clause
905 * LIST_NAMES - comma separated field names
907 function makeList( $a, $mode = LIST_COMMA
) {
908 if ( !is_array( $a ) ) {
909 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
914 foreach ( $a as $field => $value ) {
916 if ( $mode == LIST_AND
) {
924 if ( $mode == LIST_AND
&& is_numeric( $field ) ) {
926 } elseif ( $mode == LIST_AND
&& is_array ($value) ) {
927 $list .= $field." IN (".$this->makeList($value).") ";
929 if ( $mode == LIST_AND ||
$mode == LIST_SET
) {
932 $list .= ($mode==LIST_NAMES?
$value:$this->addQuotes( $value ));
939 * Change the current database
941 function selectDB( $db ) {
942 $this->mDBname
= $db;
943 return mysql_select_db( $db, $this->mConn
);
947 * Starts a timer which will kill the DB thread after $timeout seconds
949 function startTimer( $timeout ) {
951 if( function_exists( 'mysql_thread_id' ) ) {
952 # This will kill the query if it's still running after $timeout seconds.
953 $tid = mysql_thread_id( $this->mConn
);
954 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
959 * Stop a timer started by startTimer()
960 * Currently unimplemented.
963 function stopTimer() { }
966 * Format a table name ready for use in constructing an SQL query
968 * This does two important things: it quotes table names which as necessary,
969 * and it adds a table prefix if there is one.
971 * All functions of this object which require a table name call this function
972 * themselves. Pass the canonical name to such functions. This is only needed
973 * when calling query() directly.
975 * @param string $name database table name
977 function tableName( $name ) {
979 # Skip quoted literals
980 if ( $name{0} != '`' ) {
981 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
982 $name = "{$this->mTablePrefix}$name";
984 if ( isset( $wgSharedDB ) && 'user' == $name ) {
985 $name = "`$wgSharedDB`.`$name`";
995 * Fetch a number of table names into an array
996 * This is handy when you need to construct SQL for joins
999 * extract($dbr->tableNames('user','watchlist'));
1000 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1001 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1003 function tableNames() {
1004 $inArray = func_get_args();
1006 foreach ( $inArray as $name ) {
1007 $retVal[$name] = $this->tableName( $name );
1013 * Wrapper for addslashes()
1014 * @param string $s String to be slashed.
1015 * @return string slashed string.
1017 function strencode( $s ) {
1018 return addslashes( $s );
1022 * If it's a string, adds quotes and backslashes
1023 * Otherwise returns as-is
1025 function addQuotes( $s ) {
1026 if ( is_null( $s ) ) {
1029 # This will also quote numeric values. This should be harmless,
1030 # and protects against weird problems that occur when they really
1031 # _are_ strings such as article titles and string->number->string
1032 # conversion is not 1:1.
1033 $s = "'" . $this->strencode( $s ) . "'";
1039 * Returns an appropriately quoted sequence value for inserting a new row.
1040 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1041 * subclass will return an integer, and save the value for insertId()
1043 function nextSequenceValue( $seqName ) {
1049 * PostgreSQL doesn't have them and returns ""
1051 function useIndexClause( $index ) {
1052 return 'USE INDEX ('.$index.')';
1056 * REPLACE query wrapper
1057 * PostgreSQL simulates this with a DELETE followed by INSERT
1058 * $row is the row to insert, an associative array
1059 * $uniqueIndexes is an array of indexes. Each element may be either a
1060 * field name or an array of field names
1062 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1063 * However if you do this, you run the risk of encountering errors which wouldn't have
1066 * @todo migrate comment to phodocumentor format
1068 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1069 $table = $this->tableName( $table );
1072 if ( !is_array( reset( $rows ) ) ) {
1073 $rows = array( $rows );
1076 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1078 foreach ( $rows as $row ) {
1084 $sql .= '(' . $this->makeList( $row ) . ')';
1086 return $this->query( $sql, $fname );
1090 * DELETE where the condition is a join
1091 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1093 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1094 * join condition matches, set $conds='*'
1096 * DO NOT put the join condition in $conds
1098 * @param string $delTable The table to delete from.
1099 * @param string $joinTable The other table.
1100 * @param string $delVar The variable to join on, in the first table.
1101 * @param string $joinVar The variable to join on, in the second table.
1102 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1104 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1106 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1109 $delTable = $this->tableName( $delTable );
1110 $joinTable = $this->tableName( $joinTable );
1111 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1112 if ( $conds != '*' ) {
1113 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1116 return $this->query( $sql, $fname );
1120 * Returns the size of a text field, or -1 for "unlimited"
1122 function textFieldSize( $table, $field ) {
1123 $table = $this->tableName( $table );
1124 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1125 $res = $this->query( $sql, 'Database::textFieldSize' );
1126 $row = $this->fetchObject( $res );
1127 $this->freeResult( $res );
1129 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
1138 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1140 function lowPriorityOption() {
1141 return 'LOW_PRIORITY';
1145 * DELETE query wrapper
1147 * Use $conds == "*" to delete all rows
1149 function delete( $table, $conds, $fname = 'Database::delete' ) {
1151 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1153 $table = $this->tableName( $table );
1154 $sql = "DELETE FROM $table ";
1155 if ( $conds != '*' ) {
1156 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1158 return $this->query( $sql, $fname );
1162 * INSERT SELECT wrapper
1163 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1164 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1165 * $conds may be "*" to copy the whole table
1166 * srcTable may be an array of tables.
1168 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1169 $destTable = $this->tableName( $destTable );
1170 if( is_array( $srcTable ) ) {
1171 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1173 $srcTable = $this->tableName( $srcTable );
1175 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1176 ' SELECT ' . implode( ',', $varMap ) .
1178 if ( $conds != '*' ) {
1179 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1181 return $this->query( $sql, $fname );
1185 * Construct a LIMIT query with optional offset
1186 * This is used for query pages
1188 function limitResult($limit,$offset) {
1189 return ' LIMIT '.(is_numeric($offset)?
"{$offset},":"")."{$limit} ";
1193 * Returns an SQL expression for a simple conditional.
1196 * @param string $cond SQL expression which will result in a boolean value
1197 * @param string $trueVal SQL expression to return if true
1198 * @param string $falseVal SQL expression to return if false
1199 * @return string SQL fragment
1201 function conditional( $cond, $trueVal, $falseVal ) {
1202 return " IF($cond, $trueVal, $falseVal) ";
1206 * Determines if the last failure was due to a deadlock
1208 function wasDeadlock() {
1209 return $this->lastErrno() == 1213;
1213 * Perform a deadlock-prone transaction.
1215 * This function invokes a callback function to perform a set of write
1216 * queries. If a deadlock occurs during the processing, the transaction
1217 * will be rolled back and the callback function will be called again.
1220 * $dbw->deadlockLoop( callback, ... );
1222 * Extra arguments are passed through to the specified callback function.
1224 * Returns whatever the callback function returned on its successful,
1225 * iteration, or false on error, for example if the retry limit was
1228 function deadlockLoop() {
1229 $myFname = 'Database::deadlockLoop';
1231 $this->query( 'BEGIN', $myFname );
1232 $args = func_get_args();
1233 $function = array_shift( $args );
1234 $oldIgnore = $this->ignoreErrors( true );
1235 $tries = DEADLOCK_TRIES
;
1236 if ( is_array( $function ) ) {
1237 $fname = $function[0];
1242 $retVal = call_user_func_array( $function, $args );
1243 $error = $this->lastError();
1244 $errno = $this->lastErrno();
1245 $sql = $this->lastQuery();
1248 if ( $this->wasDeadlock() ) {
1250 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1252 $this->reportQueryError( $error, $errno, $sql, $fname );
1255 } while( $this->wasDeadlock() && --$tries > 0 );
1256 $this->ignoreErrors( $oldIgnore );
1257 if ( $tries <= 0 ) {
1258 $this->query( 'ROLLBACK', $myFname );
1259 $this->reportQueryError( $error, $errno, $sql, $fname );
1262 $this->query( 'COMMIT', $myFname );
1268 * Do a SELECT MASTER_POS_WAIT()
1270 * @param string $file the binlog file
1271 * @param string $pos the binlog position
1272 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1274 function masterPosWait( $file, $pos, $timeout ) {
1275 $fname = 'Database::masterPosWait';
1276 wfProfileIn( $fname );
1279 # Commit any open transactions
1280 $this->immediateCommit();
1282 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1283 $encFile = $this->strencode( $file );
1284 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1285 $res = $this->doQuery( $sql );
1286 if ( $res && $row = $this->fetchRow( $res ) ) {
1287 $this->freeResult( $res );
1295 * Get the position of the master from SHOW SLAVE STATUS
1297 function getSlavePos() {
1298 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1299 $row = $this->fetchObject( $res );
1301 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1303 return array( false, false );
1308 * Get the position of the master from SHOW MASTER STATUS
1310 function getMasterPos() {
1311 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1312 $row = $this->fetchObject( $res );
1314 return array( $row->File
, $row->Position
);
1316 return array( false, false );
1321 * Begin a transaction, or if a transaction has already started, continue it
1323 function begin( $fname = 'Database::begin' ) {
1324 if ( !$this->mTrxLevel
) {
1325 $this->immediateBegin( $fname );
1332 * End a transaction, or decrement the nest level if transactions are nested
1334 function commit( $fname = 'Database::commit' ) {
1335 if ( $this->mTrxLevel
) {
1338 if ( !$this->mTrxLevel
) {
1339 $this->immediateCommit( $fname );
1344 * Rollback a transaction
1346 function rollback( $fname = 'Database::rollback' ) {
1347 $this->query( 'ROLLBACK', $fname );
1348 $this->mTrxLevel
= 0;
1352 * Begin a transaction, committing any previously open transaction
1354 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1355 $this->query( 'BEGIN', $fname );
1356 $this->mTrxLevel
= 1;
1360 * Commit transaction, if one is open
1362 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1363 $this->query( 'COMMIT', $fname );
1364 $this->mTrxLevel
= 0;
1368 * Return MW-style timestamp used for MySQL schema
1370 function timestamp( $ts=0 ) {
1371 return wfTimestamp(TS_MW
,$ts);
1377 function &resultObject( &$result ) {
1378 if( empty( $result ) ) {
1381 return new ResultWrapper( $this, $result );
1386 * Return aggregated value alias
1388 function aggregateValue ($valuedata,$valuename='value') {
1393 * @return string wikitext of a link to the server software's web site
1395 function getSoftwareLink() {
1396 return "[http://www.mysql.com/ MySQL]";
1400 * @return string Version information from the database
1402 function getServerVersion() {
1403 return mysql_get_server_info();
1408 * Database abstraction object for mySQL
1409 * Inherit all methods and properties of Database::Database()
1411 * @package MediaWiki
1414 class DatabaseMysql
extends Database
{
1420 * Result wrapper for grabbing data queried by someone else
1422 * @package MediaWiki
1424 class ResultWrapper
{
1430 function ResultWrapper( $database, $result ) {
1431 $this->db
=& $database;
1432 $this->result
=& $result;
1438 function numRows() {
1439 return $this->db
->numRows( $this->result
);
1445 function &fetchObject() {
1446 return $this->db
->fetchObject( $this->result
);
1452 function &fetchRow() {
1453 return $this->db
->fetchRow( $this->result
);
1460 $this->db
->freeResult( $this->result
);
1461 unset( $this->result
);
1465 function seek( $row ) {
1466 $this->db
->dataSeek( $this->result
, $row );
1470 #------------------------------------------------------------------------------
1472 #------------------------------------------------------------------------------
1475 * Standard fail function, called by default when a connection cannot be
1477 * Displays the file cache if possible
1479 function wfEmergencyAbort( &$conn, $error ) {
1480 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1481 global $wgSitename, $wgServer;
1483 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1484 # Hard coding strings instead.
1486 $noconnect = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server. <br />
1488 $mainpage = 'Main Page';
1489 $searchdisabled = <<<EOT
1490 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1491 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1495 <!-- SiteSearch Google -->
1496 <FORM method=GET action=\"http://www.google.com/search\">
1497 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1498 <A HREF=\"http://www.google.com/\">
1499 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1500 border=\"0\" ALT=\"Google\"></A>
1503 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1504 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1506 <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 />
1507 <input type='hidden' name='ie' value='$2'>
1508 <input type='hidden' name='oe' value='$2'>
1512 <!-- SiteSearch Google -->";
1513 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1516 if( !headers_sent() ) {
1517 header( 'HTTP/1.0 500 Internal Server Error' );
1518 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1519 /* Don't cache error pages! They cause no end of trouble... */
1520 header( 'Cache-control: none' );
1521 header( 'Pragma: nocache' );
1523 $msg = wfGetSiteNotice();
1525 $msg = str_replace( '$1', $error, $noconnect );
1529 if($wgUseFileCache) {
1534 $t = Title
::newFromURL( $title );
1535 } elseif (@/**/$_REQUEST['search']) {
1536 $search = $_REQUEST['search'];
1537 echo $searchdisabled;
1538 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1539 $wgInputEncoding ), $googlesearch );
1542 $t = Title
::newFromText( $mainpage );
1546 $cache = new CacheManager( $t );
1547 if( $cache->isFileCached() ) {
1548 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1549 $cachederror . "</b></p>\n";
1551 $tag = '<div id="article">';
1552 $text = str_replace(
1555 $cache->fetchPageText() );