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);
18 define( 'LIST_OR', 4);
20 /** Number of times to re-try an operation in case of deadlock */
21 define( 'DEADLOCK_TRIES', 4 );
22 /** Minimum time to wait before retry, in microseconds */
23 define( 'DEADLOCK_DELAY_MIN', 500000 );
24 /** Maximum time to wait before retry */
25 define( 'DEADLOCK_DELAY_MAX', 1500000 );
30 function DBObject($data) {
44 * Database abstraction object
49 #------------------------------------------------------------------------------
51 #------------------------------------------------------------------------------
57 var $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
58 var $mOut, $mOpened = false;
67 #------------------------------------------------------------------------------
69 #------------------------------------------------------------------------------
70 # These optionally set a variable and return the previous state
73 * Fail function, takes a Database as a parameter
74 * Set to false for default, 1 for ignore errors
76 function failFunction( $function = NULL ) {
77 return wfSetVar( $this->mFailFunction
, $function );
81 * Output page, used for reporting errors
82 * FALSE means discard output
84 function &setOutputPage( &$out ) {
89 * Boolean, controls output of large amounts of debug information
91 function debug( $debug = NULL ) {
92 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
96 * Turns buffering of SQL result sets on (true) or off (false).
97 * Default is "on" and it should not be changed without good reasons.
99 function bufferResults( $buffer = NULL ) {
100 if ( is_null( $buffer ) ) {
101 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
103 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
108 * Turns on (false) or off (true) the automatic generation and sending
109 * of a "we're sorry, but there has been a database error" page on
110 * database errors. Default is on (false). When turned off, the
111 * code should use wfLastErrno() and wfLastError() to handle the
112 * situation as appropriate.
114 function ignoreErrors( $ignoreErrors = NULL ) {
115 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
119 * The current depth of nested transactions
120 * @param integer $level
122 function trxLevel( $level = NULL ) {
123 return wfSetVar( $this->mTrxLevel
, $level );
127 * Number of errors logged, only useful when errors are ignored
129 function errorCount( $count = NULL ) {
130 return wfSetVar( $this->mErrorCount
, $count );
136 function lastQuery() { return $this->mLastQuery
; }
137 function isOpen() { return $this->mOpened
; }
140 function setFlag( $flag ) {
141 $this->mFlags |
= $flag;
144 function clearFlag( $flag ) {
145 $this->mFlags
&= ~
$flag;
148 function getFlag( $flag ) {
149 return !!($this->mFlags
& $flag);
152 #------------------------------------------------------------------------------
154 #------------------------------------------------------------------------------
157 * @param string $server database server host
158 * @param string $user database user name
159 * @param string $password database user password
160 * @param string $dbname database name
164 * @param failFunction
166 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
168 function Database( $server = false, $user = false, $password = false, $dbName = false,
169 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
171 global $wgOut, $wgDBprefix, $wgCommandLineMode;
172 # Can't get a reference if it hasn't been set yet
173 if ( !isset( $wgOut ) ) {
176 $this->mOut
=& $wgOut;
178 $this->mFailFunction
= $failFunction;
179 $this->mFlags
= $flags;
181 if ( $this->mFlags
& DBO_DEFAULT
) {
182 if ( $wgCommandLineMode ) {
183 $this->mFlags
&= ~DBO_TRX
;
185 $this->mFlags |
= DBO_TRX
;
190 // Faster read-only access
191 if ( wfReadOnly() ) {
192 $this->mFlags |= DBO_PERSISTENT;
193 $this->mFlags &= ~DBO_TRX;
196 /** Get the default table prefix*/
197 if ( $tablePrefix == 'get from global' ) {
198 $this->mTablePrefix
= $wgDBprefix;
200 $this->mTablePrefix
= $tablePrefix;
204 $this->open( $server, $user, $password, $dbName );
210 * @param failFunction
213 function newFromParams( $server, $user, $password, $dbName,
214 $failFunction = false, $flags = 0 )
216 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
220 * Usually aborts on failure
221 * If the failFunction is set to a non-zero integer, returns success
223 function open( $server, $user, $password, $dbName ) {
226 # Test for missing mysql.so
227 # First try to load it
228 if (!@extension_loaded
('mysql')) {
232 # Otherwise we get a suppressed fatal error, which is very hard to track down
233 if ( !function_exists( 'mysql_connect' ) ) {
234 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
238 $this->mServer
= $server;
239 $this->mUser
= $user;
240 $this->mPassword
= $password;
241 $this->mDBname
= $dbName;
245 if ( $this->mFlags
& DBO_PERSISTENT
) {
246 @/**/$this->mConn
= mysql_pconnect( $server, $user, $password );
248 # Create a new connection...
249 if( version_compare( PHP_VERSION
, '4.2.0', 'ge' ) ) {
250 @/**/$this->mConn
= mysql_connect( $server, $user, $password, true );
252 # On PHP 4.1 the new_link parameter is not available. We cannot
253 # guarantee that we'll actually get a new connection, and this
254 # may cause some operations to fail possibly.
255 @/**/$this->mConn
= mysql_connect( $server, $user, $password );
259 if ( $dbName != '' ) {
260 if ( $this->mConn
!== false ) {
261 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
263 $error = "Error selecting database $dbname on server {$this->mServer} " .
264 "from client host {$wguname['nodename']}\n";
268 wfDebug( "DB connection error\n" );
269 wfDebug( "Server: $server, User: $user, Password: " .
270 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
275 $success = (bool)$this->mConn
;
279 $this->reportConnectionError();
284 // Tell the server we're communicating with it in UTF-8.
285 // This may engage various charset conversions.
286 $this->query( 'SET NAMES utf8' );
289 $this->mOpened
= $success;
295 * Closes a database connection.
296 * if it is open : commits any open transactions
298 * @return bool operation success. true if already closed.
302 $this->mOpened
= false;
303 if ( $this->mConn
) {
304 if ( $this->trxLevel() ) {
305 $this->immediateCommit();
307 return mysql_close( $this->mConn
);
315 * @param string $error fallback error message, used if none is given by MySQL
317 function reportConnectionError( $error = 'Unknown error' ) {
318 $myError = $this->lastError();
323 if ( $this->mFailFunction
) {
324 if ( !is_int( $this->mFailFunction
) ) {
325 $ff = $this->mFailFunction
;
326 $ff( $this, $error );
329 wfEmergencyAbort( $this, $error );
334 * Usually aborts on failure
335 * If errors are explicitly ignored, returns success
337 function query( $sql, $fname = '', $tempIgnore = false ) {
338 global $wgProfiling, $wgCommandLineMode;
340 if ( wfReadOnly() ) {
341 # This is a quick check for the most common kinds of write query used
342 # in MediaWiki, to provide extra safety in addition to UI-level checks.
343 # It is not intended to prevent every conceivable write query, or even
344 # to handle such queries gracefully.
345 if ( preg_match( '/^(?:update|insert|replace|delete)/i', $sql ) ) {
346 wfDebug( "Write query from $fname blocked\n" );
351 if ( $wgProfiling ) {
352 # generalizeSQL will probably cut down the query to reasonable
353 # logging size most of the time. The substr is really just a sanity check.
355 # Who's been wasting my precious column space? -- TS
356 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
357 $profName = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
359 wfProfileIn( 'Database::query' );
360 wfProfileIn( $profName );
363 $this->mLastQuery
= $sql;
365 # Add a comment for easy SHOW PROCESSLIST interpretation
367 $commentedSql = "/* $fname */ $sql";
369 $commentedSql = $sql;
372 # If DBO_TRX is set, start a transaction
373 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() && $sql != 'BEGIN' ) {
377 if ( $this->debug() ) {
378 $sqlx = substr( $commentedSql, 0, 500 );
379 $sqlx = strtr( $sqlx, "\t\n", ' ' );
380 wfDebug( "SQL: $sqlx\n" );
383 # Do the query and handle errors
384 $ret = $this->doQuery( $commentedSql );
386 # Try reconnecting if the connection was lost
387 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
388 # Transaction is gone, like it or not
389 $this->mTrxLevel
= 0;
390 wfDebug( "Connection lost, reconnecting...\n" );
391 if ( $this->ping() ) {
392 wfDebug( "Reconnected\n" );
393 $ret = $this->doQuery( $commentedSql );
395 wfDebug( "Failed\n" );
399 if ( false === $ret ) {
400 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
403 if ( $wgProfiling ) {
404 wfProfileOut( $profName );
405 wfProfileOut( 'Database::query' );
411 * The DBMS-dependent part of query()
412 * @param string $sql SQL query.
414 function doQuery( $sql ) {
415 if( $this->bufferResults() ) {
416 $ret = mysql_query( $sql, $this->mConn
);
418 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
427 * @param string $fname
428 * @param bool $tempIgnore
430 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
431 global $wgCommandLineMode, $wgFullyInitialised;
432 # Ignore errors during error handling to avoid infinite recursion
433 $ignore = $this->ignoreErrors( true );
434 ++
$this->mErrorCount
;
436 if( $ignore ||
$tempIgnore ) {
437 wfDebug("SQL ERROR (ignored): $error\n");
439 $sql1line = str_replace( "\n", "\\n", $sql );
440 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
441 wfDebug("SQL ERROR: " . $error . "\n");
442 if ( $wgCommandLineMode ||
!$this->mOut ||
empty( $wgFullyInitialised ) ) {
443 $message = "A database error has occurred\n" .
445 "Function: $fname\n" .
446 "Error: $errno $error\n";
447 if ( !$wgCommandLineMode ) {
448 $message = nl2br( $message );
450 wfDebugDieBacktrace( $message );
452 // this calls wfAbruptExit()
453 $this->mOut
->databaseError( $fname, $sql, $error, $errno );
456 $this->ignoreErrors( $ignore );
461 * Intended to be compatible with the PEAR::DB wrapper functions.
462 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
464 * ? = scalar value, quoted as necessary
465 * ! = raw SQL bit (a function for instance)
466 * & = filename; reads the file and inserts as a blob
467 * (we don't use this though...)
469 function prepare( $sql, $func = 'Database::prepare' ) {
470 /* MySQL doesn't support prepared statements (yet), so just
471 pack up the query for reference. We'll manually replace
473 return array( 'query' => $sql, 'func' => $func );
476 function freePrepared( $prepared ) {
477 /* No-op for MySQL */
481 * Execute a prepared query with the various arguments
482 * @param string $prepared the prepared sql
483 * @param mixed $args Either an array here, or put scalars as varargs
485 function execute( $prepared, $args = null ) {
486 if( !is_array( $args ) ) {
488 $args = func_get_args();
489 array_shift( $args );
491 $sql = $this->fillPrepared( $prepared['query'], $args );
492 return $this->query( $sql, $prepared['func'] );
496 * Prepare & execute an SQL statement, quoting and inserting arguments
497 * in the appropriate places.
498 * @param string $query
499 * @param string $args ...
501 function safeQuery( $query, $args = null ) {
502 $prepared = $this->prepare( $query, 'Database::safeQuery' );
503 if( !is_array( $args ) ) {
505 $args = func_get_args();
506 array_shift( $args );
508 $retval = $this->execute( $prepared, $args );
509 $this->freePrepared( $prepared );
514 * For faking prepared SQL statements on DBs that don't support
516 * @param string $preparedSql - a 'preparable' SQL statement
517 * @param array $args - array of arguments to fill it with
518 * @return string executable SQL
520 function fillPrepared( $preparedQuery, $args ) {
523 $this->preparedArgs
=& $args;
524 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
525 array( &$this, 'fillPreparedArg' ), $preparedQuery );
529 * preg_callback func for fillPrepared()
530 * The arguments should be in $this->preparedArgs and must not be touched
531 * while we're doing this.
533 * @param array $matches
537 function fillPreparedArg( $matches ) {
538 switch( $matches[1] ) {
539 case '\\?': return '?';
540 case '\\!': return '!';
541 case '\\&': return '&';
543 list( $n, $arg ) = each( $this->preparedArgs
);
544 switch( $matches[1] ) {
545 case '?': return $this->addQuotes( $arg );
546 case '!': return $arg;
548 # return $this->addQuotes( file_get_contents( $arg ) );
549 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
551 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
556 * @param mixed $res A SQL result
559 * Free a result object
561 function freeResult( $res ) {
562 if ( !@/**/mysql_free_result( $res ) ) {
563 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
568 * Fetch the next row from the given result object, in object form
570 function fetchObject( $res ) {
571 @/**/$row = mysql_fetch_object( $res );
572 if( mysql_errno() ) {
573 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
579 * Fetch the next row from the given result object
582 function fetchRow( $res ) {
583 @/**/$row = mysql_fetch_array( $res );
584 if (mysql_errno() ) {
585 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
591 * Get the number of rows in a result object
593 function numRows( $res ) {
594 @/**/$n = mysql_num_rows( $res );
595 if( mysql_errno() ) {
596 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
602 * Get the number of fields in a result object
603 * See documentation for mysql_num_fields()
605 function numFields( $res ) { return mysql_num_fields( $res ); }
608 * Get a field name in a result object
609 * See documentation for mysql_field_name()
611 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
614 * Get the inserted value of an auto-increment row
616 * The value inserted should be fetched from nextSequenceValue()
619 * $id = $dbw->nextSequenceValue('page_page_id_seq');
620 * $dbw->insert('page',array('page_id' => $id));
621 * $id = $dbw->insertId();
623 function insertId() { return mysql_insert_id( $this->mConn
); }
626 * Change the position of the cursor in a result object
627 * See mysql_data_seek()
629 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
632 * Get the last error number
635 function lastErrno() {
636 if ( $this->mConn
) {
637 return mysql_errno( $this->mConn
);
639 return mysql_errno();
644 * Get a description of the last error
645 * See mysql_error() for more details
647 function lastError() {
648 if ( $this->mConn
) {
649 # Even if it's non-zero, it can still be invalid
650 wfSuppressWarnings();
651 $error = mysql_error( $this->mConn
);
653 $error = mysql_error();
657 $error = mysql_error();
660 $error .= ' (' . $this->mServer
. ')';
665 * Get the number of rows affected by the last write query
666 * See mysql_affected_rows() for more details
668 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
669 /**#@-*/ // end of template : @param $result
672 * Simple UPDATE wrapper
673 * Usually aborts on failure
674 * If errors are explicitly ignored, returns success
676 * This function exists for historical reasons, Database::update() has a more standard
677 * calling convention and feature set
679 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
681 $table = $this->tableName( $table );
682 $sql = "UPDATE $table SET $var = '" .
683 $this->strencode( $value ) . "' WHERE ($cond)";
684 return (bool)$this->query( $sql, DB_MASTER
, $fname );
688 * Simple SELECT wrapper, returns a single field, input must be encoded
689 * Usually aborts on failure
690 * If errors are explicitly ignored, returns FALSE on failure
692 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
693 if ( !is_array( $options ) ) {
694 $options = array( $options );
696 $options['LIMIT'] = 1;
698 $res = $this->select( $table, $var, $cond, $fname, $options );
699 if ( $res === false ||
!$this->numRows( $res ) ) {
702 $row = $this->fetchRow( $res );
703 if ( $row !== false ) {
704 $this->freeResult( $res );
712 * Returns an optional USE INDEX clause to go after the table, and a
713 * string to go at the end of the query
717 * @param array $options an associative array of options to be turned into
718 * an SQL query, valid keys are listed in the function.
721 function makeSelectOptions( $options ) {
724 if ( isset( $options['GROUP BY'] ) ) {
725 $tailOpts .= " GROUP BY {$options['GROUP BY']}";
727 if ( isset( $options['ORDER BY'] ) ) {
728 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
730 if (isset($options['LIMIT'])) {
731 $tailOpts .= $this->limitResult('', $options['LIMIT'],
732 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
734 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
735 $tailOpts .= ' FOR UPDATE';
738 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
739 $tailOpts .= ' LOCK IN SHARE MODE';
742 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
743 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
747 return array( $useIndex, $tailOpts );
753 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
755 if( is_array( $vars ) ) {
756 $vars = implode( ',', $vars );
758 if( !is_array( $options ) ) {
759 $options = array( $options );
761 if( is_array( $table ) ) {
762 if ( @is_array
( $options['USE INDEX'] ) )
763 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
765 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
766 } elseif ($table!='') {
767 $from = ' FROM ' . $this->tableName( $table );
772 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
774 if( !empty( $conds ) ) {
775 if ( is_array( $conds ) ) {
776 $conds = $this->makeList( $conds, LIST_AND
);
778 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
780 $sql = "SELECT $vars $from $useIndex $tailOpts";
783 return $this->query( $sql, $fname );
787 * Single row SELECT wrapper
788 * Aborts or returns FALSE on error
790 * $vars: the selected variables
791 * $conds: a condition map, terms are ANDed together.
792 * Items with numeric keys are taken to be literal conditions
793 * Takes an array of selected variables, and a condition map, which is ANDed
794 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
795 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
796 * $obj- >page_id is the ID of the Astronomy article
798 * @todo migrate documentation to phpdocumentor format
800 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
801 $options['LIMIT'] = 1;
802 $res = $this->select( $table, $vars, $conds, $fname, $options );
803 if ( $res === false )
805 if ( !$this->numRows($res) ) {
806 $this->freeResult($res);
809 $obj = $this->fetchObject( $res );
810 $this->freeResult( $res );
816 * Removes most variables from an SQL query and replaces them with X or N for numbers.
817 * It's only slightly flawed. Don't use for anything important.
819 * @param string $sql A SQL Query
822 function generalizeSQL( $sql ) {
823 # This does the same as the regexp below would do, but in such a way
824 # as to avoid crashing php on some large strings.
825 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
827 $sql = str_replace ( "\\\\", '', $sql);
828 $sql = str_replace ( "\\'", '', $sql);
829 $sql = str_replace ( "\\\"", '', $sql);
830 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
831 $sql = preg_replace ('/".*"/s', "'X'", $sql);
833 # All newlines, tabs, etc replaced by single space
834 $sql = preg_replace ( "/\s+/", ' ', $sql);
837 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
843 * Determines whether a field exists in a table
844 * Usually aborts on failure
845 * If errors are explicitly ignored, returns NULL on failure
847 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
848 $table = $this->tableName( $table );
849 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE
, $fname );
856 while ( $row = $this->fetchObject( $res ) ) {
857 if ( $row->Field
== $field ) {
866 * Determines whether an index exists
867 * Usually aborts on failure
868 * If errors are explicitly ignored, returns NULL on failure
870 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
871 $info = $this->indexInfo( $table, $index, $fname );
872 if ( is_null( $info ) ) {
875 return $info !== false;
881 * Get information about an index into an object
882 * Returns false if the index does not exist
884 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
885 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
886 # SHOW INDEX should work for 3.x and up:
887 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
888 $table = $this->tableName( $table );
889 $sql = 'SHOW INDEX FROM '.$table;
890 $res = $this->query( $sql, $fname );
895 while ( $row = $this->fetchObject( $res ) ) {
896 if ( $row->Key_name
== $index ) {
904 * Query whether a given table exists
906 function tableExists( $table ) {
907 $table = $this->tableName( $table );
908 $old = $this->ignoreErrors( true );
909 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
910 $this->ignoreErrors( $old );
912 $this->freeResult( $res );
920 * mysql_fetch_field() wrapper
921 * Returns false if the field doesn't exist
926 function fieldInfo( $table, $field ) {
927 $table = $this->tableName( $table );
928 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
929 $n = mysql_num_fields( $res );
930 for( $i = 0; $i < $n; $i++
) {
931 $meta = mysql_fetch_field( $res, $i );
932 if( $field == $meta->name
) {
940 * mysql_field_type() wrapper
942 function fieldType( $res, $index ) {
943 return mysql_field_type( $res, $index );
947 * Determines if a given index is unique
949 function indexUnique( $table, $index ) {
950 $indexInfo = $this->indexInfo( $table, $index );
954 return !$indexInfo->Non_unique
;
958 * INSERT wrapper, inserts an array into a table
960 * $a may be a single associative array, or an array of these with numeric keys, for
963 * Usually aborts on failure
964 * If errors are explicitly ignored, returns success
966 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
967 # No rows to insert, easy just return now
968 if ( !count( $a ) ) {
972 $table = $this->tableName( $table );
973 if ( !is_array( $options ) ) {
974 $options = array( $options );
976 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
978 $keys = array_keys( $a[0] );
981 $keys = array_keys( $a );
984 $sql = 'INSERT ' . implode( ' ', $options ) .
985 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
989 foreach ( $a as $row ) {
995 $sql .= '(' . $this->makeList( $row ) . ')';
998 $sql .= '(' . $this->makeList( $a ) . ')';
1000 return (bool)$this->query( $sql, $fname );
1004 * Make UPDATE options for the Database::update function
1007 * @param array $options The options passed to Database::update
1010 function makeUpdateOptions( $options ) {
1011 if( !is_array( $options ) ) {
1012 $options = array( $options );
1015 if ( in_array( 'LOW_PRIORITY', $options ) )
1016 $opts[] = $this->lowPriorityOption();
1017 if ( in_array( 'IGNORE', $options ) )
1019 return implode(' ', $opts);
1023 * UPDATE wrapper, takes a condition array and a SET array
1025 * @param string $table The table to UPDATE
1026 * @param array $values An array of values to SET
1027 * @param array $conds An array of conditions (WHERE)
1028 * @param string $fname The Class::Function calling this function
1030 * @param array $options An array of UPDATE options, can be one or
1031 * more of IGNORE, LOW_PRIORITY
1033 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1034 $table = $this->tableName( $table );
1035 $opts = $this->makeUpdateOptions( $options );
1036 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1037 if ( $conds != '*' ) {
1038 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1040 $this->query( $sql, $fname );
1044 * Makes a wfStrencoded list from an array
1045 * $mode: LIST_COMMA - comma separated, no field names
1046 * LIST_AND - ANDed WHERE clause (without the WHERE)
1047 * LIST_SET - comma separated with field names, like a SET clause
1048 * LIST_NAMES - comma separated field names
1050 function makeList( $a, $mode = LIST_COMMA
) {
1051 if ( !is_array( $a ) ) {
1052 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
1057 foreach ( $a as $field => $value ) {
1059 if ( $mode == LIST_AND
) {
1061 } elseif($mode == LIST_OR
) {
1069 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1070 $list .= "($value)";
1071 } elseif ( $mode == LIST_AND
&& is_array ($value) ) {
1072 $list .= $field." IN (".$this->makeList($value).") ";
1074 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1075 $list .= "$field = ";
1077 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1084 * Change the current database
1086 function selectDB( $db ) {
1087 $this->mDBname
= $db;
1088 return mysql_select_db( $db, $this->mConn
);
1092 * Starts a timer which will kill the DB thread after $timeout seconds
1094 function startTimer( $timeout ) {
1096 if( function_exists( 'mysql_thread_id' ) ) {
1097 # This will kill the query if it's still running after $timeout seconds.
1098 $tid = mysql_thread_id( $this->mConn
);
1099 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
1104 * Stop a timer started by startTimer()
1105 * Currently unimplemented.
1108 function stopTimer() { }
1111 * Format a table name ready for use in constructing an SQL query
1113 * This does two important things: it quotes table names which as necessary,
1114 * and it adds a table prefix if there is one.
1116 * All functions of this object which require a table name call this function
1117 * themselves. Pass the canonical name to such functions. This is only needed
1118 * when calling query() directly.
1120 * @param string $name database table name
1122 function tableName( $name ) {
1124 # Skip quoted literals
1125 if ( $name{0} != '`' ) {
1126 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
1127 $name = "{$this->mTablePrefix}$name";
1129 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1130 $name = "`$wgSharedDB`.`$name`";
1140 * Fetch a number of table names into an array
1141 * This is handy when you need to construct SQL for joins
1144 * extract($dbr->tableNames('user','watchlist'));
1145 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1146 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1148 function tableNames() {
1149 $inArray = func_get_args();
1151 foreach ( $inArray as $name ) {
1152 $retVal[$name] = $this->tableName( $name );
1160 function tableNamesWithUseIndex( $tables, $use_index ) {
1163 foreach ( $tables as $table )
1164 if ( @$use_index[$table] !== null )
1165 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1167 $ret[] = $this->tableName( $table );
1169 return implode( ',', $ret );
1173 * Wrapper for addslashes()
1174 * @param string $s String to be slashed.
1175 * @return string slashed string.
1177 function strencode( $s ) {
1178 return addslashes( $s );
1182 * If it's a string, adds quotes and backslashes
1183 * Otherwise returns as-is
1185 function addQuotes( $s ) {
1186 if ( is_null( $s ) ) {
1189 # This will also quote numeric values. This should be harmless,
1190 # and protects against weird problems that occur when they really
1191 # _are_ strings such as article titles and string->number->string
1192 # conversion is not 1:1.
1193 return "'" . $this->strencode( $s ) . "'";
1198 * Escape string for safe LIKE usage
1200 function escapeLike( $s ) {
1201 $s=$this->strencode( $s );
1202 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1207 * Returns an appropriately quoted sequence value for inserting a new row.
1208 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1209 * subclass will return an integer, and save the value for insertId()
1211 function nextSequenceValue( $seqName ) {
1217 * PostgreSQL doesn't have them and returns ""
1219 function useIndexClause( $index ) {
1220 return "FORCE INDEX ($index)";
1224 * REPLACE query wrapper
1225 * PostgreSQL simulates this with a DELETE followed by INSERT
1226 * $row is the row to insert, an associative array
1227 * $uniqueIndexes is an array of indexes. Each element may be either a
1228 * field name or an array of field names
1230 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1231 * However if you do this, you run the risk of encountering errors which wouldn't have
1234 * @todo migrate comment to phodocumentor format
1236 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1237 $table = $this->tableName( $table );
1240 if ( !is_array( reset( $rows ) ) ) {
1241 $rows = array( $rows );
1244 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1246 foreach ( $rows as $row ) {
1252 $sql .= '(' . $this->makeList( $row ) . ')';
1254 return $this->query( $sql, $fname );
1258 * DELETE where the condition is a join
1259 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1261 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1262 * join condition matches, set $conds='*'
1264 * DO NOT put the join condition in $conds
1266 * @param string $delTable The table to delete from.
1267 * @param string $joinTable The other table.
1268 * @param string $delVar The variable to join on, in the first table.
1269 * @param string $joinVar The variable to join on, in the second table.
1270 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1272 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1274 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1277 $delTable = $this->tableName( $delTable );
1278 $joinTable = $this->tableName( $joinTable );
1279 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1280 if ( $conds != '*' ) {
1281 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1284 return $this->query( $sql, $fname );
1288 * Returns the size of a text field, or -1 for "unlimited"
1290 function textFieldSize( $table, $field ) {
1291 $table = $this->tableName( $table );
1292 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1293 $res = $this->query( $sql, 'Database::textFieldSize' );
1294 $row = $this->fetchObject( $res );
1295 $this->freeResult( $res );
1297 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
1306 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1308 function lowPriorityOption() {
1309 return 'LOW_PRIORITY';
1313 * DELETE query wrapper
1315 * Use $conds == "*" to delete all rows
1317 function delete( $table, $conds, $fname = 'Database::delete' ) {
1319 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1321 $table = $this->tableName( $table );
1322 $sql = "DELETE FROM $table";
1323 if ( $conds != '*' ) {
1324 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1326 return $this->query( $sql, $fname );
1330 * INSERT SELECT wrapper
1331 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1332 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1333 * $conds may be "*" to copy the whole table
1334 * srcTable may be an array of tables.
1336 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1337 $destTable = $this->tableName( $destTable );
1338 if( is_array( $srcTable ) ) {
1339 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1341 $srcTable = $this->tableName( $srcTable );
1343 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1344 ' SELECT ' . implode( ',', $varMap ) .
1346 if ( $conds != '*' ) {
1347 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1349 return $this->query( $sql, $fname );
1353 * Construct a LIMIT query with optional offset
1354 * This is used for query pages
1355 * $sql string SQL query we will append the limit too
1356 * $limit integer the SQL limit
1357 * $offset integer the SQL offset (default false)
1359 function limitResult($sql, $limit, $offset=false) {
1360 return " $sql LIMIT ".((is_numeric($offset) && $offset != 0)?
"{$offset},":"")."{$limit} ";
1362 function limitResultForUpdate($sql, $num) {
1363 return $this->limitResult($sql, $num, 0);
1367 * Returns an SQL expression for a simple conditional.
1370 * @param string $cond SQL expression which will result in a boolean value
1371 * @param string $trueVal SQL expression to return if true
1372 * @param string $falseVal SQL expression to return if false
1373 * @return string SQL fragment
1375 function conditional( $cond, $trueVal, $falseVal ) {
1376 return " IF($cond, $trueVal, $falseVal) ";
1380 * Determines if the last failure was due to a deadlock
1382 function wasDeadlock() {
1383 return $this->lastErrno() == 1213;
1387 * Perform a deadlock-prone transaction.
1389 * This function invokes a callback function to perform a set of write
1390 * queries. If a deadlock occurs during the processing, the transaction
1391 * will be rolled back and the callback function will be called again.
1394 * $dbw->deadlockLoop( callback, ... );
1396 * Extra arguments are passed through to the specified callback function.
1398 * Returns whatever the callback function returned on its successful,
1399 * iteration, or false on error, for example if the retry limit was
1402 function deadlockLoop() {
1403 $myFname = 'Database::deadlockLoop';
1406 $args = func_get_args();
1407 $function = array_shift( $args );
1408 $oldIgnore = $this->ignoreErrors( true );
1409 $tries = DEADLOCK_TRIES
;
1410 if ( is_array( $function ) ) {
1411 $fname = $function[0];
1416 $retVal = call_user_func_array( $function, $args );
1417 $error = $this->lastError();
1418 $errno = $this->lastErrno();
1419 $sql = $this->lastQuery();
1422 if ( $this->wasDeadlock() ) {
1424 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1426 $this->reportQueryError( $error, $errno, $sql, $fname );
1429 } while( $this->wasDeadlock() && --$tries > 0 );
1430 $this->ignoreErrors( $oldIgnore );
1431 if ( $tries <= 0 ) {
1432 $this->query( 'ROLLBACK', $myFname );
1433 $this->reportQueryError( $error, $errno, $sql, $fname );
1436 $this->query( 'COMMIT', $myFname );
1442 * Do a SELECT MASTER_POS_WAIT()
1444 * @param string $file the binlog file
1445 * @param string $pos the binlog position
1446 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1448 function masterPosWait( $file, $pos, $timeout ) {
1449 $fname = 'Database::masterPosWait';
1450 wfProfileIn( $fname );
1453 # Commit any open transactions
1454 $this->immediateCommit();
1456 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1457 $encFile = $this->strencode( $file );
1458 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1459 $res = $this->doQuery( $sql );
1460 if ( $res && $row = $this->fetchRow( $res ) ) {
1461 $this->freeResult( $res );
1462 wfProfileOut( $fname );
1465 wfProfileOut( $fname );
1471 * Get the position of the master from SHOW SLAVE STATUS
1473 function getSlavePos() {
1474 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1475 $row = $this->fetchObject( $res );
1477 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1479 return array( false, false );
1484 * Get the position of the master from SHOW MASTER STATUS
1486 function getMasterPos() {
1487 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1488 $row = $this->fetchObject( $res );
1490 return array( $row->File
, $row->Position
);
1492 return array( false, false );
1497 * Begin a transaction, or if a transaction has already started, continue it
1499 function begin( $fname = 'Database::begin' ) {
1500 if ( !$this->mTrxLevel
) {
1501 $this->immediateBegin( $fname );
1508 * End a transaction, or decrement the nest level if transactions are nested
1510 function commit( $fname = 'Database::commit' ) {
1511 if ( $this->mTrxLevel
) {
1514 if ( !$this->mTrxLevel
) {
1515 $this->immediateCommit( $fname );
1520 * Rollback a transaction
1522 function rollback( $fname = 'Database::rollback' ) {
1523 $this->query( 'ROLLBACK', $fname );
1524 $this->mTrxLevel
= 0;
1528 * Begin a transaction, committing any previously open transaction
1530 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1531 $this->query( 'BEGIN', $fname );
1532 $this->mTrxLevel
= 1;
1536 * Commit transaction, if one is open
1538 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1539 $this->query( 'COMMIT', $fname );
1540 $this->mTrxLevel
= 0;
1544 * Return MW-style timestamp used for MySQL schema
1546 function timestamp( $ts=0 ) {
1547 return wfTimestamp(TS_MW
,$ts);
1551 * Local database timestamp format or null
1553 function timestampOrNull( $ts = null ) {
1554 if( is_null( $ts ) ) {
1557 return $this->timestamp( $ts );
1564 function resultObject( $result ) {
1565 if( empty( $result ) ) {
1568 return new ResultWrapper( $this, $result );
1573 * Return aggregated value alias
1575 function aggregateValue ($valuedata,$valuename='value') {
1580 * @return string wikitext of a link to the server software's web site
1582 function getSoftwareLink() {
1583 return "[http://www.mysql.com/ MySQL]";
1587 * @return string Version information from the database
1589 function getServerVersion() {
1590 return mysql_get_server_info();
1594 * Ping the server and try to reconnect if it there is no connection
1597 if( function_exists( 'mysql_ping' ) ) {
1598 return mysql_ping( $this->mConn
);
1600 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1607 * At the moment, this will only work if the DB user has the PROCESS privilege
1610 $res = $this->query( 'SHOW PROCESSLIST' );
1611 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1612 # dubious, but unfortunately there's no easy rigorous way
1614 while ( $row = $this->fetchObject( $res ) ) {
1615 if ( $row->User
== 'system user' ) {
1616 if ( ++
$slaveThreads == 2 ) {
1617 # This is it, return the time
1626 * Get status information from SHOW STATUS in an associative array
1628 function getStatus() {
1629 $res = $this->query( 'SHOW STATUS' );
1631 while ( $row = $this->fetchObject( $res ) ) {
1632 $status[$row->Variable_name
] = $row->Value
;
1638 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1640 function maxListLen() {
1644 function encodeBlob($b) {
1648 function notNullTimestamp() {
1651 function isNullTimestamp() {
1657 * Database abstraction object for mySQL
1658 * Inherit all methods and properties of Database::Database()
1660 * @package MediaWiki
1663 class DatabaseMysql
extends Database
{
1669 * Result wrapper for grabbing data queried by someone else
1671 * @package MediaWiki
1673 class ResultWrapper
{
1679 function ResultWrapper( $database, $result ) {
1680 $this->db
=& $database;
1681 $this->result
=& $result;
1687 function numRows() {
1688 return $this->db
->numRows( $this->result
);
1694 function fetchObject() {
1695 return $this->db
->fetchObject( $this->result
);
1701 function &fetchRow() {
1702 return $this->db
->fetchRow( $this->result
);
1709 $this->db
->freeResult( $this->result
);
1710 unset( $this->result
);
1714 function seek( $row ) {
1715 $this->db
->dataSeek( $this->result
, $row );
1719 #------------------------------------------------------------------------------
1721 #------------------------------------------------------------------------------
1724 * Standard fail function, called by default when a connection cannot be
1726 * Displays the file cache if possible
1728 function wfEmergencyAbort( &$conn, $error ) {
1729 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1730 global $wgSitename, $wgServer, $wgMessageCache, $wgLogo;
1732 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1733 # Hard coding strings instead.
1735 $noconnect = "<h1><img src='$wgLogo' style='float:left;margin-right:1em' alt=''>$wgSitename has a problem</h1><p><strong>Sorry! This site is experiencing technical difficulties.</strong></p><p>Try waiting a few minutes and reloading.</p><p><small>(Can't contact the database server: $1)</small></p>";
1736 $mainpage = 'Main Page';
1737 $searchdisabled = <<<EOT
1738 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1739 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1743 <!-- SiteSearch Google -->
1744 <FORM method=GET action=\"http://www.google.com/search\">
1745 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1746 <A HREF=\"http://www.google.com/\">
1747 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1748 border=\"0\" ALT=\"Google\"></A>
1751 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1752 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1754 <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 />
1755 <input type='hidden' name='ie' value='$2'>
1756 <input type='hidden' name='oe' value='$2'>
1760 <!-- SiteSearch Google -->";
1761 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1764 if( !headers_sent() ) {
1765 header( 'HTTP/1.0 500 Internal Server Error' );
1766 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1767 /* Don't cache error pages! They cause no end of trouble... */
1768 header( 'Cache-control: none' );
1769 header( 'Pragma: nocache' );
1772 # No database access
1773 if ( is_object( $wgMessageCache ) ) {
1774 $wgMessageCache->disable();
1777 if ( trim( $error ) == '' ) {
1778 $error = $this->mServer
;
1781 wfLogDBError( "Connection error: $error\n" );
1783 $msg = wfGetSiteNotice();
1785 $msg = str_replace( '$1', $error, $noconnect );
1789 if($wgUseFileCache) {
1794 $t = Title
::newFromURL( $title );
1795 } elseif (@/**/$_REQUEST['search']) {
1796 $search = $_REQUEST['search'];
1797 echo $searchdisabled;
1798 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1799 $wgInputEncoding ), $googlesearch );
1802 $t = Title
::newFromText( $mainpage );
1806 $cache = new CacheManager( $t );
1807 if( $cache->isFileCached() ) {
1808 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1809 $cachederror . "</b></p>\n";
1811 $tag = '<div id="article">';
1812 $text = str_replace(
1815 $cache->fetchPageText() );