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 );
310 # Try reconnecting if the connection was lost
311 if ( false === $ret && $this->lastErrno() == 2013 ) {
312 # Transaction is gone, like it or not
313 $this->mTrxLevel
= 0;
314 wfDebug( "Connection lost, reconnecting...\n" );
315 if ( $this->ping() ) {
316 wfDebug( "Reconnected\n" );
317 $ret = $this->doQuery( $commentedSql );
319 wfDebug( "Failed\n" );
323 if ( false === $ret ) {
324 # Automatic reconnect
325 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
328 if ( $wgProfiling ) {
329 wfProfileOut( $profName );
335 * The DBMS-dependent part of query()
336 * @param string $sql SQL query.
338 function doQuery( $sql ) {
339 if( $this->bufferResults() ) {
340 $ret = mysql_query( $sql, $this->mConn
);
342 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
351 * @param string $fname
352 * @param bool $tempIgnore
354 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
355 global $wgCommandLineMode, $wgFullyInitialised;
356 # Ignore errors during error handling to avoid infinite recursion
357 $ignore = $this->ignoreErrors( true );
359 if( $ignore ||
$tempIgnore ) {
360 wfDebug("SQL ERROR (ignored): " . $error . "\n");
362 $sql1line = str_replace( "\n", "\\n", $sql );
363 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
364 wfDebug("SQL ERROR: " . $error . "\n");
365 if ( $wgCommandLineMode ||
!$this->mOut ||
empty( $wgFullyInitialised ) ) {
366 $message = "A database error has occurred\n" .
368 "Function: $fname\n" .
369 "Error: $errno $error\n";
370 if ( !$wgCommandLineMode ) {
371 $message = nl2br( $message );
373 wfDebugDieBacktrace( $message );
375 // this calls wfAbruptExit()
376 $this->mOut
->databaseError( $fname, $sql, $error, $errno );
379 $this->ignoreErrors( $ignore );
384 * Intended to be compatible with the PEAR::DB wrapper functions.
385 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
387 * ? = scalar value, quoted as necessary
388 * ! = raw SQL bit (a function for instance)
389 * & = filename; reads the file and inserts as a blob
390 * (we don't use this though...)
392 function prepare( $sql, $func = 'Database::prepare' ) {
393 /* MySQL doesn't support prepared statements (yet), so just
394 pack up the query for reference. We'll manually replace
396 return array( 'query' => $sql, 'func' => $func );
399 function freePrepared( $prepared ) {
400 /* No-op for MySQL */
404 * Execute a prepared query with the various arguments
405 * @param string $prepared the prepared sql
406 * @param mixed $args Either an array here, or put scalars as varargs
408 function execute( $prepared, $args = null ) {
409 if( !is_array( $args ) ) {
411 $args = func_get_args();
412 array_shift( $args );
414 $sql = $this->fillPrepared( $prepared['query'], $args );
415 return $this->query( $sql, $prepared['func'] );
419 * Prepare & execute an SQL statement, quoting and inserting arguments
420 * in the appropriate places.
421 * @param string $query
422 * @param string $args (default null)
424 function safeQuery( $query, $args = null ) {
425 $prepared = $this->prepare( $query, 'Database::safeQuery' );
426 if( !is_array( $args ) ) {
428 $args = func_get_args();
429 array_shift( $args );
431 $retval = $this->execute( $prepared, $args );
432 $this->freePrepared( $prepared );
437 * For faking prepared SQL statements on DBs that don't support
439 * @param string $preparedSql - a 'preparable' SQL statement
440 * @param array $args - array of arguments to fill it with
441 * @return string executable SQL
443 function fillPrepared( $preparedQuery, $args ) {
446 $this->preparedArgs
=& $args;
447 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
448 array( &$this, 'fillPreparedArg' ), $preparedQuery );
452 * preg_callback func for fillPrepared()
453 * The arguments should be in $this->preparedArgs and must not be touched
454 * while we're doing this.
456 * @param array $matches
460 function fillPreparedArg( $matches ) {
461 switch( $matches[1] ) {
462 case '\\?': return '?';
463 case '\\!': return '!';
464 case '\\&': return '&';
466 list( $n, $arg ) = each( $this->preparedArgs
);
467 switch( $matches[1] ) {
468 case '?': return $this->addQuotes( $arg );
469 case '!': return $arg;
471 # return $this->addQuotes( file_get_contents( $arg ) );
472 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
474 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
479 * @param mixed $res A SQL result
482 * Free a result object
484 function freeResult( $res ) {
485 if ( !@/**/mysql_free_result( $res ) ) {
486 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
491 * Fetch the next row from the given result object, in object form
493 function fetchObject( $res ) {
494 @/**/$row = mysql_fetch_object( $res );
495 if( mysql_errno() ) {
496 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
502 * Fetch the next row from the given result object
505 function fetchRow( $res ) {
506 @/**/$row = mysql_fetch_array( $res );
507 if (mysql_errno() ) {
508 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
514 * Get the number of rows in a result object
516 function numRows( $res ) {
517 @/**/$n = mysql_num_rows( $res );
518 if( mysql_errno() ) {
519 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
525 * Get the number of fields in a result object
526 * See documentation for mysql_num_fields()
528 function numFields( $res ) { return mysql_num_fields( $res ); }
531 * Get a field name in a result object
532 * See documentation for mysql_field_name()
534 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
537 * Get the inserted value of an auto-increment row
539 * The value inserted should be fetched from nextSequenceValue()
542 * $id = $dbw->nextSequenceValue('page_page_id_seq');
543 * $dbw->insert('page',array('page_id' => $id));
544 * $id = $dbw->insertId();
546 function insertId() { return mysql_insert_id( $this->mConn
); }
549 * Change the position of the cursor in a result object
550 * See mysql_data_seek()
552 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
555 * Get the last error number
558 function lastErrno() {
559 if ( $this->mConn
) {
560 return mysql_errno( $this->mConn
);
562 return mysql_errno();
567 * Get a description of the last error
568 * See mysql_error() for more details
570 function lastError() {
571 if ( $this->mConn
) {
572 $error = mysql_error( $this->mConn
);
574 $error = mysql_error();
577 $error .= ' (' . $this->mServer
. ')';
582 * Get the number of rows affected by the last write query
583 * See mysql_affected_rows() for more details
585 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
586 /**#@-*/ // end of template : @param $result
589 * Simple UPDATE wrapper
590 * Usually aborts on failure
591 * If errors are explicitly ignored, returns success
593 * This function exists for historical reasons, Database::update() has a more standard
594 * calling convention and feature set
596 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
598 $table = $this->tableName( $table );
599 $sql = "UPDATE $table SET $var = '" .
600 $this->strencode( $value ) . "' WHERE ($cond)";
601 return !!$this->query( $sql, DB_MASTER
, $fname );
605 * Simple SELECT wrapper, returns a single field, input must be encoded
606 * Usually aborts on failure
607 * If errors are explicitly ignored, returns FALSE on failure
609 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
610 if ( !is_array( $options ) ) {
611 $options = array( $options );
613 $options['LIMIT'] = 1;
615 $res = $this->select( $table, $var, $cond, $fname, $options );
616 if ( $res === false ||
!$this->numRows( $res ) ) {
619 $row = $this->fetchRow( $res );
620 if ( $row !== false ) {
621 $this->freeResult( $res );
629 * Returns an optional USE INDEX clause to go after the table, and a
630 * string to go at the end of the query
632 function makeSelectOptions( $options ) {
633 if ( !is_array( $options ) ) {
634 $options = array( $options );
639 if ( isset( $options['ORDER BY'] ) ) {
640 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
642 if ( isset( $options['LIMIT'] ) ) {
643 $tailOpts .= " LIMIT {$options['LIMIT']}";
646 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
647 $tailOpts .= ' FOR UPDATE';
650 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
651 $tailOpts .= ' LOCK IN SHARE MODE';
654 if ( isset( $options['USE INDEX'] ) ) {
655 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
659 return array( $useIndex, $tailOpts );
665 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
667 if( is_array( $vars ) ) {
668 $vars = implode( ',', $vars );
670 if( is_array( $table ) ) {
671 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
672 } elseif ($table!='') {
673 $from = ' FROM ' .$this->tableName( $table );
678 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
680 if( !empty( $conds ) ) {
681 if ( is_array( $conds ) ) {
682 $conds = $this->makeList( $conds, LIST_AND
);
684 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
686 $sql = "SELECT $vars $from $useIndex $tailOpts";
688 return $this->query( $sql, $fname );
692 * Single row SELECT wrapper
693 * Aborts or returns FALSE on error
695 * $vars: the selected variables
696 * $conds: a condition map, terms are ANDed together.
697 * Items with numeric keys are taken to be literal conditions
698 * Takes an array of selected variables, and a condition map, which is ANDed
699 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
700 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
701 * $obj- >page_id is the ID of the Astronomy article
703 * @todo migrate documentation to phpdocumentor format
705 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
706 $options['LIMIT'] = 1;
707 $res = $this->select( $table, $vars, $conds, $fname, $options );
708 if ( $res === false ||
!$this->numRows( $res ) ) {
711 $obj = $this->fetchObject( $res );
712 $this->freeResult( $res );
718 * Removes most variables from an SQL query and replaces them with X or N for numbers.
719 * It's only slightly flawed. Don't use for anything important.
721 * @param string $sql A SQL Query
724 function generalizeSQL( $sql ) {
725 # This does the same as the regexp below would do, but in such a way
726 # as to avoid crashing php on some large strings.
727 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
729 $sql = str_replace ( "\\\\", '', $sql);
730 $sql = str_replace ( "\\'", '', $sql);
731 $sql = str_replace ( "\\\"", '', $sql);
732 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
733 $sql = preg_replace ('/".*"/s', "'X'", $sql);
735 # All newlines, tabs, etc replaced by single space
736 $sql = preg_replace ( "/\s+/", ' ', $sql);
739 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
745 * Determines whether a field exists in a table
746 * Usually aborts on failure
747 * If errors are explicitly ignored, returns NULL on failure
749 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
750 $table = $this->tableName( $table );
751 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE
, $fname );
758 while ( $row = $this->fetchObject( $res ) ) {
759 if ( $row->Field
== $field ) {
768 * Determines whether an index exists
769 * Usually aborts on failure
770 * If errors are explicitly ignored, returns NULL on failure
772 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
773 $info = $this->indexInfo( $table, $index, $fname );
774 if ( is_null( $info ) ) {
777 return $info !== false;
783 * Get information about an index into an object
784 * Returns false if the index does not exist
786 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
787 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
788 # SHOW INDEX should work for 3.x and up:
789 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
790 $table = $this->tableName( $table );
791 $sql = 'SHOW INDEX FROM '.$table;
792 $res = $this->query( $sql, $fname );
797 while ( $row = $this->fetchObject( $res ) ) {
798 if ( $row->Key_name
== $index ) {
806 * Query whether a given table exists
808 function tableExists( $table ) {
809 $table = $this->tableName( $table );
810 $old = $this->ignoreErrors( true );
811 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
812 $this->ignoreErrors( $old );
814 $this->freeResult( $res );
822 * mysql_fetch_field() wrapper
823 * Returns false if the field doesn't exist
828 function fieldInfo( $table, $field ) {
829 $table = $this->tableName( $table );
830 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
831 $n = mysql_num_fields( $res );
832 for( $i = 0; $i < $n; $i++
) {
833 $meta = mysql_fetch_field( $res, $i );
834 if( $field == $meta->name
) {
842 * mysql_field_type() wrapper
844 function fieldType( $res, $index ) {
845 return mysql_field_type( $res, $index );
849 * Determines if a given index is unique
851 function indexUnique( $table, $index ) {
852 $indexInfo = $this->indexInfo( $table, $index );
856 return !$indexInfo->Non_unique
;
860 * INSERT wrapper, inserts an array into a table
862 * $a may be a single associative array, or an array of these with numeric keys, for
865 * Usually aborts on failure
866 * If errors are explicitly ignored, returns success
868 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
869 # No rows to insert, easy just return now
870 if ( !count( $a ) ) {
874 $table = $this->tableName( $table );
875 if ( !is_array( $options ) ) {
876 $options = array( $options );
878 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
880 $keys = array_keys( $a[0] );
883 $keys = array_keys( $a );
886 $sql = 'INSERT ' . implode( ' ', $options ) .
887 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
891 foreach ( $a as $row ) {
897 $sql .= '(' . $this->makeList( $row ) . ')';
900 $sql .= '(' . $this->makeList( $a ) . ')';
902 return !!$this->query( $sql, $fname );
906 * UPDATE wrapper, takes a condition array and a SET array
908 function update( $table, $values, $conds, $fname = 'Database::update' ) {
909 $table = $this->tableName( $table );
910 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET
);
911 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
912 $this->query( $sql, $fname );
916 * Makes a wfStrencoded list from an array
917 * $mode: LIST_COMMA - comma separated, no field names
918 * LIST_AND - ANDed WHERE clause (without the WHERE)
919 * LIST_SET - comma separated with field names, like a SET clause
920 * LIST_NAMES - comma separated field names
922 function makeList( $a, $mode = LIST_COMMA
) {
923 if ( !is_array( $a ) ) {
924 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
929 foreach ( $a as $field => $value ) {
931 if ( $mode == LIST_AND
) {
939 if ( $mode == LIST_AND
&& is_numeric( $field ) ) {
941 } elseif ( $mode == LIST_AND
&& is_array ($value) ) {
942 $list .= $field." IN (".$this->makeList($value).") ";
944 if ( $mode == LIST_AND ||
$mode == LIST_SET
) {
947 $list .= ($mode==LIST_NAMES?
$value:$this->addQuotes( $value ));
954 * Change the current database
956 function selectDB( $db ) {
957 $this->mDBname
= $db;
958 return mysql_select_db( $db, $this->mConn
);
962 * Starts a timer which will kill the DB thread after $timeout seconds
964 function startTimer( $timeout ) {
966 if( function_exists( 'mysql_thread_id' ) ) {
967 # This will kill the query if it's still running after $timeout seconds.
968 $tid = mysql_thread_id( $this->mConn
);
969 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
974 * Stop a timer started by startTimer()
975 * Currently unimplemented.
978 function stopTimer() { }
981 * Format a table name ready for use in constructing an SQL query
983 * This does two important things: it quotes table names which as necessary,
984 * and it adds a table prefix if there is one.
986 * All functions of this object which require a table name call this function
987 * themselves. Pass the canonical name to such functions. This is only needed
988 * when calling query() directly.
990 * @param string $name database table name
992 function tableName( $name ) {
994 # Skip quoted literals
995 if ( $name{0} != '`' ) {
996 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
997 $name = "{$this->mTablePrefix}$name";
999 if ( isset( $wgSharedDB ) && 'user' == $name ) {
1000 $name = "`$wgSharedDB`.`$name`";
1010 * Fetch a number of table names into an array
1011 * This is handy when you need to construct SQL for joins
1014 * extract($dbr->tableNames('user','watchlist'));
1015 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1016 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1018 function tableNames() {
1019 $inArray = func_get_args();
1021 foreach ( $inArray as $name ) {
1022 $retVal[$name] = $this->tableName( $name );
1028 * Wrapper for addslashes()
1029 * @param string $s String to be slashed.
1030 * @return string slashed string.
1032 function strencode( $s ) {
1033 return addslashes( $s );
1037 * If it's a string, adds quotes and backslashes
1038 * Otherwise returns as-is
1040 function addQuotes( $s ) {
1041 if ( is_null( $s ) ) {
1044 # This will also quote numeric values. This should be harmless,
1045 # and protects against weird problems that occur when they really
1046 # _are_ strings such as article titles and string->number->string
1047 # conversion is not 1:1.
1048 $s = "'" . $this->strencode( $s ) . "'";
1054 * Returns an appropriately quoted sequence value for inserting a new row.
1055 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1056 * subclass will return an integer, and save the value for insertId()
1058 function nextSequenceValue( $seqName ) {
1064 * PostgreSQL doesn't have them and returns ""
1066 function useIndexClause( $index ) {
1067 return 'USE INDEX ('.$index.')';
1071 * REPLACE query wrapper
1072 * PostgreSQL simulates this with a DELETE followed by INSERT
1073 * $row is the row to insert, an associative array
1074 * $uniqueIndexes is an array of indexes. Each element may be either a
1075 * field name or an array of field names
1077 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1078 * However if you do this, you run the risk of encountering errors which wouldn't have
1081 * @todo migrate comment to phodocumentor format
1083 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1084 $table = $this->tableName( $table );
1087 if ( !is_array( reset( $rows ) ) ) {
1088 $rows = array( $rows );
1091 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1093 foreach ( $rows as $row ) {
1099 $sql .= '(' . $this->makeList( $row ) . ')';
1101 return $this->query( $sql, $fname );
1105 * DELETE where the condition is a join
1106 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1108 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1109 * join condition matches, set $conds='*'
1111 * DO NOT put the join condition in $conds
1113 * @param string $delTable The table to delete from.
1114 * @param string $joinTable The other table.
1115 * @param string $delVar The variable to join on, in the first table.
1116 * @param string $joinVar The variable to join on, in the second table.
1117 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1119 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1121 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1124 $delTable = $this->tableName( $delTable );
1125 $joinTable = $this->tableName( $joinTable );
1126 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1127 if ( $conds != '*' ) {
1128 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1131 return $this->query( $sql, $fname );
1135 * Returns the size of a text field, or -1 for "unlimited"
1137 function textFieldSize( $table, $field ) {
1138 $table = $this->tableName( $table );
1139 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1140 $res = $this->query( $sql, 'Database::textFieldSize' );
1141 $row = $this->fetchObject( $res );
1142 $this->freeResult( $res );
1144 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
1153 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1155 function lowPriorityOption() {
1156 return 'LOW_PRIORITY';
1160 * DELETE query wrapper
1162 * Use $conds == "*" to delete all rows
1164 function delete( $table, $conds, $fname = 'Database::delete' ) {
1166 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1168 $table = $this->tableName( $table );
1169 $sql = "DELETE FROM $table ";
1170 if ( $conds != '*' ) {
1171 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1173 return $this->query( $sql, $fname );
1177 * INSERT SELECT wrapper
1178 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1179 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1180 * $conds may be "*" to copy the whole table
1181 * srcTable may be an array of tables.
1183 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1184 $destTable = $this->tableName( $destTable );
1185 if( is_array( $srcTable ) ) {
1186 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1188 $srcTable = $this->tableName( $srcTable );
1190 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1191 ' SELECT ' . implode( ',', $varMap ) .
1193 if ( $conds != '*' ) {
1194 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1196 return $this->query( $sql, $fname );
1200 * Construct a LIMIT query with optional offset
1201 * This is used for query pages
1203 function limitResult($limit,$offset) {
1204 return ' LIMIT '.(is_numeric($offset)?
"{$offset},":"")."{$limit} ";
1208 * Returns an SQL expression for a simple conditional.
1211 * @param string $cond SQL expression which will result in a boolean value
1212 * @param string $trueVal SQL expression to return if true
1213 * @param string $falseVal SQL expression to return if false
1214 * @return string SQL fragment
1216 function conditional( $cond, $trueVal, $falseVal ) {
1217 return " IF($cond, $trueVal, $falseVal) ";
1221 * Determines if the last failure was due to a deadlock
1223 function wasDeadlock() {
1224 return $this->lastErrno() == 1213;
1228 * Perform a deadlock-prone transaction.
1230 * This function invokes a callback function to perform a set of write
1231 * queries. If a deadlock occurs during the processing, the transaction
1232 * will be rolled back and the callback function will be called again.
1235 * $dbw->deadlockLoop( callback, ... );
1237 * Extra arguments are passed through to the specified callback function.
1239 * Returns whatever the callback function returned on its successful,
1240 * iteration, or false on error, for example if the retry limit was
1243 function deadlockLoop() {
1244 $myFname = 'Database::deadlockLoop';
1246 $this->query( 'BEGIN', $myFname );
1247 $args = func_get_args();
1248 $function = array_shift( $args );
1249 $oldIgnore = $this->ignoreErrors( true );
1250 $tries = DEADLOCK_TRIES
;
1251 if ( is_array( $function ) ) {
1252 $fname = $function[0];
1257 $retVal = call_user_func_array( $function, $args );
1258 $error = $this->lastError();
1259 $errno = $this->lastErrno();
1260 $sql = $this->lastQuery();
1263 if ( $this->wasDeadlock() ) {
1265 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1267 $this->reportQueryError( $error, $errno, $sql, $fname );
1270 } while( $this->wasDeadlock() && --$tries > 0 );
1271 $this->ignoreErrors( $oldIgnore );
1272 if ( $tries <= 0 ) {
1273 $this->query( 'ROLLBACK', $myFname );
1274 $this->reportQueryError( $error, $errno, $sql, $fname );
1277 $this->query( 'COMMIT', $myFname );
1283 * Do a SELECT MASTER_POS_WAIT()
1285 * @param string $file the binlog file
1286 * @param string $pos the binlog position
1287 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1289 function masterPosWait( $file, $pos, $timeout ) {
1290 $fname = 'Database::masterPosWait';
1291 wfProfileIn( $fname );
1294 # Commit any open transactions
1295 $this->immediateCommit();
1297 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1298 $encFile = $this->strencode( $file );
1299 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1300 $res = $this->doQuery( $sql );
1301 if ( $res && $row = $this->fetchRow( $res ) ) {
1302 $this->freeResult( $res );
1310 * Get the position of the master from SHOW SLAVE STATUS
1312 function getSlavePos() {
1313 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1314 $row = $this->fetchObject( $res );
1316 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1318 return array( false, false );
1323 * Get the position of the master from SHOW MASTER STATUS
1325 function getMasterPos() {
1326 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1327 $row = $this->fetchObject( $res );
1329 return array( $row->File
, $row->Position
);
1331 return array( false, false );
1336 * Begin a transaction, or if a transaction has already started, continue it
1338 function begin( $fname = 'Database::begin' ) {
1339 if ( !$this->mTrxLevel
) {
1340 $this->immediateBegin( $fname );
1347 * End a transaction, or decrement the nest level if transactions are nested
1349 function commit( $fname = 'Database::commit' ) {
1350 if ( $this->mTrxLevel
) {
1353 if ( !$this->mTrxLevel
) {
1354 $this->immediateCommit( $fname );
1359 * Rollback a transaction
1361 function rollback( $fname = 'Database::rollback' ) {
1362 $this->query( 'ROLLBACK', $fname );
1363 $this->mTrxLevel
= 0;
1367 * Begin a transaction, committing any previously open transaction
1369 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1370 $this->query( 'BEGIN', $fname );
1371 $this->mTrxLevel
= 1;
1375 * Commit transaction, if one is open
1377 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1378 $this->query( 'COMMIT', $fname );
1379 $this->mTrxLevel
= 0;
1383 * Return MW-style timestamp used for MySQL schema
1385 function timestamp( $ts=0 ) {
1386 return wfTimestamp(TS_MW
,$ts);
1392 function &resultObject( &$result ) {
1393 if( empty( $result ) ) {
1396 return new ResultWrapper( $this, $result );
1401 * Return aggregated value alias
1403 function aggregateValue ($valuedata,$valuename='value') {
1408 * @return string wikitext of a link to the server software's web site
1410 function getSoftwareLink() {
1411 return "[http://www.mysql.com/ MySQL]";
1415 * @return string Version information from the database
1417 function getServerVersion() {
1418 return mysql_get_server_info();
1422 * Ping the server and try to reconnect if it there is no connection
1425 return mysql_ping( $this->mConn
);
1430 * Database abstraction object for mySQL
1431 * Inherit all methods and properties of Database::Database()
1433 * @package MediaWiki
1436 class DatabaseMysql
extends Database
{
1442 * Result wrapper for grabbing data queried by someone else
1444 * @package MediaWiki
1446 class ResultWrapper
{
1452 function ResultWrapper( $database, $result ) {
1453 $this->db
=& $database;
1454 $this->result
=& $result;
1460 function numRows() {
1461 return $this->db
->numRows( $this->result
);
1467 function &fetchObject() {
1468 return $this->db
->fetchObject( $this->result
);
1474 function &fetchRow() {
1475 return $this->db
->fetchRow( $this->result
);
1482 $this->db
->freeResult( $this->result
);
1483 unset( $this->result
);
1487 function seek( $row ) {
1488 $this->db
->dataSeek( $this->result
, $row );
1492 #------------------------------------------------------------------------------
1494 #------------------------------------------------------------------------------
1497 * Standard fail function, called by default when a connection cannot be
1499 * Displays the file cache if possible
1501 function wfEmergencyAbort( &$conn, $error ) {
1502 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1503 global $wgSitename, $wgServer;
1505 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1506 # Hard coding strings instead.
1508 $noconnect = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server. <br />
1510 $mainpage = 'Main Page';
1511 $searchdisabled = <<<EOT
1512 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1513 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1517 <!-- SiteSearch Google -->
1518 <FORM method=GET action=\"http://www.google.com/search\">
1519 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1520 <A HREF=\"http://www.google.com/\">
1521 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1522 border=\"0\" ALT=\"Google\"></A>
1525 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1526 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1528 <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 />
1529 <input type='hidden' name='ie' value='$2'>
1530 <input type='hidden' name='oe' value='$2'>
1534 <!-- SiteSearch Google -->";
1535 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1538 if( !headers_sent() ) {
1539 header( 'HTTP/1.0 500 Internal Server Error' );
1540 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1541 /* Don't cache error pages! They cause no end of trouble... */
1542 header( 'Cache-control: none' );
1543 header( 'Pragma: nocache' );
1545 $msg = wfGetSiteNotice();
1547 $msg = str_replace( '$1', $error, $noconnect );
1551 if($wgUseFileCache) {
1556 $t = Title
::newFromURL( $title );
1557 } elseif (@/**/$_REQUEST['search']) {
1558 $search = $_REQUEST['search'];
1559 echo $searchdisabled;
1560 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1561 $wgInputEncoding ), $googlesearch );
1564 $t = Title
::newFromText( $mainpage );
1568 $cache = new CacheManager( $t );
1569 if( $cache->isFileCached() ) {
1570 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1571 $cachederror . "</b></p>\n";
1573 $tag = '<div id="article">';
1574 $text = str_replace(
1577 $cache->fetchPageText() );