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;
65 var $mLBInfo = array();
68 #------------------------------------------------------------------------------
70 #------------------------------------------------------------------------------
71 # These optionally set a variable and return the previous state
74 * Fail function, takes a Database as a parameter
75 * Set to false for default, 1 for ignore errors
77 function failFunction( $function = NULL ) {
78 return wfSetVar( $this->mFailFunction
, $function );
82 * Output page, used for reporting errors
83 * FALSE means discard output
85 function &setOutputPage( &$out ) {
90 * Boolean, controls output of large amounts of debug information
92 function debug( $debug = NULL ) {
93 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
97 * Turns buffering of SQL result sets on (true) or off (false).
98 * Default is "on" and it should not be changed without good reasons.
100 function bufferResults( $buffer = NULL ) {
101 if ( is_null( $buffer ) ) {
102 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
104 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
109 * Turns on (false) or off (true) the automatic generation and sending
110 * of a "we're sorry, but there has been a database error" page on
111 * database errors. Default is on (false). When turned off, the
112 * code should use wfLastErrno() and wfLastError() to handle the
113 * situation as appropriate.
115 function ignoreErrors( $ignoreErrors = NULL ) {
116 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
120 * The current depth of nested transactions
121 * @param integer $level
123 function trxLevel( $level = NULL ) {
124 return wfSetVar( $this->mTrxLevel
, $level );
128 * Number of errors logged, only useful when errors are ignored
130 function errorCount( $count = NULL ) {
131 return wfSetVar( $this->mErrorCount
, $count );
135 * Properties passed down from the server info array of the load balancer
137 function getLBInfo( $name = NULL ) {
138 if ( is_null( $name ) ) {
139 return $this->mLBInfo
;
141 if ( array_key_exists( $name, $this->mLBInfo
) ) {
142 return $this->mLBInfo
[$name];
149 function setLBInfo( $name, $value = NULL ) {
150 if ( is_null( $value ) ) {
151 $this->mLBInfo
= $name;
153 $this->mLBInfo
[$name] = $value;
160 function lastQuery() { return $this->mLastQuery
; }
161 function isOpen() { return $this->mOpened
; }
164 function setFlag( $flag ) {
165 $this->mFlags |
= $flag;
168 function clearFlag( $flag ) {
169 $this->mFlags
&= ~
$flag;
172 function getFlag( $flag ) {
173 return !!($this->mFlags
& $flag);
176 #------------------------------------------------------------------------------
178 #------------------------------------------------------------------------------
181 * @param string $server database server host
182 * @param string $user database user name
183 * @param string $password database user password
184 * @param string $dbname database name
188 * @param failFunction
190 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
192 function Database( $server = false, $user = false, $password = false, $dbName = false,
193 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
195 global $wgOut, $wgDBprefix, $wgCommandLineMode;
196 # Can't get a reference if it hasn't been set yet
197 if ( !isset( $wgOut ) ) {
200 $this->mOut
=& $wgOut;
202 $this->mFailFunction
= $failFunction;
203 $this->mFlags
= $flags;
205 if ( $this->mFlags
& DBO_DEFAULT
) {
206 if ( $wgCommandLineMode ) {
207 $this->mFlags
&= ~DBO_TRX
;
209 $this->mFlags |
= DBO_TRX
;
214 // Faster read-only access
215 if ( wfReadOnly() ) {
216 $this->mFlags |= DBO_PERSISTENT;
217 $this->mFlags &= ~DBO_TRX;
220 /** Get the default table prefix*/
221 if ( $tablePrefix == 'get from global' ) {
222 $this->mTablePrefix
= $wgDBprefix;
224 $this->mTablePrefix
= $tablePrefix;
228 $this->open( $server, $user, $password, $dbName );
234 * @param failFunction
237 function newFromParams( $server, $user, $password, $dbName,
238 $failFunction = false, $flags = 0 )
240 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
244 * Usually aborts on failure
245 * If the failFunction is set to a non-zero integer, returns success
247 function open( $server, $user, $password, $dbName ) {
250 # Test for missing mysql.so
251 # First try to load it
252 if (!@extension_loaded
('mysql')) {
256 # Otherwise we get a suppressed fatal error, which is very hard to track down
257 if ( !function_exists( 'mysql_connect' ) ) {
258 wfDie( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
262 $this->mServer
= $server;
263 $this->mUser
= $user;
264 $this->mPassword
= $password;
265 $this->mDBname
= $dbName;
269 if ( $this->mFlags
& DBO_PERSISTENT
) {
270 @/**/$this->mConn
= mysql_pconnect( $server, $user, $password );
272 # Create a new connection...
273 if( version_compare( PHP_VERSION
, '4.2.0', 'ge' ) ) {
274 @/**/$this->mConn
= mysql_connect( $server, $user, $password, true );
276 # On PHP 4.1 the new_link parameter is not available. We cannot
277 # guarantee that we'll actually get a new connection, and this
278 # may cause some operations to fail possibly.
279 @/**/$this->mConn
= mysql_connect( $server, $user, $password );
283 if ( $dbName != '' ) {
284 if ( $this->mConn
!== false ) {
285 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
287 $error = "Error selecting database $dbName on server {$this->mServer} " .
288 "from client host {$wguname['nodename']}\n";
292 wfDebug( "DB connection error\n" );
293 wfDebug( "Server: $server, User: $user, Password: " .
294 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
299 $success = (bool)$this->mConn
;
303 $this->reportConnectionError();
308 // Tell the server we're communicating with it in UTF-8.
309 // This may engage various charset conversions.
310 $this->query( 'SET NAMES utf8' );
313 $this->mOpened
= $success;
319 * Closes a database connection.
320 * if it is open : commits any open transactions
322 * @return bool operation success. true if already closed.
326 $this->mOpened
= false;
327 if ( $this->mConn
) {
328 if ( $this->trxLevel() ) {
329 $this->immediateCommit();
331 return mysql_close( $this->mConn
);
339 * @param string $error fallback error message, used if none is given by MySQL
341 function reportConnectionError( $error = 'Unknown error' ) {
342 $myError = $this->lastError();
347 if ( $this->mFailFunction
) {
348 if ( !is_int( $this->mFailFunction
) ) {
349 $ff = $this->mFailFunction
;
350 $ff( $this, $error );
353 wfEmergencyAbort( $this, $error );
358 * Usually aborts on failure
359 * If errors are explicitly ignored, returns success
361 function query( $sql, $fname = '', $tempIgnore = false ) {
364 if ( $wgProfiling ) {
365 # generalizeSQL will probably cut down the query to reasonable
366 # logging size most of the time. The substr is really just a sanity check.
368 # Who's been wasting my precious column space? -- TS
369 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
370 $profName = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
372 wfProfileIn( 'Database::query' );
373 wfProfileIn( $profName );
376 $this->mLastQuery
= $sql;
378 # Add a comment for easy SHOW PROCESSLIST interpretation
380 $commentedSql = preg_replace("/\s/", " /* $fname */ ", $sql, 1);
382 $commentedSql = $sql;
385 # If DBO_TRX is set, start a transaction
386 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() && $sql != 'BEGIN' ) {
390 if ( $this->debug() ) {
391 $sqlx = substr( $commentedSql, 0, 500 );
392 $sqlx = strtr( $sqlx, "\t\n", ' ' );
393 wfDebug( "SQL: $sqlx\n" );
396 # Do the query and handle errors
397 $ret = $this->doQuery( $commentedSql );
399 # Try reconnecting if the connection was lost
400 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
401 # Transaction is gone, like it or not
402 $this->mTrxLevel
= 0;
403 wfDebug( "Connection lost, reconnecting...\n" );
404 if ( $this->ping() ) {
405 wfDebug( "Reconnected\n" );
406 $ret = $this->doQuery( $commentedSql );
408 wfDebug( "Failed\n" );
412 if ( false === $ret ) {
413 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
416 if ( $wgProfiling ) {
417 wfProfileOut( $profName );
418 wfProfileOut( 'Database::query' );
424 * The DBMS-dependent part of query()
425 * @param string $sql SQL query.
427 function doQuery( $sql ) {
428 if( $this->bufferResults() ) {
429 $ret = mysql_query( $sql, $this->mConn
);
431 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
440 * @param string $fname
441 * @param bool $tempIgnore
443 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
444 global $wgCommandLineMode, $wgFullyInitialised;
445 # Ignore errors during error handling to avoid infinite recursion
446 $ignore = $this->ignoreErrors( true );
447 ++
$this->mErrorCount
;
449 if( $ignore ||
$tempIgnore ) {
450 wfDebug("SQL ERROR (ignored): $error\n");
452 $sql1line = str_replace( "\n", "\\n", $sql );
453 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
454 wfDebug("SQL ERROR: " . $error . "\n");
455 if ( $wgCommandLineMode ||
!$this->mOut ||
empty( $wgFullyInitialised ) ) {
456 $message = "A database error has occurred\n" .
458 "Function: $fname\n" .
459 "Error: $errno $error\n";
460 if ( !$wgCommandLineMode ) {
461 $message = nl2br( $message );
463 wfDebugDieBacktrace( $message );
465 // this calls wfAbruptExit()
466 $this->mOut
->databaseError( $fname, $sql, $error, $errno );
469 $this->ignoreErrors( $ignore );
474 * Intended to be compatible with the PEAR::DB wrapper functions.
475 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
477 * ? = scalar value, quoted as necessary
478 * ! = raw SQL bit (a function for instance)
479 * & = filename; reads the file and inserts as a blob
480 * (we don't use this though...)
482 function prepare( $sql, $func = 'Database::prepare' ) {
483 /* MySQL doesn't support prepared statements (yet), so just
484 pack up the query for reference. We'll manually replace
486 return array( 'query' => $sql, 'func' => $func );
489 function freePrepared( $prepared ) {
490 /* No-op for MySQL */
494 * Execute a prepared query with the various arguments
495 * @param string $prepared the prepared sql
496 * @param mixed $args Either an array here, or put scalars as varargs
498 function execute( $prepared, $args = null ) {
499 if( !is_array( $args ) ) {
501 $args = func_get_args();
502 array_shift( $args );
504 $sql = $this->fillPrepared( $prepared['query'], $args );
505 return $this->query( $sql, $prepared['func'] );
509 * Prepare & execute an SQL statement, quoting and inserting arguments
510 * in the appropriate places.
511 * @param string $query
512 * @param string $args ...
514 function safeQuery( $query, $args = null ) {
515 $prepared = $this->prepare( $query, 'Database::safeQuery' );
516 if( !is_array( $args ) ) {
518 $args = func_get_args();
519 array_shift( $args );
521 $retval = $this->execute( $prepared, $args );
522 $this->freePrepared( $prepared );
527 * For faking prepared SQL statements on DBs that don't support
529 * @param string $preparedSql - a 'preparable' SQL statement
530 * @param array $args - array of arguments to fill it with
531 * @return string executable SQL
533 function fillPrepared( $preparedQuery, $args ) {
536 $this->preparedArgs
=& $args;
537 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
538 array( &$this, 'fillPreparedArg' ), $preparedQuery );
542 * preg_callback func for fillPrepared()
543 * The arguments should be in $this->preparedArgs and must not be touched
544 * while we're doing this.
546 * @param array $matches
550 function fillPreparedArg( $matches ) {
551 switch( $matches[1] ) {
552 case '\\?': return '?';
553 case '\\!': return '!';
554 case '\\&': return '&';
556 list( $n, $arg ) = each( $this->preparedArgs
);
557 switch( $matches[1] ) {
558 case '?': return $this->addQuotes( $arg );
559 case '!': return $arg;
561 # return $this->addQuotes( file_get_contents( $arg ) );
562 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
564 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
569 * @param mixed $res A SQL result
572 * Free a result object
574 function freeResult( $res ) {
575 if ( !@/**/mysql_free_result( $res ) ) {
576 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
581 * Fetch the next row from the given result object, in object form
583 function fetchObject( $res ) {
584 @/**/$row = mysql_fetch_object( $res );
585 if( mysql_errno() ) {
586 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
592 * Fetch the next row from the given result object
595 function fetchRow( $res ) {
596 @/**/$row = mysql_fetch_array( $res );
597 if (mysql_errno() ) {
598 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
604 * Get the number of rows in a result object
606 function numRows( $res ) {
607 @/**/$n = mysql_num_rows( $res );
608 if( mysql_errno() ) {
609 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
615 * Get the number of fields in a result object
616 * See documentation for mysql_num_fields()
618 function numFields( $res ) { return mysql_num_fields( $res ); }
621 * Get a field name in a result object
622 * See documentation for mysql_field_name()
624 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
627 * Get the inserted value of an auto-increment row
629 * The value inserted should be fetched from nextSequenceValue()
632 * $id = $dbw->nextSequenceValue('page_page_id_seq');
633 * $dbw->insert('page',array('page_id' => $id));
634 * $id = $dbw->insertId();
636 function insertId() { return mysql_insert_id( $this->mConn
); }
639 * Change the position of the cursor in a result object
640 * See mysql_data_seek()
642 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
645 * Get the last error number
648 function lastErrno() {
649 if ( $this->mConn
) {
650 return mysql_errno( $this->mConn
);
652 return mysql_errno();
657 * Get a description of the last error
658 * See mysql_error() for more details
660 function lastError() {
661 if ( $this->mConn
) {
662 # Even if it's non-zero, it can still be invalid
663 wfSuppressWarnings();
664 $error = mysql_error( $this->mConn
);
666 $error = mysql_error();
670 $error = mysql_error();
673 $error .= ' (' . $this->mServer
. ')';
678 * Get the number of rows affected by the last write query
679 * See mysql_affected_rows() for more details
681 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
682 /**#@-*/ // end of template : @param $result
685 * Simple UPDATE wrapper
686 * Usually aborts on failure
687 * If errors are explicitly ignored, returns success
689 * This function exists for historical reasons, Database::update() has a more standard
690 * calling convention and feature set
692 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
694 $table = $this->tableName( $table );
695 $sql = "UPDATE $table SET $var = '" .
696 $this->strencode( $value ) . "' WHERE ($cond)";
697 return (bool)$this->query( $sql, $fname );
701 * Simple SELECT wrapper, returns a single field, input must be encoded
702 * Usually aborts on failure
703 * If errors are explicitly ignored, returns FALSE on failure
705 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
706 if ( !is_array( $options ) ) {
707 $options = array( $options );
709 $options['LIMIT'] = 1;
711 $res = $this->select( $table, $var, $cond, $fname, $options );
712 if ( $res === false ||
!$this->numRows( $res ) ) {
715 $row = $this->fetchRow( $res );
716 if ( $row !== false ) {
717 $this->freeResult( $res );
725 * Returns an optional USE INDEX clause to go after the table, and a
726 * string to go at the end of the query
730 * @param array $options an associative array of options to be turned into
731 * an SQL query, valid keys are listed in the function.
734 function makeSelectOptions( $options ) {
737 if ( isset( $options['GROUP BY'] ) ) {
738 $tailOpts .= " GROUP BY {$options['GROUP BY']}";
740 if ( isset( $options['ORDER BY'] ) ) {
741 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
743 if (isset($options['LIMIT'])) {
744 $tailOpts .= $this->limitResult('', $options['LIMIT'],
745 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
747 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
748 $tailOpts .= ' FOR UPDATE';
751 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
752 $tailOpts .= ' LOCK IN SHARE MODE';
755 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
756 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
760 return array( $useIndex, $tailOpts );
766 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
768 if( is_array( $vars ) ) {
769 $vars = implode( ',', $vars );
771 if( !is_array( $options ) ) {
772 $options = array( $options );
774 if( is_array( $table ) ) {
775 if ( @is_array
( $options['USE INDEX'] ) )
776 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
778 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
779 } elseif ($table!='') {
780 $from = ' FROM ' . $this->tableName( $table );
785 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
787 if( !empty( $conds ) ) {
788 if ( is_array( $conds ) ) {
789 $conds = $this->makeList( $conds, LIST_AND
);
791 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
793 $sql = "SELECT $vars $from $useIndex $tailOpts";
796 return $this->query( $sql, $fname );
800 * Single row SELECT wrapper
801 * Aborts or returns FALSE on error
803 * $vars: the selected variables
804 * $conds: a condition map, terms are ANDed together.
805 * Items with numeric keys are taken to be literal conditions
806 * Takes an array of selected variables, and a condition map, which is ANDed
807 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
808 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
809 * $obj- >page_id is the ID of the Astronomy article
811 * @todo migrate documentation to phpdocumentor format
813 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
814 $options['LIMIT'] = 1;
815 $res = $this->select( $table, $vars, $conds, $fname, $options );
816 if ( $res === false )
818 if ( !$this->numRows($res) ) {
819 $this->freeResult($res);
822 $obj = $this->fetchObject( $res );
823 $this->freeResult( $res );
829 * Removes most variables from an SQL query and replaces them with X or N for numbers.
830 * It's only slightly flawed. Don't use for anything important.
832 * @param string $sql A SQL Query
835 function generalizeSQL( $sql ) {
836 # This does the same as the regexp below would do, but in such a way
837 # as to avoid crashing php on some large strings.
838 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
840 $sql = str_replace ( "\\\\", '', $sql);
841 $sql = str_replace ( "\\'", '', $sql);
842 $sql = str_replace ( "\\\"", '', $sql);
843 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
844 $sql = preg_replace ('/".*"/s', "'X'", $sql);
846 # All newlines, tabs, etc replaced by single space
847 $sql = preg_replace ( "/\s+/", ' ', $sql);
850 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
856 * Determines whether a field exists in a table
857 * Usually aborts on failure
858 * If errors are explicitly ignored, returns NULL on failure
860 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
861 $table = $this->tableName( $table );
862 $res = $this->query( 'DESCRIBE '.$table, $fname );
869 while ( $row = $this->fetchObject( $res ) ) {
870 if ( $row->Field
== $field ) {
879 * Determines whether an index exists
880 * Usually aborts on failure
881 * If errors are explicitly ignored, returns NULL on failure
883 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
884 $info = $this->indexInfo( $table, $index, $fname );
885 if ( is_null( $info ) ) {
888 return $info !== false;
894 * Get information about an index into an object
895 * Returns false if the index does not exist
897 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
898 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
899 # SHOW INDEX should work for 3.x and up:
900 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
901 $table = $this->tableName( $table );
902 $sql = 'SHOW INDEX FROM '.$table;
903 $res = $this->query( $sql, $fname );
908 while ( $row = $this->fetchObject( $res ) ) {
909 if ( $row->Key_name
== $index ) {
917 * Query whether a given table exists
919 function tableExists( $table ) {
920 $table = $this->tableName( $table );
921 $old = $this->ignoreErrors( true );
922 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
923 $this->ignoreErrors( $old );
925 $this->freeResult( $res );
933 * mysql_fetch_field() wrapper
934 * Returns false if the field doesn't exist
939 function fieldInfo( $table, $field ) {
940 $table = $this->tableName( $table );
941 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
942 $n = mysql_num_fields( $res );
943 for( $i = 0; $i < $n; $i++
) {
944 $meta = mysql_fetch_field( $res, $i );
945 if( $field == $meta->name
) {
953 * mysql_field_type() wrapper
955 function fieldType( $res, $index ) {
956 return mysql_field_type( $res, $index );
960 * Determines if a given index is unique
962 function indexUnique( $table, $index ) {
963 $indexInfo = $this->indexInfo( $table, $index );
967 return !$indexInfo->Non_unique
;
971 * INSERT wrapper, inserts an array into a table
973 * $a may be a single associative array, or an array of these with numeric keys, for
976 * Usually aborts on failure
977 * If errors are explicitly ignored, returns success
979 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
980 # No rows to insert, easy just return now
981 if ( !count( $a ) ) {
985 $table = $this->tableName( $table );
986 if ( !is_array( $options ) ) {
987 $options = array( $options );
989 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
991 $keys = array_keys( $a[0] );
994 $keys = array_keys( $a );
997 $sql = 'INSERT ' . implode( ' ', $options ) .
998 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1002 foreach ( $a as $row ) {
1008 $sql .= '(' . $this->makeList( $row ) . ')';
1011 $sql .= '(' . $this->makeList( $a ) . ')';
1013 return (bool)$this->query( $sql, $fname );
1017 * Make UPDATE options for the Database::update function
1020 * @param array $options The options passed to Database::update
1023 function makeUpdateOptions( $options ) {
1024 if( !is_array( $options ) ) {
1025 $options = array( $options );
1028 if ( in_array( 'LOW_PRIORITY', $options ) )
1029 $opts[] = $this->lowPriorityOption();
1030 if ( in_array( 'IGNORE', $options ) )
1032 return implode(' ', $opts);
1036 * UPDATE wrapper, takes a condition array and a SET array
1038 * @param string $table The table to UPDATE
1039 * @param array $values An array of values to SET
1040 * @param array $conds An array of conditions (WHERE)
1041 * @param string $fname The Class::Function calling this function
1043 * @param array $options An array of UPDATE options, can be one or
1044 * more of IGNORE, LOW_PRIORITY
1046 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1047 $table = $this->tableName( $table );
1048 $opts = $this->makeUpdateOptions( $options );
1049 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1050 if ( $conds != '*' ) {
1051 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1053 $this->query( $sql, $fname );
1057 * Makes a wfStrencoded list from an array
1058 * $mode: LIST_COMMA - comma separated, no field names
1059 * LIST_AND - ANDed WHERE clause (without the WHERE)
1060 * LIST_SET - comma separated with field names, like a SET clause
1061 * LIST_NAMES - comma separated field names
1063 function makeList( $a, $mode = LIST_COMMA
) {
1064 if ( !is_array( $a ) ) {
1065 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
1070 foreach ( $a as $field => $value ) {
1072 if ( $mode == LIST_AND
) {
1074 } elseif($mode == LIST_OR
) {
1082 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1083 $list .= "($value)";
1084 } elseif ( $mode == LIST_AND
&& is_array ($value) ) {
1085 $list .= $field." IN (".$this->makeList($value).") ";
1087 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1088 $list .= "$field = ";
1090 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1097 * Change the current database
1099 function selectDB( $db ) {
1100 $this->mDBname
= $db;
1101 return mysql_select_db( $db, $this->mConn
);
1105 * Format a table name ready for use in constructing an SQL query
1107 * This does two important things: it quotes table names which as necessary,
1108 * and it adds a table prefix if there is one.
1110 * All functions of this object which require a table name call this function
1111 * themselves. Pass the canonical name to such functions. This is only needed
1112 * when calling query() directly.
1114 * @param string $name database table name
1116 function tableName( $name ) {
1118 # Skip quoted literals
1119 if ( $name{0} != '`' ) {
1120 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
1121 $name = "{$this->mTablePrefix}$name";
1123 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1124 $name = "`$wgSharedDB`.`$name`";
1134 * Fetch a number of table names into an array
1135 * This is handy when you need to construct SQL for joins
1138 * extract($dbr->tableNames('user','watchlist'));
1139 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1140 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1142 function tableNames() {
1143 $inArray = func_get_args();
1145 foreach ( $inArray as $name ) {
1146 $retVal[$name] = $this->tableName( $name );
1154 function tableNamesWithUseIndex( $tables, $use_index ) {
1157 foreach ( $tables as $table )
1158 if ( @$use_index[$table] !== null )
1159 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1161 $ret[] = $this->tableName( $table );
1163 return implode( ',', $ret );
1167 * Wrapper for addslashes()
1168 * @param string $s String to be slashed.
1169 * @return string slashed string.
1171 function strencode( $s ) {
1172 return addslashes( $s );
1176 * If it's a string, adds quotes and backslashes
1177 * Otherwise returns as-is
1179 function addQuotes( $s ) {
1180 if ( is_null( $s ) ) {
1183 # This will also quote numeric values. This should be harmless,
1184 # and protects against weird problems that occur when they really
1185 # _are_ strings such as article titles and string->number->string
1186 # conversion is not 1:1.
1187 return "'" . $this->strencode( $s ) . "'";
1192 * Escape string for safe LIKE usage
1194 function escapeLike( $s ) {
1195 $s=$this->strencode( $s );
1196 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1201 * Returns an appropriately quoted sequence value for inserting a new row.
1202 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1203 * subclass will return an integer, and save the value for insertId()
1205 function nextSequenceValue( $seqName ) {
1211 * PostgreSQL doesn't have them and returns ""
1213 function useIndexClause( $index ) {
1214 return "FORCE INDEX ($index)";
1218 * REPLACE query wrapper
1219 * PostgreSQL simulates this with a DELETE followed by INSERT
1220 * $row is the row to insert, an associative array
1221 * $uniqueIndexes is an array of indexes. Each element may be either a
1222 * field name or an array of field names
1224 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1225 * However if you do this, you run the risk of encountering errors which wouldn't have
1228 * @todo migrate comment to phodocumentor format
1230 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1231 $table = $this->tableName( $table );
1234 if ( !is_array( reset( $rows ) ) ) {
1235 $rows = array( $rows );
1238 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1240 foreach ( $rows as $row ) {
1246 $sql .= '(' . $this->makeList( $row ) . ')';
1248 return $this->query( $sql, $fname );
1252 * DELETE where the condition is a join
1253 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1255 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1256 * join condition matches, set $conds='*'
1258 * DO NOT put the join condition in $conds
1260 * @param string $delTable The table to delete from.
1261 * @param string $joinTable The other table.
1262 * @param string $delVar The variable to join on, in the first table.
1263 * @param string $joinVar The variable to join on, in the second table.
1264 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1266 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1268 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1271 $delTable = $this->tableName( $delTable );
1272 $joinTable = $this->tableName( $joinTable );
1273 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1274 if ( $conds != '*' ) {
1275 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1278 return $this->query( $sql, $fname );
1282 * Returns the size of a text field, or -1 for "unlimited"
1284 function textFieldSize( $table, $field ) {
1285 $table = $this->tableName( $table );
1286 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1287 $res = $this->query( $sql, 'Database::textFieldSize' );
1288 $row = $this->fetchObject( $res );
1289 $this->freeResult( $res );
1291 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
1300 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1302 function lowPriorityOption() {
1303 return 'LOW_PRIORITY';
1307 * DELETE query wrapper
1309 * Use $conds == "*" to delete all rows
1311 function delete( $table, $conds, $fname = 'Database::delete' ) {
1313 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1315 $table = $this->tableName( $table );
1316 $sql = "DELETE FROM $table";
1317 if ( $conds != '*' ) {
1318 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1320 return $this->query( $sql, $fname );
1324 * INSERT SELECT wrapper
1325 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1326 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1327 * $conds may be "*" to copy the whole table
1328 * srcTable may be an array of tables.
1330 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1331 $options = array() )
1333 $destTable = $this->tableName( $destTable );
1334 if ( is_array( $options ) ) {
1335 $options = implode( ' ', $options );
1337 if( is_array( $srcTable ) ) {
1338 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1340 $srcTable = $this->tableName( $srcTable );
1342 $sql = "INSERT $options INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1343 ' SELECT ' . implode( ',', $varMap ) .
1345 if ( $conds != '*' ) {
1346 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1348 return $this->query( $sql, $fname );
1352 * Construct a LIMIT query with optional offset
1353 * This is used for query pages
1354 * $sql string SQL query we will append the limit too
1355 * $limit integer the SQL limit
1356 * $offset integer the SQL offset (default false)
1358 function limitResult($sql, $limit, $offset=false) {
1359 return " $sql LIMIT ".((is_numeric($offset) && $offset != 0)?
"{$offset},":"")."{$limit} ";
1361 function limitResultForUpdate($sql, $num) {
1362 return $this->limitResult($sql, $num, 0);
1366 * Returns an SQL expression for a simple conditional.
1369 * @param string $cond SQL expression which will result in a boolean value
1370 * @param string $trueVal SQL expression to return if true
1371 * @param string $falseVal SQL expression to return if false
1372 * @return string SQL fragment
1374 function conditional( $cond, $trueVal, $falseVal ) {
1375 return " IF($cond, $trueVal, $falseVal) ";
1379 * Determines if the last failure was due to a deadlock
1381 function wasDeadlock() {
1382 return $this->lastErrno() == 1213;
1386 * Perform a deadlock-prone transaction.
1388 * This function invokes a callback function to perform a set of write
1389 * queries. If a deadlock occurs during the processing, the transaction
1390 * will be rolled back and the callback function will be called again.
1393 * $dbw->deadlockLoop( callback, ... );
1395 * Extra arguments are passed through to the specified callback function.
1397 * Returns whatever the callback function returned on its successful,
1398 * iteration, or false on error, for example if the retry limit was
1401 function deadlockLoop() {
1402 $myFname = 'Database::deadlockLoop';
1405 $args = func_get_args();
1406 $function = array_shift( $args );
1407 $oldIgnore = $this->ignoreErrors( true );
1408 $tries = DEADLOCK_TRIES
;
1409 if ( is_array( $function ) ) {
1410 $fname = $function[0];
1415 $retVal = call_user_func_array( $function, $args );
1416 $error = $this->lastError();
1417 $errno = $this->lastErrno();
1418 $sql = $this->lastQuery();
1421 if ( $this->wasDeadlock() ) {
1423 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1425 $this->reportQueryError( $error, $errno, $sql, $fname );
1428 } while( $this->wasDeadlock() && --$tries > 0 );
1429 $this->ignoreErrors( $oldIgnore );
1430 if ( $tries <= 0 ) {
1431 $this->query( 'ROLLBACK', $myFname );
1432 $this->reportQueryError( $error, $errno, $sql, $fname );
1435 $this->query( 'COMMIT', $myFname );
1441 * Do a SELECT MASTER_POS_WAIT()
1443 * @param string $file the binlog file
1444 * @param string $pos the binlog position
1445 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1447 function masterPosWait( $file, $pos, $timeout ) {
1448 $fname = 'Database::masterPosWait';
1449 wfProfileIn( $fname );
1452 # Commit any open transactions
1453 $this->immediateCommit();
1455 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1456 $encFile = $this->strencode( $file );
1457 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1458 $res = $this->doQuery( $sql );
1459 if ( $res && $row = $this->fetchRow( $res ) ) {
1460 $this->freeResult( $res );
1461 wfProfileOut( $fname );
1464 wfProfileOut( $fname );
1470 * Get the position of the master from SHOW SLAVE STATUS
1472 function getSlavePos() {
1473 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1474 $row = $this->fetchObject( $res );
1476 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1478 return array( false, false );
1483 * Get the position of the master from SHOW MASTER STATUS
1485 function getMasterPos() {
1486 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1487 $row = $this->fetchObject( $res );
1489 return array( $row->File
, $row->Position
);
1491 return array( false, false );
1496 * Begin a transaction, or if a transaction has already started, continue it
1498 function begin( $fname = 'Database::begin' ) {
1499 if ( !$this->mTrxLevel
) {
1500 $this->immediateBegin( $fname );
1507 * End a transaction, or decrement the nest level if transactions are nested
1509 function commit( $fname = 'Database::commit' ) {
1510 if ( $this->mTrxLevel
) {
1513 if ( !$this->mTrxLevel
) {
1514 $this->immediateCommit( $fname );
1519 * Rollback a transaction
1521 function rollback( $fname = 'Database::rollback' ) {
1522 $this->query( 'ROLLBACK', $fname );
1523 $this->mTrxLevel
= 0;
1527 * Begin a transaction, committing any previously open transaction
1529 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1530 $this->query( 'BEGIN', $fname );
1531 $this->mTrxLevel
= 1;
1535 * Commit transaction, if one is open
1537 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1538 $this->query( 'COMMIT', $fname );
1539 $this->mTrxLevel
= 0;
1543 * Return MW-style timestamp used for MySQL schema
1545 function timestamp( $ts=0 ) {
1546 return wfTimestamp(TS_MW
,$ts);
1550 * Local database timestamp format or null
1552 function timestampOrNull( $ts = null ) {
1553 if( is_null( $ts ) ) {
1556 return $this->timestamp( $ts );
1563 function resultObject( $result ) {
1564 if( empty( $result ) ) {
1567 return new ResultWrapper( $this, $result );
1572 * Return aggregated value alias
1574 function aggregateValue ($valuedata,$valuename='value') {
1579 * @return string wikitext of a link to the server software's web site
1581 function getSoftwareLink() {
1582 return "[http://www.mysql.com/ MySQL]";
1586 * @return string Version information from the database
1588 function getServerVersion() {
1589 return mysql_get_server_info();
1593 * Ping the server and try to reconnect if it there is no connection
1596 if( function_exists( 'mysql_ping' ) ) {
1597 return mysql_ping( $this->mConn
);
1599 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1606 * At the moment, this will only work if the DB user has the PROCESS privilege
1609 $res = $this->query( 'SHOW PROCESSLIST' );
1610 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1611 # dubious, but unfortunately there's no easy rigorous way
1613 while ( $row = $this->fetchObject( $res ) ) {
1614 if ( $row->User
== 'system user' ) {
1615 if ( ++
$slaveThreads == 2 ) {
1616 # This is it, return the time (except -ve)
1617 if ( $row->Time
> 1>>31 ) {
1629 * Get status information from SHOW STATUS in an associative array
1631 function getStatus($which="%") {
1632 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1634 while ( $row = $this->fetchObject( $res ) ) {
1635 $status[$row->Variable_name
] = $row->Value
;
1641 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1643 function maxListLen() {
1647 function encodeBlob($b) {
1652 * Read and execute SQL commands from a file.
1653 * Returns true on success, error string on failure
1655 function sourceFile( $filename ) {
1656 $fp = fopen( $filename, 'r' );
1657 if ( false === $fp ) {
1658 return "Could not open \"{$fname}\".\n";
1664 while ( ! feof( $fp ) ) {
1665 $line = trim( fgets( $fp, 1024 ) );
1666 $sl = strlen( $line ) - 1;
1668 if ( $sl < 0 ) { continue; }
1669 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
1671 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
1673 $line = substr( $line, 0, $sl );
1676 if ( '' != $cmd ) { $cmd .= ' '; }
1680 $cmd = str_replace(';;', ";", $cmd);
1681 $cmd = $this->replaceVars( $cmd );
1682 $res = $this->query( $cmd, 'dbsource', true );
1684 if ( false === $res ) {
1685 $err = $this->lastError();
1686 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1698 * Replace variables in sourced SQL
1700 function replaceVars( $ins ) {
1702 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
1703 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
1704 'wgDBadminuser', 'wgDBadminpassword',
1707 // Ordinary variables
1708 foreach ( $varnames as $var ) {
1709 if( isset( $GLOBALS[$var] ) ) {
1710 $val = addslashes( $GLOBALS[$var] );
1711 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1712 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1713 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1718 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
1719 array( &$this, 'tableNameCallback' ), $ins );
1724 * Table name callback
1727 function tableNameCallback( $matches ) {
1728 return $this->tableName( $matches[1] );
1734 * Database abstraction object for mySQL
1735 * Inherit all methods and properties of Database::Database()
1737 * @package MediaWiki
1740 class DatabaseMysql
extends Database
{
1746 * Result wrapper for grabbing data queried by someone else
1748 * @package MediaWiki
1750 class ResultWrapper
{
1756 function ResultWrapper( &$database, $result ) {
1757 $this->db
=& $database;
1758 $this->result
=& $result;
1764 function numRows() {
1765 return $this->db
->numRows( $this->result
);
1771 function fetchObject() {
1772 return $this->db
->fetchObject( $this->result
);
1778 function &fetchRow() {
1779 return $this->db
->fetchRow( $this->result
);
1786 $this->db
->freeResult( $this->result
);
1787 unset( $this->result
);
1791 function seek( $row ) {
1792 $this->db
->dataSeek( $this->result
, $row );
1798 #------------------------------------------------------------------------------
1800 #------------------------------------------------------------------------------
1803 * Standard fail function, called by default when a connection cannot be
1805 * Displays the file cache if possible
1807 function wfEmergencyAbort( &$conn, $error ) {
1808 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1809 global $wgSitename, $wgServer, $wgMessageCache, $wgLogo;
1811 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1812 # Hard coding strings instead.
1814 $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>";
1815 $mainpage = 'Main Page';
1816 $searchdisabled = <<<EOT
1817 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1818 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1822 <!-- SiteSearch Google -->
1823 <FORM method=GET action=\"http://www.google.com/search\">
1824 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1825 <A HREF=\"http://www.google.com/\">
1826 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1827 border=\"0\" ALT=\"Google\"></A>
1830 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1831 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1833 <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 />
1834 <input type='hidden' name='ie' value='$2'>
1835 <input type='hidden' name='oe' value='$2'>
1839 <!-- SiteSearch Google -->";
1840 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1843 if( !headers_sent() ) {
1844 header( 'HTTP/1.0 500 Internal Server Error' );
1845 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1846 /* Don't cache error pages! They cause no end of trouble... */
1847 header( 'Cache-control: none' );
1848 header( 'Pragma: nocache' );
1851 # No database access
1852 if ( is_object( $wgMessageCache ) ) {
1853 $wgMessageCache->disable();
1856 if ( trim( $error ) == '' ) {
1857 $error = $this->mServer
;
1860 wfLogDBError( "Connection error: $error\n" );
1862 $text = str_replace( '$1', $error, $noconnect );
1863 $text .= wfGetSiteNotice();
1865 if($wgUseFileCache) {
1870 $t = Title
::newFromURL( $title );
1871 } elseif (@/**/$_REQUEST['search']) {
1872 $search = $_REQUEST['search'];
1873 echo $searchdisabled;
1874 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1875 $wgInputEncoding ), $googlesearch );
1878 $t = Title
::newFromText( $mainpage );
1882 $cache = new CacheManager( $t );
1883 if( $cache->isFileCached() ) {
1884 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1885 $cachederror . "</b></p>\n";
1887 $tag = '<div id="article">';
1888 $text = str_replace(
1891 $cache->fetchPageText() );