Quick fix for canonical redirects when the URL is case-converted.
[mediawiki.git] / includes / Database.php
blob829bb56a98099ce0d69220345a4ab62037bba04b
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 );
21 /** Number of times to re-try an operation in case of deadlock */
22 define( 'DEADLOCK_TRIES', 4 );
23 /** Minimum time to wait before retry, in microseconds */
24 define( 'DEADLOCK_DELAY_MIN', 500000 );
25 /** Maximum time to wait before retry */
26 define( 'DEADLOCK_DELAY_MAX', 1500000 );
28 /**
29 * Database abstraction object
30 * @package MediaWiki
31 * @version # $Id$
33 class Database {
35 #------------------------------------------------------------------------------
36 # Variables
37 #------------------------------------------------------------------------------
38 /**#@+
39 * @access private
41 var $mLastQuery = '';
43 var $mServer, $mUser, $mPassword, $mConn, $mDBname;
44 var $mOut, $mOpened = false;
46 var $mFailFunction;
47 var $mTablePrefix;
48 var $mFlags;
49 var $mTrxLevel = 0;
50 /**#@-*/
52 #------------------------------------------------------------------------------
53 # Accessors
54 #------------------------------------------------------------------------------
55 # These optionally set a variable and return the previous state
57 /**
58 * Fail function, takes a Database as a parameter
59 * Set to false for default, 1 for ignore errors
61 function failFunction( $function = NULL ) {
62 return wfSetVar( $this->mFailFunction, $function );
65 /**
66 * Output page, used for reporting errors
67 * FALSE means discard output
69 function &setOutputPage( &$out ) {
70 $this->mOut =& $out;
73 /**
74 * Boolean, controls output of large amounts of debug information
76 function debug( $debug = NULL ) {
77 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
80 /**
81 * Turns buffering of SQL result sets on (true) or off (false).
82 * Default is "on" and it should not be changed without good reasons.
84 function bufferResults( $buffer = NULL ) {
85 if ( is_null( $buffer ) ) {
86 return !(bool)( $this->mFlags & DBO_NOBUFFER );
87 } else {
88 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
92 /**
93 * Turns on (false) or off (true) the automatic generation and sending
94 * of a "we're sorry, but there has been a database error" page on
95 * database errors. Default is on (false). When turned off, the
96 * code should use wfLastErrno() and wfLastError() to handle the
97 * situation as appropriate.
99 function ignoreErrors( $ignoreErrors = NULL ) {
100 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
104 * The current depth of nested transactions
105 * @param integer $level
107 function trxLevel( $level = NULL ) {
108 return wfSetVar( $this->mTrxLevel, $level );
111 /**#@+
112 * Get function
114 function lastQuery() { return $this->mLastQuery; }
115 function isOpen() { return $this->mOpened; }
116 /**#@-*/
118 #------------------------------------------------------------------------------
119 # Other functions
120 #------------------------------------------------------------------------------
122 /**#@+
123 * @param string $server database server host
124 * @param string $user database user name
125 * @param string $password database user password
126 * @param string $dbname database name
130 * @param failFunction
131 * @param $flags
132 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
134 function Database( $server = false, $user = false, $password = false, $dbName = false,
135 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
137 global $wgOut, $wgDBprefix, $wgCommandLineMode;
138 # Can't get a reference if it hasn't been set yet
139 if ( !isset( $wgOut ) ) {
140 $wgOut = NULL;
142 $this->mOut =& $wgOut;
144 $this->mFailFunction = $failFunction;
145 $this->mFlags = $flags;
147 if ( $this->mFlags & DBO_DEFAULT ) {
148 if ( $wgCommandLineMode ) {
149 $this->mFlags &= ~DBO_TRX;
150 } else {
151 $this->mFlags |= DBO_TRX;
155 /** Get the default table prefix*/
156 if ( $tablePrefix == 'get from global' ) {
157 $this->mTablePrefix = $wgDBprefix;
158 } else {
159 $this->mTablePrefix = $tablePrefix;
162 if ( $server ) {
163 $this->open( $server, $user, $password, $dbName );
168 * @static
169 * @param failFunction
170 * @param $flags
172 function newFromParams( $server, $user, $password, $dbName,
173 $failFunction = false, $flags = 0 )
175 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
179 * Usually aborts on failure
180 * If the failFunction is set to a non-zero integer, returns success
182 function open( $server, $user, $password, $dbName ) {
183 # Test for missing mysql.so
184 # Otherwise we get a suppressed fatal error, which is very hard to track down
185 if ( !function_exists( 'mysql_connect' ) ) {
186 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
189 $this->close();
190 $this->mServer = $server;
191 $this->mUser = $user;
192 $this->mPassword = $password;
193 $this->mDBname = $dbName;
195 $success = false;
197 @/**/$this->mConn = mysql_connect( $server, $user, $password );
198 if ( $dbName != '' ) {
199 if ( $this->mConn !== false ) {
200 $success = @/**/mysql_select_db( $dbName, $this->mConn );
201 if ( !$success ) {
202 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
204 } else {
205 wfDebug( "DB connection error\n" );
206 wfDebug( "Server: $server, User: $user, Password: " .
207 substr( $password, 0, 3 ) . "...\n" );
208 $success = false;
210 } else {
211 # Delay USE query
212 $success = !!$this->mConn;
215 if ( !$success ) {
216 $this->reportConnectionError();
217 $this->close();
219 $this->mOpened = $success;
220 return $success;
222 /**#@-*/
225 * Closes a database connection.
226 * if it is open : commits any open transactions
228 * @return bool operation success. true if already closed.
230 function close()
232 $this->mOpened = false;
233 if ( $this->mConn ) {
234 if ( $this->trxLevel() ) {
235 $this->immediateCommit();
237 return mysql_close( $this->mConn );
238 } else {
239 return true;
244 * @access private
245 * @param string $msg error message ?
246 * @todo parameter $msg is not used
248 function reportConnectionError( $msg = '') {
249 if ( $this->mFailFunction ) {
250 if ( !is_int( $this->mFailFunction ) ) {
251 $ff = $this->mFailFunction;
252 $ff( $this, mysql_error() );
254 } else {
255 wfEmergencyAbort( $this, mysql_error() );
260 * Usually aborts on failure
261 * If errors are explicitly ignored, returns success
263 function query( $sql, $fname = '', $tempIgnore = false ) {
264 global $wgProfiling, $wgCommandLineMode;
266 if ( $wgProfiling ) {
267 # generalizeSQL will probably cut down the query to reasonable
268 # logging size most of the time. The substr is really just a sanity check.
269 $profName = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
270 wfProfileIn( $profName );
273 $this->mLastQuery = $sql;
275 if ( $this->debug() ) {
276 $sqlx = substr( $sql, 0, 500 );
277 $sqlx = wordwrap(strtr($sqlx,"\t\n",' '));
278 wfDebug( "SQL: $sqlx\n" );
280 # Add a comment for easy SHOW PROCESSLIST interpretation
281 if ( $fname ) {
282 $commentedSql = "/* $fname */ $sql";
283 } else {
284 $commentedSql = $sql;
287 # If DBO_TRX is set, start a transaction
288 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() && $sql != 'BEGIN' ) {
289 $this->begin();
292 # Do the query and handle errors
293 $ret = $this->doQuery( $commentedSql );
294 if ( false === $ret ) {
295 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
298 if ( $wgProfiling ) {
299 wfProfileOut( $profName );
301 return $ret;
305 * The DBMS-dependent part of query()
306 * @param string $sql SQL query.
308 function doQuery( $sql ) {
309 if( $this->bufferResults() ) {
310 $ret = mysql_query( $sql, $this->mConn );
311 } else {
312 $ret = mysql_unbuffered_query( $sql, $this->mConn );
314 return $ret;
318 * @param $error
319 * @param $errno
320 * @param $sql
321 * @param string $fname
322 * @param bool $tempIgnore
324 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
325 global $wgCommandLineMode, $wgFullyInitialised;
326 # Ignore errors during error handling to avoid infinite recursion
327 $ignore = $this->ignoreErrors( true );
329 if( $ignore || $tempIgnore ) {
330 wfDebug("SQL ERROR (ignored): " . $error . "\n");
331 } else {
332 $sql1line = str_replace( "\n", "\\n", $sql );
333 wfLogDBError("$fname\t$errno\t$error\t$sql1line\n");
334 wfDebug("SQL ERROR: " . $error . "\n");
335 if ( $wgCommandLineMode || !$this->mOut || empty( $wgFullyInitialised ) ) {
336 $message = "A database error has occurred\n" .
337 "Query: $sql\n" .
338 "Function: $fname\n" .
339 "Error: $errno $error\n";
340 if ( !$wgCommandLineMode ) {
341 $message = nl2br( $message );
343 wfDebugDieBacktrace( $message );
344 } else {
345 // this calls wfAbruptExit()
346 $this->mOut->databaseError( $fname, $sql, $error, $errno );
349 $this->ignoreErrors( $ignore );
353 /**#@+
354 * @param mixed $res A SQL result
357 * @todo document
359 function freeResult( $res ) {
360 if ( !@/**/mysql_free_result( $res ) ) {
361 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
366 * @todo FIXME: HACK HACK HACK HACK debug
368 function fetchObject( $res ) {
369 @/**/$row = mysql_fetch_object( $res );
370 # FIXME: HACK HACK HACK HACK debug
371 if( mysql_errno() ) {
372 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
374 return $row;
378 * @todo document
380 function fetchRow( $res ) {
381 @/**/$row = mysql_fetch_array( $res );
382 if (mysql_errno() ) {
383 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
385 return $row;
389 * @todo document
391 function numRows( $res ) {
392 @/**/$n = mysql_num_rows( $res );
393 if( mysql_errno() ) {
394 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
396 return $n;
400 * @todo document
402 function numFields( $res ) { return mysql_num_fields( $res ); }
405 * @todo document
407 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
409 * @todo document
411 function insertId() { return mysql_insert_id( $this->mConn ); }
413 * @todo document
415 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
417 * @todo document
419 function lastErrno() { return mysql_errno(); }
421 * @todo document
423 function lastError() { return mysql_error(); }
425 * @todo document
427 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
428 /**#@-*/ // end of template : @param $result
432 * Simple UPDATE wrapper
433 * Usually aborts on failure
434 * If errors are explicitly ignored, returns success
436 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
438 $table = $this->tableName( $table );
439 $sql = "UPDATE $table SET $var = '" .
440 $this->strencode( $value ) . "' WHERE ($cond)";
441 return !!$this->query( $sql, DB_MASTER, $fname );
445 * @todo document
447 function getField( $table, $var, $cond='', $fname = 'Database::getField', $options = array() ) {
448 return $this->selectField( $table, $var, $cond, $fname = 'Database::get', $options = array() );
452 * Simple SELECT wrapper, returns a single field, input must be encoded
453 * Usually aborts on failure
454 * If errors are explicitly ignored, returns FALSE on failure
456 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
457 if ( !is_array( $options ) ) {
458 $options = array( $options );
460 $options['LIMIT'] = 1;
462 $res = $this->select( $table, $var, $cond, $fname, $options );
463 if ( $res === false || !$this->numRows( $res ) ) {
464 return false;
466 $row = $this->fetchRow( $res );
467 if ( $row !== false ) {
468 $this->freeResult( $res );
469 return $row[0];
470 } else {
471 return false;
476 * Returns an optional USE INDEX clause to go after the table, and a
477 * string to go at the end of the query
479 function makeSelectOptions( $options ) {
480 if ( !is_array( $options ) ) {
481 $options = array( $options );
484 $tailOpts = '';
486 if ( isset( $options['ORDER BY'] ) ) {
487 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
489 if ( isset( $options['LIMIT'] ) ) {
490 $tailOpts .= " LIMIT {$options['LIMIT']}";
493 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
494 $tailOpts .= ' FOR UPDATE';
497 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
498 $tailOpts .= ' LOCK IN SHARE MODE';
501 if ( isset( $options['USE INDEX'] ) ) {
502 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
503 } else {
504 $useIndex = '';
506 return array( $useIndex, $tailOpts );
510 * SELECT wrapper
512 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
514 if ( is_array( $vars ) ) {
515 $vars = implode( ',', $vars );
517 if ($table!='')
518 $from = ' FROM ' .$this->tableName( $table );
519 else
520 $from = '';
522 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
524 if ( $conds !== false && $conds != '' ) {
525 if ( is_array( $conds ) ) {
526 $conds = $this->makeList( $conds, LIST_AND );
528 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
529 } else {
530 $sql = "SELECT $vars $from $useIndex $tailOpts";
532 return $this->query( $sql, $fname );
536 * @todo document
538 function getArray( $table, $vars, $conds, $fname = 'Database::getArray', $options = array() ) {
539 return $this->selectRow( $table, $vars, $conds, $fname, $options );
544 * Single row SELECT wrapper
545 * Aborts or returns FALSE on error
547 * $vars: the selected variables
548 * $conds: a condition map, terms are ANDed together.
549 * Items with numeric keys are taken to be literal conditions
550 * Takes an array of selected variables, and a condition map, which is ANDed
551 * e.g. selectRow( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
552 * would return an object where $obj->cur_id is the ID of the Astronomy article
554 * @todo migrate documentation to phpdocumentor format
556 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
557 $options['LIMIT'] = 1;
558 $res = $this->select( $table, $vars, $conds, $fname, $options );
559 if ( $res === false || !$this->numRows( $res ) ) {
560 return false;
562 $obj = $this->fetchObject( $res );
563 $this->freeResult( $res );
564 return $obj;
569 * Removes most variables from an SQL query and replaces them with X or N for numbers.
570 * It's only slightly flawed. Don't use for anything important.
572 * @param string $sql A SQL Query
573 * @static
575 function generalizeSQL( $sql ) {
576 # This does the same as the regexp below would do, but in such a way
577 # as to avoid crashing php on some large strings.
578 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
580 $sql = str_replace ( "\\\\", '', $sql);
581 $sql = str_replace ( "\\'", '', $sql);
582 $sql = str_replace ( "\\\"", '', $sql);
583 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
584 $sql = preg_replace ('/".*"/s', "'X'", $sql);
586 # All newlines, tabs, etc replaced by single space
587 $sql = preg_replace ( "/\s+/", ' ', $sql);
589 # All numbers => N
590 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
592 return $sql;
596 * Determines whether a field exists in a table
597 * Usually aborts on failure
598 * If errors are explicitly ignored, returns NULL on failure
600 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
601 $table = $this->tableName( $table );
602 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE, $fname );
603 if ( !$res ) {
604 return NULL;
607 $found = false;
609 while ( $row = $this->fetchObject( $res ) ) {
610 if ( $row->Field == $field ) {
611 $found = true;
612 break;
615 return $found;
619 * Determines whether an index exists
620 * Usually aborts on failure
621 * If errors are explicitly ignored, returns NULL on failure
623 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
624 $info = $this->indexInfo( $table, $index, $fname );
625 if ( is_null( $info ) ) {
626 return NULL;
627 } else {
628 return $info !== false;
634 * @todo document
636 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
637 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
638 # SHOW INDEX should work for 3.x and up:
639 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
640 $table = $this->tableName( $table );
641 $sql = 'SHOW INDEX FROM '.$table;
642 $res = $this->query( $sql, $fname );
643 if ( !$res ) {
644 return NULL;
647 while ( $row = $this->fetchObject( $res ) ) {
648 if ( $row->Key_name == $index ) {
649 return $row;
652 return false;
656 * @param $table
657 * @todo document
659 function tableExists( $table ) {
660 $table = $this->tableName( $table );
661 $old = $this->ignoreErrors( true );
662 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
663 $this->ignoreErrors( $old );
664 if( $res ) {
665 $this->freeResult( $res );
666 return true;
667 } else {
668 return false;
673 * @param $table
674 * @param $field
675 * @todo document
677 function fieldInfo( $table, $field ) {
678 $table = $this->tableName( $table );
679 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
680 $n = mysql_num_fields( $res );
681 for( $i = 0; $i < $n; $i++ ) {
682 $meta = mysql_fetch_field( $res, $i );
683 if( $field == $meta->name ) {
684 return $meta;
687 return false;
691 * @todo document
693 function fieldType( $res, $index ) {
694 return mysql_field_type( $res, $index );
698 * @todo document
700 function indexUnique( $table, $index ) {
701 $indexInfo = $this->indexInfo( $table, $index );
702 if ( !$indexInfo ) {
703 return NULL;
705 return !$indexInfo->Non_unique;
709 * @todo document
711 function insertArray( $table, $a, $fname = 'Database::insertArray', $options = array() ) {
712 return $this->insert( $table, $a, $fname = 'Database::insertArray', $options = array() );
716 * INSERT wrapper, inserts an array into a table
718 * $a may be a single associative array, or an array of these with numeric keys, for
719 * multi-row insert.
721 * Usually aborts on failure
722 * If errors are explicitly ignored, returns success
724 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
725 # No rows to insert, easy just return now
726 if ( !count( $a ) ) {
727 return true;
730 $table = $this->tableName( $table );
731 if ( !is_array( $options ) ) {
732 $options = array( $options );
734 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
735 $multi = true;
736 $keys = array_keys( $a[0] );
737 } else {
738 $multi = false;
739 $keys = array_keys( $a );
742 $sql = 'INSERT ' . implode( ' ', $options ) .
743 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
745 if ( $multi ) {
746 $first = true;
747 foreach ( $a as $row ) {
748 if ( $first ) {
749 $first = false;
750 } else {
751 $sql .= ',';
753 $sql .= '(' . $this->makeList( $row ) . ')';
755 } else {
756 $sql .= '(' . $this->makeList( $a ) . ')';
758 return !!$this->query( $sql, $fname );
762 * @todo document
764 function updateArray( $table, $values, $conds, $fname = 'Database::updateArray' ) {
765 return $this->update( $table, $values, $conds, $fname );
769 * UPDATE wrapper, takes a condition array and a SET array
771 function update( $table, $values, $conds, $fname = 'Database::update' ) {
772 $table = $this->tableName( $table );
773 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET );
774 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
775 $this->query( $sql, $fname );
779 * Makes a wfStrencoded list from an array
780 * $mode: LIST_COMMA - comma separated, no field names
781 * LIST_AND - ANDed WHERE clause (without the WHERE)
782 * LIST_SET - comma separated with field names, like a SET clause
784 function makeList( $a, $mode = LIST_COMMA ) {
785 if ( !is_array( $a ) ) {
786 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
789 $first = true;
790 $list = '';
791 foreach ( $a as $field => $value ) {
792 if ( !$first ) {
793 if ( $mode == LIST_AND ) {
794 $list .= ' AND ';
795 } else {
796 $list .= ',';
798 } else {
799 $first = false;
801 if ( $mode == LIST_AND && is_numeric( $field ) ) {
802 $list .= "($value)";
803 } else {
804 if ( $mode == LIST_AND || $mode == LIST_SET ) {
805 $list .= $field.'=';
807 $list .= $this->addQuotes( $value );
810 return $list;
814 * @todo document
816 function selectDB( $db ) {
817 $this->mDBname = $db;
818 mysql_select_db( $db, $this->mConn );
822 * @todo document
824 function startTimer( $timeout ) {
825 global $IP;
826 if( function_exists( 'mysql_thread_id' ) ) {
827 # This will kill the query if it's still running after $timeout seconds.
828 $tid = mysql_thread_id( $this->mConn );
829 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );
834 * Does nothing at all
835 * @todo document
837 function stopTimer() { }
840 * @param string $name database table name
841 * @todo document
843 function tableName( $name ) {
844 global $wgSharedDB;
845 if ( $this->mTablePrefix !== '' ) {
846 if ( strpos( '.', $name ) === false ) {
847 $name = $this->mTablePrefix . $name;
850 if ( isset( $wgSharedDB ) && 'user' == $name ) {
851 $name = $wgSharedDB . '.' . $name;
853 return $name;
857 * @todo document
859 function tableNames() {
860 $inArray = func_get_args();
861 $retVal = array();
862 foreach ( $inArray as $name ) {
863 $retVal[$name] = $this->tableName( $name );
865 return $retVal;
869 * Wrapper for addslashes()
870 * @param string $s String to be slashed.
871 * @return string slashed string.
873 function strencode( $s ) {
874 return addslashes( $s );
878 * If it's a string, adds quotes and backslashes
879 * Otherwise returns as-is
881 function addQuotes( $s ) {
882 if ( is_null( $s ) ) {
883 $s = 'NULL';
884 } else {
885 # This will also quote numeric values. This should be harmless,
886 # and protects against weird problems that occur when they really
887 # _are_ strings such as article titles and string->number->string
888 # conversion is not 1:1.
889 $s = "'" . $this->strencode( $s ) . "'";
891 return $s;
895 * Returns an appropriately quoted sequence value for inserting a new row.
896 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
897 * subclass will return an integer, and save the value for insertId()
899 function nextSequenceValue( $seqName ) {
900 return NULL;
904 * USE INDEX clause
905 * PostgreSQL doesn't have them and returns ""
907 function useIndexClause( $index ) {
908 return 'USE INDEX ('.$index.')';
912 * REPLACE query wrapper
913 * PostgreSQL simulates this with a DELETE followed by INSERT
914 * $row is the row to insert, an associative array
915 * $uniqueIndexes is an array of indexes. Each element may be either a
916 * field name or an array of field names
918 * It may be more efficient to leave off unique indexes which are unlikely to collide.
919 * However if you do this, you run the risk of encountering errors which wouldn't have
920 * occurred in MySQL
922 * @todo migrate comment to phodocumentor format
924 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
925 $table = $this->tableName( $table );
927 # Single row case
928 if ( !is_array( reset( $rows ) ) ) {
929 $rows = array( $rows );
932 $sql = "REPLACE INTO $table (" . implode( ',', array_flip( $rows[0] ) ) .') VALUES ';
933 $first = true;
934 foreach ( $rows as $row ) {
935 if ( $first ) {
936 $first = false;
937 } else {
938 $sql .= ',';
940 $sql .= '(' . $this->makeList( $row ) . ')';
942 return $this->query( $sql, $fname );
946 * DELETE where the condition is a join
947 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
949 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
950 * join condition matches, set $conds='*'
952 * DO NOT put the join condition in $conds
954 * @param string $delTable The table to delete from.
955 * @param string $joinTable The other table.
956 * @param string $delVar The variable to join on, in the first table.
957 * @param string $joinVar The variable to join on, in the second table.
958 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
960 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
961 if ( !$conds ) {
962 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
965 $delTable = $this->tableName( $delTable );
966 $joinTable = $this->tableName( $joinTable );
967 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
968 if ( $conds != '*' ) {
969 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
972 return $this->query( $sql, $fname );
976 * Returns the size of a text field, or -1 for "unlimited"
978 function textFieldSize( $table, $field ) {
979 $table = $this->tableName( $table );
980 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
981 $res = $this->query( $sql, 'Database::textFieldSize' );
982 $row = $this->fetchObject( $res );
983 $this->freeResult( $res );
985 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
986 $size = $m[1];
987 } else {
988 $size = -1;
990 return $size;
994 * @return string Always return 'LOW_PRIORITY'
996 function lowPriorityOption() {
997 return 'LOW_PRIORITY';
1001 * Use $conds == "*" to delete all rows
1002 * @todo document
1004 function delete( $table, $conds, $fname = 'Database::delete' ) {
1005 if ( !$conds ) {
1006 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1008 $table = $this->tableName( $table );
1009 $sql = "DELETE FROM $table ";
1010 if ( $conds != '*' ) {
1011 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
1013 return $this->query( $sql, $fname );
1017 * INSERT SELECT wrapper
1018 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1019 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1020 * $conds may be "*" to copy the whole table
1022 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1023 $destTable = $this->tableName( $destTable );
1024 $srcTable = $this->tableName( $srcTable );
1025 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1026 ' SELECT ' . implode( ',', $varMap ) .
1027 " FROM $srcTable";
1028 if ( $conds != '*' ) {
1029 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1031 return $this->query( $sql, $fname );
1035 * @todo document
1037 function limitResult($limit,$offset) {
1038 return ' LIMIT '.(is_numeric($offset)?"{$offset},":"")."{$limit} ";
1042 * @todo document
1044 function wasDeadlock() {
1045 return $this->lastErrno() == 1213;
1049 * @todo document
1051 function deadlockLoop() {
1052 $myFname = 'Database::deadlockLoop';
1054 $this->query( 'BEGIN', $myFname );
1055 $args = func_get_args();
1056 $function = array_shift( $args );
1057 $oldIgnore = $dbw->ignoreErrors( true );
1058 $tries = DEADLOCK_TRIES;
1059 if ( is_array( $function ) ) {
1060 $fname = $function[0];
1061 } else {
1062 $fname = $function;
1064 do {
1065 $retVal = call_user_func_array( $function, $args );
1066 $error = $this->lastError();
1067 $errno = $this->lastErrno();
1068 $sql = $this->lastQuery();
1070 if ( $errno ) {
1071 if ( $dbw->wasDeadlock() ) {
1072 # Retry
1073 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1074 } else {
1075 $dbw->reportQueryError( $error, $errno, $sql, $fname );
1078 } while( $dbw->wasDeadlock && --$tries > 0 );
1079 $this->ignoreErrors( $oldIgnore );
1080 if ( $tries <= 0 ) {
1081 $this->query( 'ROLLBACK', $myFname );
1082 $this->reportQueryError( $error, $errno, $sql, $fname );
1083 return false;
1084 } else {
1085 $this->query( 'COMMIT', $myFname );
1086 return $retVal;
1091 * Do a SELECT MASTER_POS_WAIT()
1092 * @todo document
1094 function masterPosWait( $file, $pos, $timeout ) {
1095 $encFile = $this->strencode( $file );
1096 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1097 $res = $this->query( $sql, 'Database::masterPosWait' );
1098 if ( $res && $row = $this->fetchRow( $res ) ) {
1099 $this->freeResult( $res );
1100 return $row[0];
1101 } else {
1102 return false;
1107 * Get the position of the master from SHOW SLAVE STATUS
1109 function getSlavePos() {
1110 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1111 $row = $this->fetchObject( $res );
1112 if ( $row ) {
1113 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1114 } else {
1115 return array( false, false );
1120 * Get the position of the master from SHOW MASTER STATUS
1122 function getMasterPos() {
1123 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1124 $row = $this->fetchObject( $res );
1125 if ( $row ) {
1126 return array( $row->File, $row->Position );
1127 } else {
1128 return array( false, false );
1133 * Begin a transaction, or if a transaction has already started, continue it
1135 function begin( $fname = 'Database::begin' ) {
1136 if ( !$this->mTrxLevel ) {
1137 $this->immediateBegin( $fname );
1138 } else {
1139 $this->mTrxLevel++;
1144 * End a transaction, or decrement the nest level if transactions are nested
1146 function commit( $fname = 'Database::commit' ) {
1147 if ( $this->mTrxLevel ) {
1148 $this->mTrxLevel--;
1150 if ( !$this->mTrxLevel ) {
1151 $this->immediateCommit( $fname );
1156 * Rollback a transaction
1158 function rollback( $fname = 'Database::rollback' ) {
1159 $this->query( 'ROLLBACK', $fname );
1160 $this->mTrxLevel = 0;
1164 * Begin a transaction, committing any previously open transaction
1166 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1167 $this->query( 'BEGIN', $fname );
1168 $this->mTrxLevel = 1;
1172 * Commit transaction, if one is open
1174 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1175 $this->query( 'COMMIT', $fname );
1176 $this->mTrxLevel = 0;
1180 * Return MW-style timestamp used for MySQL schema
1182 function timestamp( $ts=0 ) {
1183 return wfTimestamp(TS_MW,$ts);
1187 * @todo document
1189 function &resultObject( &$result ) {
1190 if( empty( $result ) ) {
1191 return NULL;
1192 } else {
1193 return new ResultWrapper( $this, $result );
1199 * Database abstraction object for mySQL
1200 * Inherit all methods and properties of Database::Database()
1202 * @package MediaWiki
1203 * @see Database
1204 * @version # $Id$
1206 class DatabaseMysql extends Database {
1207 # Inherit all
1212 * Result wrapper for grabbing data queried by someone else
1214 * @package MediaWiki
1215 * @version # $Id$
1217 class ResultWrapper {
1218 var $db, $result;
1221 * @todo document
1223 function ResultWrapper( $database, $result ) {
1224 $this->db =& $database;
1225 $this->result =& $result;
1229 * @todo document
1231 function numRows() {
1232 return $this->db->numRows( $this->result );
1236 * @todo document
1238 function &fetchObject() {
1239 return $this->db->fetchObject( $this->result );
1243 * @todo document
1245 function &fetchRow() {
1246 return $this->db->fetchRow( $this->result );
1250 * @todo document
1252 function free() {
1253 $this->db->freeResult( $this->result );
1254 unset( $this->result );
1255 unset( $this->db );
1259 #------------------------------------------------------------------------------
1260 # Global functions
1261 #------------------------------------------------------------------------------
1264 * Standard fail function, called by default when a connection cannot be
1265 * established.
1266 * Displays the file cache if possible
1268 function wfEmergencyAbort( &$conn, $error ) {
1269 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
1271 if( !headers_sent() ) {
1272 header( 'HTTP/1.0 500 Internal Server Error' );
1273 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1274 /* Don't cache error pages! They cause no end of trouble... */
1275 header( 'Cache-control: none' );
1276 header( 'Pragma: nocache' );
1278 $msg = $wgSiteNotice;
1279 if($msg == '') $msg = wfMsgNoDB( 'noconnect', $error );
1280 $text = $msg;
1282 if($wgUseFileCache) {
1283 if($wgTitle) {
1284 $t =& $wgTitle;
1285 } else {
1286 if($title) {
1287 $t = Title::newFromURL( $title );
1288 } elseif (@/**/$_REQUEST['search']) {
1289 $search = $_REQUEST['search'];
1290 echo wfMsgNoDB( 'searchdisabled' );
1291 echo wfMsgNoDB( 'googlesearch', htmlspecialchars( $search ), $wgInputEncoding );
1292 wfErrorExit();
1293 } else {
1294 $t = Title::newFromText( wfMsgNoDB( 'mainpage' ) );
1298 $cache = new CacheManager( $t );
1299 if( $cache->isFileCached() ) {
1300 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1301 wfMsgNoDB( 'cachederror' ) . "</b></p>\n";
1303 $tag = '<div id="article">';
1304 $text = str_replace(
1305 $tag,
1306 $tag . $msg,
1307 $cache->fetchPageText() );
1311 echo $text;
1312 wfErrorExit();