Installer support for picking traditional Chinese (zh-tw) localization.
[mediawiki.git] / includes / Database.php
blobd9ab04571958b8637f5929f59126536fe959aa88
1 <?php
2 /**
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
5 * @version # $Id$
6 * @package MediaWiki
7 */
9 /**
10 * Depends on the CacheManager
12 require_once( 'CacheManager.php' );
14 /** @todo document */
15 define( 'LIST_COMMA', 0 );
16 /** @todo document */
17 define( 'LIST_AND', 1 );
18 /** @todo document */
19 define( 'LIST_SET', 2 );
20 /** @todo document */
21 define( 'LIST_NAMES', 3);
23 /** Number of times to re-try an operation in case of deadlock */
24 define( 'DEADLOCK_TRIES', 4 );
25 /** Minimum time to wait before retry, in microseconds */
26 define( 'DEADLOCK_DELAY_MIN', 500000 );
27 /** Maximum time to wait before retry */
28 define( 'DEADLOCK_DELAY_MAX', 1500000 );
30 /**
31 * Database abstraction object
32 * @package MediaWiki
33 * @version # $Id$
35 class Database {
37 #------------------------------------------------------------------------------
38 # Variables
39 #------------------------------------------------------------------------------
40 /**#@+
41 * @access private
43 var $mLastQuery = '';
45 var $mServer, $mUser, $mPassword, $mConn, $mDBname;
46 var $mOut, $mOpened = false;
48 var $mFailFunction;
49 var $mTablePrefix;
50 var $mFlags;
51 var $mTrxLevel = 0;
52 /**#@-*/
54 #------------------------------------------------------------------------------
55 # Accessors
56 #------------------------------------------------------------------------------
57 # These optionally set a variable and return the previous state
59 /**
60 * Fail function, takes a Database as a parameter
61 * Set to false for default, 1 for ignore errors
63 function failFunction( $function = NULL ) {
64 return wfSetVar( $this->mFailFunction, $function );
67 /**
68 * Output page, used for reporting errors
69 * FALSE means discard output
71 function &setOutputPage( &$out ) {
72 $this->mOut =& $out;
75 /**
76 * Boolean, controls output of large amounts of debug information
78 function debug( $debug = NULL ) {
79 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
82 /**
83 * Turns buffering of SQL result sets on (true) or off (false).
84 * Default is "on" and it should not be changed without good reasons.
86 function bufferResults( $buffer = NULL ) {
87 if ( is_null( $buffer ) ) {
88 return !(bool)( $this->mFlags & DBO_NOBUFFER );
89 } else {
90 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
94 /**
95 * Turns on (false) or off (true) the automatic generation and sending
96 * of a "we're sorry, but there has been a database error" page on
97 * database errors. Default is on (false). When turned off, the
98 * code should use wfLastErrno() and wfLastError() to handle the
99 * situation as appropriate.
101 function ignoreErrors( $ignoreErrors = NULL ) {
102 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
106 * The current depth of nested transactions
107 * @param integer $level
109 function trxLevel( $level = NULL ) {
110 return wfSetVar( $this->mTrxLevel, $level );
113 /**#@+
114 * Get function
116 function lastQuery() { return $this->mLastQuery; }
117 function isOpen() { return $this->mOpened; }
118 /**#@-*/
120 #------------------------------------------------------------------------------
121 # Other functions
122 #------------------------------------------------------------------------------
124 /**#@+
125 * @param string $server database server host
126 * @param string $user database user name
127 * @param string $password database user password
128 * @param string $dbname database name
132 * @param failFunction
133 * @param $flags
134 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
136 function Database( $server = false, $user = false, $password = false, $dbName = false,
137 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
139 global $wgOut, $wgDBprefix, $wgCommandLineMode;
140 # Can't get a reference if it hasn't been set yet
141 if ( !isset( $wgOut ) ) {
142 $wgOut = NULL;
144 $this->mOut =& $wgOut;
146 $this->mFailFunction = $failFunction;
147 $this->mFlags = $flags;
149 if ( $this->mFlags & DBO_DEFAULT ) {
150 if ( $wgCommandLineMode ) {
151 $this->mFlags &= ~DBO_TRX;
152 } else {
153 $this->mFlags |= DBO_TRX;
157 /** Get the default table prefix*/
158 if ( $tablePrefix == 'get from global' ) {
159 $this->mTablePrefix = $wgDBprefix;
160 } else {
161 $this->mTablePrefix = $tablePrefix;
164 if ( $server ) {
165 $this->open( $server, $user, $password, $dbName );
170 * @static
171 * @param failFunction
172 * @param $flags
174 function newFromParams( $server, $user, $password, $dbName,
175 $failFunction = false, $flags = 0 )
177 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
181 * Usually aborts on failure
182 * If the failFunction is set to a non-zero integer, returns success
184 function open( $server, $user, $password, $dbName ) {
185 # Test for missing mysql.so
186 # Otherwise we get a suppressed fatal error, which is very hard to track down
187 if ( !function_exists( 'mysql_connect' ) ) {
188 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
191 $this->close();
192 $this->mServer = $server;
193 $this->mUser = $user;
194 $this->mPassword = $password;
195 $this->mDBname = $dbName;
197 $success = false;
199 @/**/$this->mConn = mysql_connect( $server, $user, $password );
200 if ( $dbName != '' ) {
201 if ( $this->mConn !== false ) {
202 $success = @/**/mysql_select_db( $dbName, $this->mConn );
203 if ( !$success ) {
204 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
206 } else {
207 wfDebug( "DB connection error\n" );
208 wfDebug( "Server: $server, User: $user, Password: " .
209 substr( $password, 0, 3 ) . "...\n" );
210 $success = false;
212 } else {
213 # Delay USE query
214 $success = !!$this->mConn;
217 if ( !$success ) {
218 $this->reportConnectionError();
219 $this->close();
221 $this->mOpened = $success;
222 return $success;
224 /**#@-*/
227 * Closes a database connection.
228 * if it is open : commits any open transactions
230 * @return bool operation success. true if already closed.
232 function close()
234 $this->mOpened = false;
235 if ( $this->mConn ) {
236 if ( $this->trxLevel() ) {
237 $this->immediateCommit();
239 return mysql_close( $this->mConn );
240 } else {
241 return true;
246 * @access private
247 * @param string $msg error message ?
248 * @todo parameter $msg is not used
250 function reportConnectionError( $msg = '') {
251 if ( $this->mFailFunction ) {
252 if ( !is_int( $this->mFailFunction ) ) {
253 $ff = $this->mFailFunction;
254 $ff( $this, mysql_error() );
256 } else {
257 wfEmergencyAbort( $this, mysql_error() );
262 * Usually aborts on failure
263 * If errors are explicitly ignored, returns success
265 function query( $sql, $fname = '', $tempIgnore = false ) {
266 global $wgProfiling, $wgCommandLineMode;
268 if ( $wgProfiling ) {
269 # generalizeSQL will probably cut down the query to reasonable
270 # logging size most of the time. The substr is really just a sanity check.
271 $profName = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
272 wfProfileIn( $profName );
275 $this->mLastQuery = $sql;
277 if ( $this->debug() ) {
278 $sqlx = substr( $sql, 0, 500 );
279 $sqlx = wordwrap(strtr($sqlx,"\t\n",' '));
280 wfDebug( "SQL: $sqlx\n" );
282 # Add a comment for easy SHOW PROCESSLIST interpretation
283 if ( $fname ) {
284 $commentedSql = "/* $fname */ $sql";
285 } else {
286 $commentedSql = $sql;
289 # If DBO_TRX is set, start a transaction
290 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() && $sql != 'BEGIN' ) {
291 $this->begin();
294 # Do the query and handle errors
295 $ret = $this->doQuery( $commentedSql );
296 if ( false === $ret ) {
297 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
300 if ( $wgProfiling ) {
301 wfProfileOut( $profName );
303 return $ret;
307 * The DBMS-dependent part of query()
308 * @param string $sql SQL query.
310 function doQuery( $sql ) {
311 if( $this->bufferResults() ) {
312 $ret = mysql_query( $sql, $this->mConn );
313 } else {
314 $ret = mysql_unbuffered_query( $sql, $this->mConn );
316 return $ret;
320 * @param $error
321 * @param $errno
322 * @param $sql
323 * @param string $fname
324 * @param bool $tempIgnore
326 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
327 global $wgCommandLineMode, $wgFullyInitialised;
328 # Ignore errors during error handling to avoid infinite recursion
329 $ignore = $this->ignoreErrors( true );
331 if( $ignore || $tempIgnore ) {
332 wfDebug("SQL ERROR (ignored): " . $error . "\n");
333 } else {
334 $sql1line = str_replace( "\n", "\\n", $sql );
335 wfLogDBError("$fname\t$errno\t$error\t$sql1line\n");
336 wfDebug("SQL ERROR: " . $error . "\n");
337 if ( $wgCommandLineMode || !$this->mOut || empty( $wgFullyInitialised ) ) {
338 $message = "A database error has occurred\n" .
339 "Query: $sql\n" .
340 "Function: $fname\n" .
341 "Error: $errno $error\n";
342 if ( !$wgCommandLineMode ) {
343 $message = nl2br( $message );
345 wfDebugDieBacktrace( $message );
346 } else {
347 // this calls wfAbruptExit()
348 $this->mOut->databaseError( $fname, $sql, $error, $errno );
351 $this->ignoreErrors( $ignore );
355 /**#@+
356 * @param mixed $res A SQL result
359 * @todo document
361 function freeResult( $res ) {
362 if ( !@/**/mysql_free_result( $res ) ) {
363 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
368 * @todo FIXME: HACK HACK HACK HACK debug
370 function fetchObject( $res ) {
371 @/**/$row = mysql_fetch_object( $res );
372 # FIXME: HACK HACK HACK HACK debug
373 if( mysql_errno() ) {
374 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
376 return $row;
380 * @todo document
382 function fetchRow( $res ) {
383 @/**/$row = mysql_fetch_array( $res );
384 if (mysql_errno() ) {
385 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
387 return $row;
391 * @todo document
393 function numRows( $res ) {
394 @/**/$n = mysql_num_rows( $res );
395 if( mysql_errno() ) {
396 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
398 return $n;
402 * @todo document
404 function numFields( $res ) { return mysql_num_fields( $res ); }
407 * @todo document
409 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
411 * @todo document
413 function insertId() { return mysql_insert_id( $this->mConn ); }
415 * @todo document
417 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
419 * @todo document
421 function lastErrno() { return mysql_errno(); }
423 * @todo document
425 function lastError() { return mysql_error(); }
427 * @todo document
429 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
430 /**#@-*/ // end of template : @param $result
434 * Simple UPDATE wrapper
435 * Usually aborts on failure
436 * If errors are explicitly ignored, returns success
438 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
440 $table = $this->tableName( $table );
441 $sql = "UPDATE $table SET $var = '" .
442 $this->strencode( $value ) . "' WHERE ($cond)";
443 return !!$this->query( $sql, DB_MASTER, $fname );
447 * @todo document
449 function getField( $table, $var, $cond='', $fname = 'Database::getField', $options = array() ) {
450 return $this->selectField( $table, $var, $cond, $fname = 'Database::get', $options = array() );
454 * Simple SELECT wrapper, returns a single field, input must be encoded
455 * Usually aborts on failure
456 * If errors are explicitly ignored, returns FALSE on failure
458 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
459 if ( !is_array( $options ) ) {
460 $options = array( $options );
462 $options['LIMIT'] = 1;
464 $res = $this->select( $table, $var, $cond, $fname, $options );
465 if ( $res === false || !$this->numRows( $res ) ) {
466 return false;
468 $row = $this->fetchRow( $res );
469 if ( $row !== false ) {
470 $this->freeResult( $res );
471 return $row[0];
472 } else {
473 return false;
478 * Returns an optional USE INDEX clause to go after the table, and a
479 * string to go at the end of the query
481 function makeSelectOptions( $options ) {
482 if ( !is_array( $options ) ) {
483 $options = array( $options );
486 $tailOpts = '';
488 if ( isset( $options['ORDER BY'] ) ) {
489 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
491 if ( isset( $options['LIMIT'] ) ) {
492 $tailOpts .= " LIMIT {$options['LIMIT']}";
495 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
496 $tailOpts .= ' FOR UPDATE';
499 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
500 $tailOpts .= ' LOCK IN SHARE MODE';
503 if ( isset( $options['USE INDEX'] ) ) {
504 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
505 } else {
506 $useIndex = '';
508 return array( $useIndex, $tailOpts );
512 * SELECT wrapper
514 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
516 if ( is_array( $vars ) ) {
517 $vars = implode( ',', $vars );
519 if ($table!='')
520 $from = ' FROM ' .$this->tableName( $table );
521 else
522 $from = '';
524 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
526 if ( $conds !== false && $conds != '' ) {
527 if ( is_array( $conds ) ) {
528 $conds = $this->makeList( $conds, LIST_AND );
530 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
531 } else {
532 $sql = "SELECT $vars $from $useIndex $tailOpts";
534 return $this->query( $sql, $fname );
538 * @todo document
540 function getArray( $table, $vars, $conds, $fname = 'Database::getArray', $options = array() ) {
541 return $this->selectRow( $table, $vars, $conds, $fname, $options );
546 * Single row SELECT wrapper
547 * Aborts or returns FALSE on error
549 * $vars: the selected variables
550 * $conds: a condition map, terms are ANDed together.
551 * Items with numeric keys are taken to be literal conditions
552 * Takes an array of selected variables, and a condition map, which is ANDed
553 * e.g. selectRow( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
554 * would return an object where $obj->cur_id is the ID of the Astronomy article
556 * @todo migrate documentation to phpdocumentor format
558 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
559 $options['LIMIT'] = 1;
560 $res = $this->select( $table, $vars, $conds, $fname, $options );
561 if ( $res === false || !$this->numRows( $res ) ) {
562 return false;
564 $obj = $this->fetchObject( $res );
565 $this->freeResult( $res );
566 return $obj;
571 * Removes most variables from an SQL query and replaces them with X or N for numbers.
572 * It's only slightly flawed. Don't use for anything important.
574 * @param string $sql A SQL Query
575 * @static
577 function generalizeSQL( $sql ) {
578 # This does the same as the regexp below would do, but in such a way
579 # as to avoid crashing php on some large strings.
580 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
582 $sql = str_replace ( "\\\\", '', $sql);
583 $sql = str_replace ( "\\'", '', $sql);
584 $sql = str_replace ( "\\\"", '', $sql);
585 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
586 $sql = preg_replace ('/".*"/s', "'X'", $sql);
588 # All newlines, tabs, etc replaced by single space
589 $sql = preg_replace ( "/\s+/", ' ', $sql);
591 # All numbers => N
592 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
594 return $sql;
598 * Determines whether a field exists in a table
599 * Usually aborts on failure
600 * If errors are explicitly ignored, returns NULL on failure
602 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
603 $table = $this->tableName( $table );
604 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE, $fname );
605 if ( !$res ) {
606 return NULL;
609 $found = false;
611 while ( $row = $this->fetchObject( $res ) ) {
612 if ( $row->Field == $field ) {
613 $found = true;
614 break;
617 return $found;
621 * Determines whether an index exists
622 * Usually aborts on failure
623 * If errors are explicitly ignored, returns NULL on failure
625 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
626 $info = $this->indexInfo( $table, $index, $fname );
627 if ( is_null( $info ) ) {
628 return NULL;
629 } else {
630 return $info !== false;
636 * @todo document
638 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
639 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
640 # SHOW INDEX should work for 3.x and up:
641 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
642 $table = $this->tableName( $table );
643 $sql = 'SHOW INDEX FROM '.$table;
644 $res = $this->query( $sql, $fname );
645 if ( !$res ) {
646 return NULL;
649 while ( $row = $this->fetchObject( $res ) ) {
650 if ( $row->Key_name == $index ) {
651 return $row;
654 return false;
658 * @param $table
659 * @todo document
661 function tableExists( $table ) {
662 $table = $this->tableName( $table );
663 $old = $this->ignoreErrors( true );
664 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
665 $this->ignoreErrors( $old );
666 if( $res ) {
667 $this->freeResult( $res );
668 return true;
669 } else {
670 return false;
675 * @param $table
676 * @param $field
677 * @todo document
679 function fieldInfo( $table, $field ) {
680 $table = $this->tableName( $table );
681 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
682 $n = mysql_num_fields( $res );
683 for( $i = 0; $i < $n; $i++ ) {
684 $meta = mysql_fetch_field( $res, $i );
685 if( $field == $meta->name ) {
686 return $meta;
689 return false;
693 * @todo document
695 function fieldType( $res, $index ) {
696 return mysql_field_type( $res, $index );
700 * @todo document
702 function indexUnique( $table, $index ) {
703 $indexInfo = $this->indexInfo( $table, $index );
704 if ( !$indexInfo ) {
705 return NULL;
707 return !$indexInfo->Non_unique;
711 * @todo document
713 function insertArray( $table, $a, $fname = 'Database::insertArray', $options = array() ) {
714 return $this->insert( $table, $a, $fname = 'Database::insertArray', $options = array() );
718 * INSERT wrapper, inserts an array into a table
720 * $a may be a single associative array, or an array of these with numeric keys, for
721 * multi-row insert.
723 * Usually aborts on failure
724 * If errors are explicitly ignored, returns success
726 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
727 # No rows to insert, easy just return now
728 if ( !count( $a ) ) {
729 return true;
732 $table = $this->tableName( $table );
733 if ( !is_array( $options ) ) {
734 $options = array( $options );
736 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
737 $multi = true;
738 $keys = array_keys( $a[0] );
739 } else {
740 $multi = false;
741 $keys = array_keys( $a );
744 $sql = 'INSERT ' . implode( ' ', $options ) .
745 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
747 if ( $multi ) {
748 $first = true;
749 foreach ( $a as $row ) {
750 if ( $first ) {
751 $first = false;
752 } else {
753 $sql .= ',';
755 $sql .= '(' . $this->makeList( $row ) . ')';
757 } else {
758 $sql .= '(' . $this->makeList( $a ) . ')';
760 return !!$this->query( $sql, $fname );
764 * @todo document
766 function updateArray( $table, $values, $conds, $fname = 'Database::updateArray' ) {
767 return $this->update( $table, $values, $conds, $fname );
771 * UPDATE wrapper, takes a condition array and a SET array
773 function update( $table, $values, $conds, $fname = 'Database::update' ) {
774 $table = $this->tableName( $table );
775 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET );
776 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
777 $this->query( $sql, $fname );
781 * Makes a wfStrencoded list from an array
782 * $mode: LIST_COMMA - comma separated, no field names
783 * LIST_AND - ANDed WHERE clause (without the WHERE)
784 * LIST_SET - comma separated with field names, like a SET clause
785 * LIST_NAMES - comma separated field names
787 function makeList( $a, $mode = LIST_COMMA ) {
788 if ( !is_array( $a ) ) {
789 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
792 $first = true;
793 $list = '';
794 foreach ( $a as $field => $value ) {
795 if ( !$first ) {
796 if ( $mode == LIST_AND ) {
797 $list .= ' AND ';
798 } else {
799 $list .= ',';
801 } else {
802 $first = false;
804 if ( $mode == LIST_AND && is_numeric( $field ) ) {
805 $list .= "($value)";
806 } else {
807 if ( $mode == LIST_AND || $mode == LIST_SET ) {
808 $list .= $field.'=';
810 $list .= ($mode==LIST_NAMES?$value:$this->addQuotes( $value ));
813 return $list;
817 * @todo document
819 function selectDB( $db ) {
820 $this->mDBname = $db;
821 mysql_select_db( $db, $this->mConn );
825 * @todo document
827 function startTimer( $timeout ) {
828 global $IP;
829 if( function_exists( 'mysql_thread_id' ) ) {
830 # This will kill the query if it's still running after $timeout seconds.
831 $tid = mysql_thread_id( $this->mConn );
832 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );
837 * Does nothing at all
838 * @todo document
840 function stopTimer() { }
843 * @param string $name database table name
844 * @todo document
846 function tableName( $name ) {
847 global $wgSharedDB;
848 if ( $this->mTablePrefix !== '' ) {
849 if ( strpos( '.', $name ) === false ) {
850 $name = $this->mTablePrefix . $name;
853 if ( isset( $wgSharedDB ) && 'user' == $name ) {
854 $name = $wgSharedDB . '.' . $name;
856 return $name;
860 * @todo document
862 function tableNames() {
863 $inArray = func_get_args();
864 $retVal = array();
865 foreach ( $inArray as $name ) {
866 $retVal[$name] = $this->tableName( $name );
868 return $retVal;
872 * Wrapper for addslashes()
873 * @param string $s String to be slashed.
874 * @return string slashed string.
876 function strencode( $s ) {
877 return addslashes( $s );
881 * If it's a string, adds quotes and backslashes
882 * Otherwise returns as-is
884 function addQuotes( $s ) {
885 if ( is_null( $s ) ) {
886 $s = 'NULL';
887 } else {
888 # This will also quote numeric values. This should be harmless,
889 # and protects against weird problems that occur when they really
890 # _are_ strings such as article titles and string->number->string
891 # conversion is not 1:1.
892 $s = "'" . $this->strencode( $s ) . "'";
894 return $s;
898 * Returns an appropriately quoted sequence value for inserting a new row.
899 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
900 * subclass will return an integer, and save the value for insertId()
902 function nextSequenceValue( $seqName ) {
903 return NULL;
907 * USE INDEX clause
908 * PostgreSQL doesn't have them and returns ""
910 function useIndexClause( $index ) {
911 return 'USE INDEX ('.$index.')';
915 * REPLACE query wrapper
916 * PostgreSQL simulates this with a DELETE followed by INSERT
917 * $row is the row to insert, an associative array
918 * $uniqueIndexes is an array of indexes. Each element may be either a
919 * field name or an array of field names
921 * It may be more efficient to leave off unique indexes which are unlikely to collide.
922 * However if you do this, you run the risk of encountering errors which wouldn't have
923 * occurred in MySQL
925 * @todo migrate comment to phodocumentor format
927 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
928 $table = $this->tableName( $table );
930 # Single row case
931 if ( !is_array( reset( $rows ) ) ) {
932 $rows = array( $rows );
935 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
936 $first = true;
937 foreach ( $rows as $row ) {
938 if ( $first ) {
939 $first = false;
940 } else {
941 $sql .= ',';
943 $sql .= '(' . $this->makeList( $row ) . ')';
945 return $this->query( $sql, $fname );
949 * DELETE where the condition is a join
950 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
952 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
953 * join condition matches, set $conds='*'
955 * DO NOT put the join condition in $conds
957 * @param string $delTable The table to delete from.
958 * @param string $joinTable The other table.
959 * @param string $delVar The variable to join on, in the first table.
960 * @param string $joinVar The variable to join on, in the second table.
961 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
963 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
964 if ( !$conds ) {
965 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
968 $delTable = $this->tableName( $delTable );
969 $joinTable = $this->tableName( $joinTable );
970 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
971 if ( $conds != '*' ) {
972 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
975 return $this->query( $sql, $fname );
979 * Returns the size of a text field, or -1 for "unlimited"
981 function textFieldSize( $table, $field ) {
982 $table = $this->tableName( $table );
983 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
984 $res = $this->query( $sql, 'Database::textFieldSize' );
985 $row = $this->fetchObject( $res );
986 $this->freeResult( $res );
988 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
989 $size = $m[1];
990 } else {
991 $size = -1;
993 return $size;
997 * @return string Always return 'LOW_PRIORITY'
999 function lowPriorityOption() {
1000 return 'LOW_PRIORITY';
1004 * Use $conds == "*" to delete all rows
1005 * @todo document
1007 function delete( $table, $conds, $fname = 'Database::delete' ) {
1008 if ( !$conds ) {
1009 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1011 $table = $this->tableName( $table );
1012 $sql = "DELETE FROM $table ";
1013 if ( $conds != '*' ) {
1014 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
1016 return $this->query( $sql, $fname );
1020 * INSERT SELECT wrapper
1021 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1022 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1023 * $conds may be "*" to copy the whole table
1025 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1026 $destTable = $this->tableName( $destTable );
1027 $srcTable = $this->tableName( $srcTable );
1028 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1029 ' SELECT ' . implode( ',', $varMap ) .
1030 " FROM $srcTable";
1031 if ( $conds != '*' ) {
1032 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1034 return $this->query( $sql, $fname );
1038 * @todo document
1040 function limitResult($limit,$offset) {
1041 return ' LIMIT '.(is_numeric($offset)?"{$offset},":"")."{$limit} ";
1045 * Returns an SQL expression for a simple conditional.
1046 * Uses IF on MySQL.
1048 * @param string $cond SQL expression which will result in a boolean value
1049 * @param string $trueVal SQL expression to return if true
1050 * @param string $falseVal SQL expression to return if false
1051 * @return string SQL fragment
1053 function conditional( $cond, $trueVal, $falseVal ) {
1054 return " IF($cond, $trueVal, $falseVal) ";
1058 * @todo document
1060 function wasDeadlock() {
1061 return $this->lastErrno() == 1213;
1065 * @todo document
1067 function deadlockLoop() {
1068 $myFname = 'Database::deadlockLoop';
1070 $this->query( 'BEGIN', $myFname );
1071 $args = func_get_args();
1072 $function = array_shift( $args );
1073 $oldIgnore = $dbw->ignoreErrors( true );
1074 $tries = DEADLOCK_TRIES;
1075 if ( is_array( $function ) ) {
1076 $fname = $function[0];
1077 } else {
1078 $fname = $function;
1080 do {
1081 $retVal = call_user_func_array( $function, $args );
1082 $error = $this->lastError();
1083 $errno = $this->lastErrno();
1084 $sql = $this->lastQuery();
1086 if ( $errno ) {
1087 if ( $dbw->wasDeadlock() ) {
1088 # Retry
1089 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1090 } else {
1091 $dbw->reportQueryError( $error, $errno, $sql, $fname );
1094 } while( $dbw->wasDeadlock && --$tries > 0 );
1095 $this->ignoreErrors( $oldIgnore );
1096 if ( $tries <= 0 ) {
1097 $this->query( 'ROLLBACK', $myFname );
1098 $this->reportQueryError( $error, $errno, $sql, $fname );
1099 return false;
1100 } else {
1101 $this->query( 'COMMIT', $myFname );
1102 return $retVal;
1107 * Do a SELECT MASTER_POS_WAIT()
1108 * @todo document
1110 function masterPosWait( $file, $pos, $timeout ) {
1111 $encFile = $this->strencode( $file );
1112 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1113 $res = $this->query( $sql, 'Database::masterPosWait' );
1114 if ( $res && $row = $this->fetchRow( $res ) ) {
1115 $this->freeResult( $res );
1116 return $row[0];
1117 } else {
1118 return false;
1123 * Get the position of the master from SHOW SLAVE STATUS
1125 function getSlavePos() {
1126 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1127 $row = $this->fetchObject( $res );
1128 if ( $row ) {
1129 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1130 } else {
1131 return array( false, false );
1136 * Get the position of the master from SHOW MASTER STATUS
1138 function getMasterPos() {
1139 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1140 $row = $this->fetchObject( $res );
1141 if ( $row ) {
1142 return array( $row->File, $row->Position );
1143 } else {
1144 return array( false, false );
1149 * Begin a transaction, or if a transaction has already started, continue it
1151 function begin( $fname = 'Database::begin' ) {
1152 if ( !$this->mTrxLevel ) {
1153 $this->immediateBegin( $fname );
1154 } else {
1155 $this->mTrxLevel++;
1160 * End a transaction, or decrement the nest level if transactions are nested
1162 function commit( $fname = 'Database::commit' ) {
1163 if ( $this->mTrxLevel ) {
1164 $this->mTrxLevel--;
1166 if ( !$this->mTrxLevel ) {
1167 $this->immediateCommit( $fname );
1172 * Rollback a transaction
1174 function rollback( $fname = 'Database::rollback' ) {
1175 $this->query( 'ROLLBACK', $fname );
1176 $this->mTrxLevel = 0;
1180 * Begin a transaction, committing any previously open transaction
1182 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1183 $this->query( 'BEGIN', $fname );
1184 $this->mTrxLevel = 1;
1188 * Commit transaction, if one is open
1190 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1191 $this->query( 'COMMIT', $fname );
1192 $this->mTrxLevel = 0;
1196 * Return MW-style timestamp used for MySQL schema
1198 function timestamp( $ts=0 ) {
1199 return wfTimestamp(TS_MW,$ts);
1203 * @todo document
1205 function &resultObject( &$result ) {
1206 if( empty( $result ) ) {
1207 return NULL;
1208 } else {
1209 return new ResultWrapper( $this, $result );
1214 * @return string wikitext of a link to the server software's web site
1216 function getSoftwareLink() {
1217 return "[http://www.mysql.com/ MySQL]";
1221 * @return string Version information from the database
1223 function getServerVersion() {
1224 return mysql_get_server_info();
1229 * Database abstraction object for mySQL
1230 * Inherit all methods and properties of Database::Database()
1232 * @package MediaWiki
1233 * @see Database
1234 * @version # $Id$
1236 class DatabaseMysql extends Database {
1237 # Inherit all
1242 * Result wrapper for grabbing data queried by someone else
1244 * @package MediaWiki
1245 * @version # $Id$
1247 class ResultWrapper {
1248 var $db, $result;
1251 * @todo document
1253 function ResultWrapper( $database, $result ) {
1254 $this->db =& $database;
1255 $this->result =& $result;
1259 * @todo document
1261 function numRows() {
1262 return $this->db->numRows( $this->result );
1266 * @todo document
1268 function &fetchObject() {
1269 return $this->db->fetchObject( $this->result );
1273 * @todo document
1275 function &fetchRow() {
1276 return $this->db->fetchRow( $this->result );
1280 * @todo document
1282 function free() {
1283 $this->db->freeResult( $this->result );
1284 unset( $this->result );
1285 unset( $this->db );
1289 #------------------------------------------------------------------------------
1290 # Global functions
1291 #------------------------------------------------------------------------------
1294 * Standard fail function, called by default when a connection cannot be
1295 * established.
1296 * Displays the file cache if possible
1298 function wfEmergencyAbort( &$conn, $error ) {
1299 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
1301 if( !headers_sent() ) {
1302 header( 'HTTP/1.0 500 Internal Server Error' );
1303 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1304 /* Don't cache error pages! They cause no end of trouble... */
1305 header( 'Cache-control: none' );
1306 header( 'Pragma: nocache' );
1308 $msg = $wgSiteNotice;
1309 if($msg == '') $msg = wfMsgNoDB( 'noconnect', $error );
1310 $text = $msg;
1312 if($wgUseFileCache) {
1313 if($wgTitle) {
1314 $t =& $wgTitle;
1315 } else {
1316 if($title) {
1317 $t = Title::newFromURL( $title );
1318 } elseif (@/**/$_REQUEST['search']) {
1319 $search = $_REQUEST['search'];
1320 echo wfMsgNoDB( 'searchdisabled' );
1321 echo wfMsgNoDB( 'googlesearch', htmlspecialchars( $search ), $wgInputEncoding );
1322 wfErrorExit();
1323 } else {
1324 $t = Title::newFromText( wfMsgNoDB( 'mainpage' ) );
1328 $cache = new CacheManager( $t );
1329 if( $cache->isFileCached() ) {
1330 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1331 wfMsgNoDB( 'cachederror' ) . "</b></p>\n";
1333 $tag = '<div id="article">';
1334 $text = str_replace(
1335 $tag,
1336 $tag . $msg,
1337 $cache->fetchPageText() );
1341 echo $text;
1342 wfErrorExit();