3 # This file deals with MySQL interface functions
4 # and query specifics/optimisations
6 require_once( "CacheManager.php" );
8 define( "LIST_COMMA", 0 );
9 define( "LIST_AND", 1 );
10 define( "LIST_SET", 2 );
14 #------------------------------------------------------------------------------
16 #------------------------------------------------------------------------------
17 /* private */ var $mLastQuery = "";
18 /* private */ var $mBufferResults = true;
19 /* private */ var $mIgnoreErrors = false;
21 /* private */ var $mServer, $mUser, $mPassword, $mConn, $mDBname;
22 /* private */ var $mOut, $mDebug, $mOpened = false;
24 /* private */ var $mFailFunction;
26 #------------------------------------------------------------------------------
28 #------------------------------------------------------------------------------
30 # These set a variable and return the previous state
32 # Fail function, takes a Database as a parameter
33 # Set to false for default, 1 for ignore errors
34 function setFailFunction( $function ) { return wfSetVar( $this->mFailFunction
, $function ); }
36 # Output page, used for reporting errors
37 # FALSE means discard output
38 function &setOutputPage( &$out ) { $this->mOut
=& $out; }
40 # Boolean, controls output of large amounts of debug information
41 function setDebug( $debug ) { return wfSetVar( $this->mDebug
, $debug ); }
43 # Turns buffering of SQL result sets on (true) or off (false). Default is
44 # "on" and it should not be changed without good reasons.
45 function setBufferResults( $buffer ) { return wfSetVar( $this->mBufferResults
, $buffer ); }
47 # Turns on (false) or off (true) the automatic generation and sending
48 # of a "we're sorry, but there has been a database error" page on
49 # database errors. Default is on (false). When turned off, the
50 # code should use wfLastErrno() and wfLastError() to handle the
51 # situation as appropriate.
52 function setIgnoreErrors( $ignoreErrors ) { return wfSetVar( $this->mIgnoreErrors
, $ignoreErrors ); }
56 function lastQuery() { return $this->mLastQuery
; }
57 function isOpen() { return $this->mOpened
; }
59 #------------------------------------------------------------------------------
61 #------------------------------------------------------------------------------
63 function Database( $server = false, $user = false, $password = false, $dbName = false,
64 $failFunction = false, $debug = false, $bufferResults = true, $ignoreErrors = false )
67 # Can't get a reference if it hasn't been set yet
68 if ( !isset( $wgOut ) ) {
71 $this->mOut
=& $wgOut;
73 $this->mFailFunction
= $failFunction;
74 $this->mIgnoreErrors
= $ignoreErrors;
75 $this->mDebug
= $debug;
76 $this->mBufferResults
= $bufferResults;
78 $this->open( $server, $user, $password, $dbName );
82 /* static */ function newFromParams( $server, $user, $password, $dbName,
83 $failFunction = false, $debug = false, $bufferResults = true, $ignoreErrors = false )
85 return new Database( $server, $user, $password, $dbName, $failFunction, $debug,
86 $bufferResults, $ignoreErrors );
89 # Usually aborts on failure
90 # If the failFunction is set to a non-zero integer, returns success
91 function open( $server, $user, $password, $dbName )
93 # Test for missing mysql.so
94 # Otherwise we get a suppressed fatal error, which is very hard to track down
95 if ( !function_exists( 'mysql_connect' ) ) {
96 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
100 $this->mServer
= $server;
101 $this->mUser
= $user;
102 $this->mPassword
= $password;
103 $this->mDBname
= $dbName;
107 @$this->mConn
= mysql_connect( $server, $user, $password );
108 if ( $dbName != "" ) {
109 if ( $this->mConn
!== false ) {
110 $success = @mysql_select_db
( $dbName, $this->mConn
);
112 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
115 wfDebug( "DB connection error\n" );
116 wfDebug( "Server: $server, User: $user, Password: " .
117 substr( $password, 0, 3 ) . "...\n" );
122 $success = !!$this->mConn
;
126 $this->reportConnectionError();
129 $this->mOpened
= $success;
133 # Closes a database connection, if it is open
134 # Returns success, true if already closed
137 $this->mOpened
= false;
138 if ( $this->mConn
) {
139 return mysql_close( $this->mConn
);
145 /* private */ function reportConnectionError( $msg = "")
147 if ( $this->mFailFunction
) {
148 if ( !is_int( $this->mFailFunction
) ) {
149 $ff = $this->mFailFunction
;
150 $ff( $this, mysql_error() );
153 wfEmergencyAbort( $this, mysql_error() );
157 # Usually aborts on failure
158 # If errors are explicitly ignored, returns success
159 function query( $sql, $fname = "", $tempIgnore = false )
161 global $wgProfiling, $wgCommandLineMode;
163 if ( $wgProfiling ) {
164 # generalizeSQL will probably cut down the query to reasonable
165 # logging size most of the time. The substr is really just a sanity check.
166 $profName = "query: " . substr( Database
::generalizeSQL( $sql ), 0, 255 );
167 wfProfileIn( $profName );
170 $this->mLastQuery
= $sql;
172 if ( $this->mDebug
) {
173 $sqlx = substr( $sql, 0, 500 );
174 $sqlx = wordwrap(strtr($sqlx,"\t\n"," "));
175 wfDebug( "SQL: $sqlx\n" );
177 # Add a comment for easy SHOW PROCESSLIST interpretation
179 $commentedSql = "/* $fname */ $sql";
181 $commentedSql = $sql;
184 if( $this->mBufferResults
) {
185 $ret = mysql_query( $commentedSql, $this->mConn
);
187 $ret = mysql_unbuffered_query( $commentedSql, $this->mConn
);
190 if ( false === $ret ) {
191 # Ignore errors during error handling to avoid infinite recursion
192 $ignore = $this->setIgnoreErrors( true );
194 $error = mysql_error( $this->mConn
);
195 $errno = mysql_errno( $this->mConn
);
196 if( $ignore ||
$tempIgnore ) {
197 wfDebug("SQL ERROR (ignored): " . $error . "\n");
199 $sql1line = str_replace( "\n", "\\n", $sql );
200 wfLogDBError("$fname\t$errno\t$error\t$sql1line\n");
201 wfDebug("SQL ERROR: " . $error . "\n");
202 if ( $wgCommandLineMode ) {
203 wfDebugDieBacktrace( "A database error has occurred\n" .
205 "Function: $fname\n" .
206 "Error: $errno $error\n"
208 } elseif ( $this->mOut
) {
209 // this calls wfAbruptExit()
210 $this->mOut
->databaseError( $fname, $sql, $error, $errno );
213 $this->setIgnoreErrors( $ignore );
216 if ( $wgProfiling ) {
217 wfProfileOut( $profName );
222 function freeResult( $res ) {
223 if ( !@mysql_free_result
( $res ) ) {
224 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
227 function fetchObject( $res ) {
228 @$row = mysql_fetch_object( $res );
229 # FIXME: HACK HACK HACK HACK debug
230 if( mysql_errno() ) {
231 wfDebugDieBacktrace( "Error in fetchObject(): " . htmlspecialchars( mysql_error() ) );
236 function fetchRow( $res ) {
237 @$row = mysql_fetch_array( $res );
238 if (mysql_errno() ) {
239 wfDebugDieBacktrace( "Error in fetchRow(): " . htmlspecialchars( mysql_error() ) );
244 function numRows( $res ) {
245 @$n = mysql_num_rows( $res );
246 if( mysql_errno() ) {
247 wfDebugDieBacktrace( "Error in numRows(): " . htmlspecialchars( mysql_error() ) );
251 function numFields( $res ) { return mysql_num_fields( $res ); }
252 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
253 function insertId() { return mysql_insert_id( $this->mConn
); }
254 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
255 function lastErrno() { return mysql_errno(); }
256 function lastError() { return mysql_error(); }
257 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
259 # Simple UPDATE wrapper
260 # Usually aborts on failure
261 # If errors are explicitly ignored, returns success
262 function set( $table, $var, $value, $cond, $fname = "Database::set" )
264 $table = $this->tableName( $table );
265 $sql = "UPDATE $table SET $var = '" .
266 wfStrencode( $value ) . "' WHERE ($cond)";
267 return !!$this->query( $sql, DB_WRITE
, $fname );
270 # Simple SELECT wrapper, returns a single field, input must be encoded
271 # Usually aborts on failure
272 # If errors are explicitly ignored, returns FALSE on failure
273 function getField( $table, $var, $cond, $fname = "Database::get" )
275 $table = $this->tableName( $table );
276 $from = $table?
" FROM $table ":"";
277 if ( is_array( $cond ) ) {
278 $where = ' WHERE ' . $this->makeList( $cond, LIST_AND
);
280 $where = " WHERE ($cond)";
284 $sql = "SELECT $var $from $where LIMIT 1";
285 $result = $this->query( $sql, $fname );
288 if ( $this->numRows( $result ) > 0 ) {
289 $s = $this->fetchRow( $result );
291 $this->freeResult( $result );
297 function select( $table, $vars, $conds, $fname = "Database::select", $options = array() )
299 $vars = implode( ",", $vars );
300 $table = $this->tableName( $table );
301 if ( !is_array( $options ) ) {
302 $options = array( $options );
307 if ( isset( $options['ORDER BY'] ) ) {
308 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
310 if ( isset( $options['LIMIT'] ) ) {
311 $tailOpts .= " LIMIT {$options['LIMIT']}";
314 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
315 $tailOpts .= ' FOR UPDATE';
318 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
319 $tailOpts .= ' LOCK IN SHARE MODE';
322 if ( isset( $options['USE INDEX'] ) ) {
323 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
328 if ( $conds !== false ) {
329 $where = $this->makeList( $conds, LIST_AND
);
330 $sql = "SELECT $vars FROM $table $useIndex WHERE $where $tailOpts";
332 $sql = "SELECT $vars FROM $table $useIndex $tailOpts";
334 return $this->query( $sql, $fname );
337 # Single row SELECT wrapper
338 # Aborts or returns FALSE on error
340 # $vars: the selected variables
341 # $conds: a condition map, terms are ANDed together.
342 # Items with numeric keys are taken to be literal conditions
343 # Takes an array of selected variables, and a condition map, which is ANDed
344 # e.g. getArray( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
345 # would return an object where $obj->cur_id is the ID of the Astronomy article
346 function getArray( $table, $vars, $conds, $fname = "Database::getArray", $options = array() ) {
347 $options['LIMIT'] = 1;
348 $res = $this->select( $table, $vars, $conds, $fname, $options );
349 if ( $res === false ||
!$this->numRows( $res ) ) {
352 $obj = $this->fetchObject( $res );
353 $this->freeResult( $res );
358 # Removes most variables from an SQL query and replaces them with X or N for numbers.
359 # It's only slightly flawed. Don't use for anything important.
360 /* static */ function generalizeSQL( $sql )
362 # This does the same as the regexp below would do, but in such a way
363 # as to avoid crashing php on some large strings.
364 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
366 $sql = str_replace ( "\\\\", "", $sql);
367 $sql = str_replace ( "\\'", "", $sql);
368 $sql = str_replace ( "\\\"", "", $sql);
369 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
370 $sql = preg_replace ('/".*"/s', "'X'", $sql);
372 # All newlines, tabs, etc replaced by single space
373 $sql = preg_replace ( "/\s+/", " ", $sql);
376 $sql = preg_replace ('/-?[0-9]+/s', "N", $sql);
381 # Determines whether a field exists in a table
382 # Usually aborts on failure
383 # If errors are explicitly ignored, returns NULL on failure
384 function fieldExists( $table, $field, $fname = "Database::fieldExists" )
386 $table = $this->tableName( $table );
387 $res = $this->query( "DESCRIBE $table", DB_READ
, $fname );
394 while ( $row = $this->fetchObject( $res ) ) {
395 if ( $row->Field
== $field ) {
403 # Determines whether an index exists
404 # Usually aborts on failure
405 # If errors are explicitly ignored, returns NULL on failure
406 function indexExists( $table, $index, $fname = "Database::indexExists" )
408 $info = $this->indexInfo( $table, $index, $fname );
409 if ( is_null( $info ) ) {
412 return $info !== false;
416 function indexInfo( $table, $index, $fname = "Database::indexInfo" ) {
417 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
418 # SHOW INDEX should work for 3.x and up:
419 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
420 $table = $this->tableName( $table );
421 $sql = "SHOW INDEX FROM $table";
422 $res = $this->query( $sql, $fname );
427 while ( $row = $this->fetchObject( $res ) ) {
428 if ( $row->Key_name
== $index ) {
434 function tableExists( $table )
436 $table = $this->tableName( $table );
437 $old = $this->mIgnoreErrors
;
438 $this->mIgnoreErrors
= true;
439 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
440 $this->mIgnoreErrors
= $old;
442 $this->freeResult( $res );
449 function fieldInfo( $table, $field )
451 $table = $this->tableName( $table );
452 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
453 $n = mysql_num_fields( $res );
454 for( $i = 0; $i < $n; $i++
) {
455 $meta = mysql_fetch_field( $res, $i );
456 if( $field == $meta->name
) {
463 # INSERT wrapper, inserts an array into a table
465 # $a may be a single associative array, or an array of these with numeric keys, for
468 # Usually aborts on failure
469 # If errors are explicitly ignored, returns success
470 function insertArray( $table, $a, $fname = "Database::insertArray", $options = array() )
472 $table = $this->tableName( $table );
473 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
475 $keys = array_keys( $a[0] );
478 $keys = array_keys( $a );
481 $sql = 'INSERT ' . implode( ' ', $options ) .
482 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
486 foreach ( $a as $row ) {
492 $sql .= '(' . $this->makeList( $row ) . ')';
495 $sql .= '(' . $this->makeList( $a ) . ')';
497 return !!$this->query( $sql, $fname );
500 # UPDATE wrapper, takes a condition array and a SET array
501 function updateArray( $table, $values, $conds, $fname = "Database::updateArray" )
503 $table = $this->tableName( $table );
504 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET
);
505 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
506 $this->query( $sql, $fname );
509 # Makes a wfStrencoded list from an array
510 # $mode: LIST_COMMA - comma separated, no field names
511 # LIST_AND - ANDed WHERE clause (without the WHERE)
512 # LIST_SET - comma separated with field names, like a SET clause
513 function makeList( $a, $mode = LIST_COMMA
)
515 if ( !is_array( $a ) ) {
516 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
521 foreach ( $a as $field => $value ) {
523 if ( $mode == LIST_AND
) {
531 if ( $mode == LIST_AND
&& is_numeric( $field ) ) {
534 if ( $mode == LIST_AND ||
$mode == LIST_SET
) {
537 $list .= $this->addQuotes( $value );
543 function selectDB( $db )
545 $this->mDBname
= $db;
546 mysql_select_db( $db, $this->mConn
);
549 function startTimer( $timeout )
553 $tid = mysql_thread_id( $this->mConn
);
554 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );
561 function tableName( $name ) {
565 function strencode( $s ) {
566 return addslashes( $s );
569 # If it's a string, adds quotes and backslashes
570 # Otherwise returns as-is
571 function addQuotes( $s ) {
572 if ( !is_numeric( $s ) ) {
573 $s = "'" . $this->strencode( $s ) . "'";
574 } else if ( is_null( $s ) ) {
580 # Returns an appropriately quoted sequence value for inserting a new row.
581 # MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
582 # subclass will return an integer, and save the value for insertId()
583 function nextSequenceValue( $seqName ) {
588 # PostgreSQL doesn't have them and returns ""
589 function useIndexClause( $index ) {
590 return "USE INDEX ($index)";
593 # REPLACE query wrapper
594 # PostgreSQL simulates this with a DELETE followed by INSERT
595 # $row is the row to insert, an associative array
596 # $uniqueIndexes is an array of indexes. Each element may be either a
597 # field name or an array of field names
599 # It may be more efficient to leave off unique indexes which are unlikely to collide.
600 # However if you do this, you run the risk of encountering errors which wouldn't have
602 function replace( $table, $uniqueIndexes, $rows, $fname = "Database::replace" ) {
603 $table = $this->tableName( $table );
606 if ( !is_array( reset( $rows ) ) ) {
607 $rows = array( $rows );
610 $sql = "REPLACE INTO $table (" . implode( ',', array_flip( $rows[0] ) ) .") VALUES ";
612 foreach ( $rows as $row ) {
618 $sql .= "(" . $this->makeList( $row ) . ")";
620 return $this->query( $sql, $fname );
623 # DELETE where the condition is a join
624 # MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
626 # $delTable is the table to delete from
627 # $joinTable is the other table
628 # $delVar is the variable to join on, in the first table
629 # $joinVar is the variable to join on, in the second table
630 # $conds is a condition array of field names mapped to variables, ANDed together in the WHERE clause
632 # For safety, an empty $conds will not delete everything. If you want to delete all rows where the
633 # join condition matches, set $conds='*'
635 # DO NOT put the join condition in $conds
636 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
638 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
641 $delTable = $this->tableName( $delTable );
642 $joinTable = $this->tableName( $joinTable );
643 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
644 if ( $conds != '*' ) {
645 $sql .= " AND " . $this->makeList( $conds, LIST_AND
);
648 return $this->query( $sql, $fname );
651 # Returns the size of a text field, or -1 for "unlimited"
652 function textFieldSize( $table, $field ) {
653 $table = $this->tableName( $table );
654 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
655 $res = $this->query( $sql, "Database::textFieldSize" );
656 $row = wfFetchObject( $res );
657 $this->freeResult( $res );
659 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
667 function lowPriorityOption() {
668 return 'LOW_PRIORITY';
671 # Use $conds == "*" to delete all rows
672 function delete( $table, $conds, $fname = "Database::delete" ) {
674 wfDebugDieBacktrace( "Database::delete() called with no conditions" );
676 $table = $this->tableName( $table );
677 $sql = "DELETE FROM $table ";
678 if ( $conds != '*' ) {
679 $sql .= "WHERE " . $this->makeList( $conds, LIST_AND
);
681 return $this->query( $sql, $fname );
684 # INSERT SELECT wrapper
685 # $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
686 # Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
687 # $conds may be "*" to copy the whole table
688 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
689 $destTable = $this->tableName( $destTable );
690 $srcTable = $this->tableName( $srcTable );
691 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ")" .
692 " SELECT " . implode( ',', $varMap ) .
694 if ( $conds != '*' ) {
695 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
697 return $this->query( $sql, $fname );
701 class DatabaseMysql
extends Database
{
705 #------------------------------------------------------------------------------
707 #------------------------------------------------------------------------------
709 /* Standard fail function, called by default when a connection cannot be established
710 Displays the file cache if possible */
711 function wfEmergencyAbort( &$conn, $error ) {
712 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
714 if( !headers_sent() ) {
715 header( "HTTP/1.0 500 Internal Server Error" );
716 header( "Content-type: text/html; charset=$wgOutputEncoding" );
717 /* Don't cache error pages! They cause no end of trouble... */
718 header( "Cache-control: none" );
719 header( "Pragma: nocache" );
721 $msg = $wgSiteNotice;
722 if($msg == "") $msg = wfMsgNoDB( "noconnect", $error );
725 if($wgUseFileCache) {
730 $t = Title
::newFromURL( $title );
731 } elseif (@$_REQUEST['search']) {
732 $search = $_REQUEST['search'];
733 echo wfMsgNoDB( "searchdisabled" );
734 echo wfMsgNoDB( "googlesearch", htmlspecialchars( $search ), $wgInputEncoding );
737 $t = Title
::newFromText( wfMsgNoDB( "mainpage" ) );
741 $cache = new CacheManager( $t );
742 if( $cache->isFileCached() ) {
743 $msg = "<p style='color: red'><b>$msg<br />\n" .
744 wfMsgNoDB( "cachederror" ) . "</b></p>\n";
746 $tag = "<div id='article'>";
750 $cache->fetchPageText() );
758 function wfLimitResult( $limit, $offset ) {
759 return " LIMIT ".(is_numeric($offset)?
"{$offset},":"")."{$limit} ";