Removed allpagesformtext1 and allpagesformtext2, obsolete
[mediawiki.git] / includes / Database.php
blob73580316e067248bf1144a39213ff8433ef08830
1 <?php
2 /**
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
5 * @package MediaWiki
6 */
8 /**
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);
19 /** Number of times to re-try an operation in case of deadlock */
20 define( 'DEADLOCK_TRIES', 4 );
21 /** Minimum time to wait before retry, in microseconds */
22 define( 'DEADLOCK_DELAY_MIN', 500000 );
23 /** Maximum time to wait before retry */
24 define( 'DEADLOCK_DELAY_MAX', 1500000 );
26 /**
27 * Database abstraction object
28 * @package MediaWiki
30 class Database {
32 #------------------------------------------------------------------------------
33 # Variables
34 #------------------------------------------------------------------------------
35 /**#@+
36 * @access private
38 var $mLastQuery = '';
40 var $mServer, $mUser, $mPassword, $mConn, $mDBname;
41 var $mOut, $mOpened = false;
43 var $mFailFunction;
44 var $mTablePrefix;
45 var $mFlags;
46 var $mTrxLevel = 0;
47 var $mErrorCount = 0;
48 /**#@-*/
50 #------------------------------------------------------------------------------
51 # Accessors
52 #------------------------------------------------------------------------------
53 # These optionally set a variable and return the previous state
55 /**
56 * Fail function, takes a Database as a parameter
57 * Set to false for default, 1 for ignore errors
59 function failFunction( $function = NULL ) {
60 return wfSetVar( $this->mFailFunction, $function );
63 /**
64 * Output page, used for reporting errors
65 * FALSE means discard output
67 function &setOutputPage( &$out ) {
68 $this->mOut =& $out;
71 /**
72 * Boolean, controls output of large amounts of debug information
74 function debug( $debug = NULL ) {
75 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
78 /**
79 * Turns buffering of SQL result sets on (true) or off (false).
80 * Default is "on" and it should not be changed without good reasons.
82 function bufferResults( $buffer = NULL ) {
83 if ( is_null( $buffer ) ) {
84 return !(bool)( $this->mFlags & DBO_NOBUFFER );
85 } else {
86 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
90 /**
91 * Turns on (false) or off (true) the automatic generation and sending
92 * of a "we're sorry, but there has been a database error" page on
93 * database errors. Default is on (false). When turned off, the
94 * code should use wfLastErrno() and wfLastError() to handle the
95 * situation as appropriate.
97 function ignoreErrors( $ignoreErrors = NULL ) {
98 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
102 * The current depth of nested transactions
103 * @param integer $level
105 function trxLevel( $level = NULL ) {
106 return wfSetVar( $this->mTrxLevel, $level );
109 /**
110 * Number of errors logged, only useful when errors are ignored
112 function errorCount( $count = NULL ) {
113 return wfSetVar( $this->mErrorCount, $count );
116 /**#@+
117 * Get function
119 function lastQuery() { return $this->mLastQuery; }
120 function isOpen() { return $this->mOpened; }
121 /**#@-*/
123 #------------------------------------------------------------------------------
124 # Other functions
125 #------------------------------------------------------------------------------
127 /**#@+
128 * @param string $server database server host
129 * @param string $user database user name
130 * @param string $password database user password
131 * @param string $dbname database name
135 * @param failFunction
136 * @param $flags
137 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
139 function Database( $server = false, $user = false, $password = false, $dbName = false,
140 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
142 global $wgOut, $wgDBprefix, $wgCommandLineMode;
143 # Can't get a reference if it hasn't been set yet
144 if ( !isset( $wgOut ) ) {
145 $wgOut = NULL;
147 $this->mOut =& $wgOut;
149 $this->mFailFunction = $failFunction;
150 $this->mFlags = $flags;
152 if ( $this->mFlags & DBO_DEFAULT ) {
153 if ( $wgCommandLineMode ) {
154 $this->mFlags &= ~DBO_TRX;
155 } else {
156 $this->mFlags |= DBO_TRX;
161 // Faster read-only access
162 if ( wfReadOnly() ) {
163 $this->mFlags |= DBO_PERSISTENT;
164 $this->mFlags &= ~DBO_TRX;
167 /** Get the default table prefix*/
168 if ( $tablePrefix == 'get from global' ) {
169 $this->mTablePrefix = $wgDBprefix;
170 } else {
171 $this->mTablePrefix = $tablePrefix;
174 if ( $server ) {
175 $this->open( $server, $user, $password, $dbName );
180 * @static
181 * @param failFunction
182 * @param $flags
184 function newFromParams( $server, $user, $password, $dbName,
185 $failFunction = false, $flags = 0 )
187 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
191 * Usually aborts on failure
192 * If the failFunction is set to a non-zero integer, returns success
194 function open( $server, $user, $password, $dbName ) {
195 # Test for missing mysql.so
196 # First try to load it
197 if (!@extension_loaded('mysql')) {
198 @dl('mysql.so');
201 # Otherwise we get a suppressed fatal error, which is very hard to track down
202 if ( !function_exists( 'mysql_connect' ) ) {
203 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
206 $this->close();
207 $this->mServer = $server;
208 $this->mUser = $user;
209 $this->mPassword = $password;
210 $this->mDBname = $dbName;
212 $success = false;
214 if ( $this->mFlags & DBO_PERSISTENT ) {
215 @/**/$this->mConn = mysql_pconnect( $server, $user, $password );
216 } else {
217 @/**/$this->mConn = mysql_connect( $server, $user, $password );
220 if ( $dbName != '' ) {
221 if ( $this->mConn !== false ) {
222 $success = @/**/mysql_select_db( $dbName, $this->mConn );
223 if ( !$success ) {
224 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
226 } else {
227 wfDebug( "DB connection error\n" );
228 wfDebug( "Server: $server, User: $user, Password: " .
229 substr( $password, 0, 3 ) . "...\n" );
230 $success = false;
232 } else {
233 # Delay USE query
234 $success = !!$this->mConn;
237 if ( !$success ) {
238 $this->reportConnectionError();
239 $this->close();
241 $this->mOpened = $success;
242 return $success;
244 /**#@-*/
247 * Closes a database connection.
248 * if it is open : commits any open transactions
250 * @return bool operation success. true if already closed.
252 function close()
254 $this->mOpened = false;
255 if ( $this->mConn ) {
256 if ( $this->trxLevel() ) {
257 $this->immediateCommit();
259 return mysql_close( $this->mConn );
260 } else {
261 return true;
266 * @access private
267 * @param string $msg error message ?
268 * @todo parameter $msg is not used
270 function reportConnectionError( $msg = '') {
271 if ( $this->mFailFunction ) {
272 if ( !is_int( $this->mFailFunction ) ) {
273 $ff = $this->mFailFunction;
274 $ff( $this, mysql_error() );
276 } else {
277 wfEmergencyAbort( $this, mysql_error() );
282 * Usually aborts on failure
283 * If errors are explicitly ignored, returns success
285 function query( $sql, $fname = '', $tempIgnore = false ) {
286 global $wgProfiling, $wgCommandLineMode;
288 if ( $wgProfiling ) {
289 # generalizeSQL will probably cut down the query to reasonable
290 # logging size most of the time. The substr is really just a sanity check.
291 $profName = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
292 wfProfileIn( 'Database::query' );
293 wfProfileIn( $profName );
296 $this->mLastQuery = $sql;
298 # Add a comment for easy SHOW PROCESSLIST interpretation
299 if ( $fname ) {
300 $commentedSql = "/* $fname */ $sql";
301 } else {
302 $commentedSql = $sql;
305 # If DBO_TRX is set, start a transaction
306 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() && $sql != 'BEGIN' ) {
307 $this->begin();
310 if ( $this->debug() ) {
311 $sqlx = substr( $sql, 0, 500 );
312 $sqlx = strtr($sqlx,"\t\n",' ');
313 wfDebug( "SQL: $sqlx\n" );
316 # Do the query and handle errors
317 $ret = $this->doQuery( $commentedSql );
319 # Try reconnecting if the connection was lost
320 if ( false === $ret && ( $this->lastErrno() == 2013 || $this->lastErrno() == 2006 ) ) {
321 # Transaction is gone, like it or not
322 $this->mTrxLevel = 0;
323 wfDebug( "Connection lost, reconnecting...\n" );
324 if ( $this->ping() ) {
325 wfDebug( "Reconnected\n" );
326 $ret = $this->doQuery( $commentedSql );
327 } else {
328 wfDebug( "Failed\n" );
332 if ( false === $ret ) {
333 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
336 if ( $wgProfiling ) {
337 wfProfileOut( $profName );
338 wfProfileOut( 'Database::query' );
340 return $ret;
344 * The DBMS-dependent part of query()
345 * @param string $sql SQL query.
347 function doQuery( $sql ) {
348 if( $this->bufferResults() ) {
349 $ret = mysql_query( $sql, $this->mConn );
350 } else {
351 $ret = mysql_unbuffered_query( $sql, $this->mConn );
353 return $ret;
357 * @param $error
358 * @param $errno
359 * @param $sql
360 * @param string $fname
361 * @param bool $tempIgnore
363 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
364 global $wgCommandLineMode, $wgFullyInitialised;
365 # Ignore errors during error handling to avoid infinite recursion
366 $ignore = $this->ignoreErrors( true );
367 $this->mErrorCount ++;
369 if( $ignore || $tempIgnore ) {
370 wfDebug("SQL ERROR (ignored): " . $error . "\n");
371 } else {
372 $sql1line = str_replace( "\n", "\\n", $sql );
373 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
374 wfDebug("SQL ERROR: " . $error . "\n");
375 if ( $wgCommandLineMode || !$this->mOut || empty( $wgFullyInitialised ) ) {
376 $message = "A database error has occurred\n" .
377 "Query: $sql\n" .
378 "Function: $fname\n" .
379 "Error: $errno $error\n";
380 if ( !$wgCommandLineMode ) {
381 $message = nl2br( $message );
383 wfDebugDieBacktrace( $message );
384 } else {
385 // this calls wfAbruptExit()
386 $this->mOut->databaseError( $fname, $sql, $error, $errno );
389 $this->ignoreErrors( $ignore );
394 * Intended to be compatible with the PEAR::DB wrapper functions.
395 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
397 * ? = scalar value, quoted as necessary
398 * ! = raw SQL bit (a function for instance)
399 * & = filename; reads the file and inserts as a blob
400 * (we don't use this though...)
402 function prepare( $sql, $func = 'Database::prepare' ) {
403 /* MySQL doesn't support prepared statements (yet), so just
404 pack up the query for reference. We'll manually replace
405 the bits later. */
406 return array( 'query' => $sql, 'func' => $func );
409 function freePrepared( $prepared ) {
410 /* No-op for MySQL */
414 * Execute a prepared query with the various arguments
415 * @param string $prepared the prepared sql
416 * @param mixed $args Either an array here, or put scalars as varargs
418 function execute( $prepared, $args = null ) {
419 if( !is_array( $args ) ) {
420 # Pull the var args
421 $args = func_get_args();
422 array_shift( $args );
424 $sql = $this->fillPrepared( $prepared['query'], $args );
425 return $this->query( $sql, $prepared['func'] );
429 * Prepare & execute an SQL statement, quoting and inserting arguments
430 * in the appropriate places.
431 * @param string $query
432 * @param string $args (default null)
434 function safeQuery( $query, $args = null ) {
435 $prepared = $this->prepare( $query, 'Database::safeQuery' );
436 if( !is_array( $args ) ) {
437 # Pull the var args
438 $args = func_get_args();
439 array_shift( $args );
441 $retval = $this->execute( $prepared, $args );
442 $this->freePrepared( $prepared );
443 return $retval;
447 * For faking prepared SQL statements on DBs that don't support
448 * it directly.
449 * @param string $preparedSql - a 'preparable' SQL statement
450 * @param array $args - array of arguments to fill it with
451 * @return string executable SQL
453 function fillPrepared( $preparedQuery, $args ) {
454 $n = 0;
455 reset( $args );
456 $this->preparedArgs =& $args;
457 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
458 array( &$this, 'fillPreparedArg' ), $preparedQuery );
462 * preg_callback func for fillPrepared()
463 * The arguments should be in $this->preparedArgs and must not be touched
464 * while we're doing this.
466 * @param array $matches
467 * @return string
468 * @access private
470 function fillPreparedArg( $matches ) {
471 switch( $matches[1] ) {
472 case '\\?': return '?';
473 case '\\!': return '!';
474 case '\\&': return '&';
476 list( $n, $arg ) = each( $this->preparedArgs );
477 switch( $matches[1] ) {
478 case '?': return $this->addQuotes( $arg );
479 case '!': return $arg;
480 case '&':
481 # return $this->addQuotes( file_get_contents( $arg ) );
482 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
483 default:
484 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
488 /**#@+
489 * @param mixed $res A SQL result
492 * Free a result object
494 function freeResult( $res ) {
495 if ( !@/**/mysql_free_result( $res ) ) {
496 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
501 * Fetch the next row from the given result object, in object form
503 function fetchObject( $res ) {
504 @/**/$row = mysql_fetch_object( $res );
505 if( mysql_errno() ) {
506 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
508 return $row;
512 * Fetch the next row from the given result object
513 * Returns an array
515 function fetchRow( $res ) {
516 @/**/$row = mysql_fetch_array( $res );
517 if (mysql_errno() ) {
518 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
520 return $row;
524 * Get the number of rows in a result object
526 function numRows( $res ) {
527 @/**/$n = mysql_num_rows( $res );
528 if( mysql_errno() ) {
529 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
531 return $n;
535 * Get the number of fields in a result object
536 * See documentation for mysql_num_fields()
538 function numFields( $res ) { return mysql_num_fields( $res ); }
541 * Get a field name in a result object
542 * See documentation for mysql_field_name()
544 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
547 * Get the inserted value of an auto-increment row
549 * The value inserted should be fetched from nextSequenceValue()
551 * Example:
552 * $id = $dbw->nextSequenceValue('page_page_id_seq');
553 * $dbw->insert('page',array('page_id' => $id));
554 * $id = $dbw->insertId();
556 function insertId() { return mysql_insert_id( $this->mConn ); }
559 * Change the position of the cursor in a result object
560 * See mysql_data_seek()
562 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
565 * Get the last error number
566 * See mysql_errno()
568 function lastErrno() {
569 if ( $this->mConn ) {
570 return mysql_errno( $this->mConn );
571 } else {
572 return mysql_errno();
577 * Get a description of the last error
578 * See mysql_error() for more details
580 function lastError() {
581 if ( $this->mConn ) {
582 $error = mysql_error( $this->mConn );
583 } else {
584 $error = mysql_error();
586 if( $error ) {
587 $error .= ' (' . $this->mServer . ')';
589 return $error;
592 * Get the number of rows affected by the last write query
593 * See mysql_affected_rows() for more details
595 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
596 /**#@-*/ // end of template : @param $result
599 * Simple UPDATE wrapper
600 * Usually aborts on failure
601 * If errors are explicitly ignored, returns success
603 * This function exists for historical reasons, Database::update() has a more standard
604 * calling convention and feature set
606 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
608 $table = $this->tableName( $table );
609 $sql = "UPDATE $table SET $var = '" .
610 $this->strencode( $value ) . "' WHERE ($cond)";
611 return !!$this->query( $sql, DB_MASTER, $fname );
615 * Simple SELECT wrapper, returns a single field, input must be encoded
616 * Usually aborts on failure
617 * If errors are explicitly ignored, returns FALSE on failure
619 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
620 if ( !is_array( $options ) ) {
621 $options = array( $options );
623 $options['LIMIT'] = 1;
625 $res = $this->select( $table, $var, $cond, $fname, $options );
626 if ( $res === false || !$this->numRows( $res ) ) {
627 return false;
629 $row = $this->fetchRow( $res );
630 if ( $row !== false ) {
631 $this->freeResult( $res );
632 return $row[0];
633 } else {
634 return false;
639 * Returns an optional USE INDEX clause to go after the table, and a
640 * string to go at the end of the query
642 * @access private
644 * @param array $options an associative array of options to be turned into
645 * an SQL query, valid keys are listed in the function.
646 * @return array
648 function makeSelectOptions( $options ) {
649 $tailOpts = '';
651 if ( isset( $options['ORDER BY'] ) ) {
652 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
654 if ( isset( $options['LIMIT'] ) ) {
655 $tailOpts .= " LIMIT {$options['LIMIT']}";
658 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
659 $tailOpts .= ' FOR UPDATE';
662 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
663 $tailOpts .= ' LOCK IN SHARE MODE';
666 if ( isset( $options['USE INDEX'] ) ) {
667 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
668 } else {
669 $useIndex = '';
671 return array( $useIndex, $tailOpts );
675 * SELECT wrapper
677 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
679 if( is_array( $vars ) ) {
680 $vars = implode( ',', $vars );
682 if( is_array( $table ) ) {
683 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
684 } elseif ($table!='') {
685 $from = ' FROM ' .$this->tableName( $table );
686 } else {
687 $from = '';
690 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( (array)$options );
692 if( !empty( $conds ) ) {
693 if ( is_array( $conds ) ) {
694 $conds = $this->makeList( $conds, LIST_AND );
696 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
697 } else {
698 $sql = "SELECT $vars $from $useIndex $tailOpts";
700 return $this->query( $sql, $fname );
704 * Single row SELECT wrapper
705 * Aborts or returns FALSE on error
707 * $vars: the selected variables
708 * $conds: a condition map, terms are ANDed together.
709 * Items with numeric keys are taken to be literal conditions
710 * Takes an array of selected variables, and a condition map, which is ANDed
711 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
712 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
713 * $obj- >page_id is the ID of the Astronomy article
715 * @todo migrate documentation to phpdocumentor format
717 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
718 $options['LIMIT'] = 1;
719 $res = $this->select( $table, $vars, $conds, $fname, $options );
720 if ( $res === false || !$this->numRows( $res ) ) {
721 return false;
723 $obj = $this->fetchObject( $res );
724 $this->freeResult( $res );
725 return $obj;
730 * Removes most variables from an SQL query and replaces them with X or N for numbers.
731 * It's only slightly flawed. Don't use for anything important.
733 * @param string $sql A SQL Query
734 * @static
736 function generalizeSQL( $sql ) {
737 # This does the same as the regexp below would do, but in such a way
738 # as to avoid crashing php on some large strings.
739 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
741 $sql = str_replace ( "\\\\", '', $sql);
742 $sql = str_replace ( "\\'", '', $sql);
743 $sql = str_replace ( "\\\"", '', $sql);
744 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
745 $sql = preg_replace ('/".*"/s', "'X'", $sql);
747 # All newlines, tabs, etc replaced by single space
748 $sql = preg_replace ( "/\s+/", ' ', $sql);
750 # All numbers => N
751 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
753 return $sql;
757 * Determines whether a field exists in a table
758 * Usually aborts on failure
759 * If errors are explicitly ignored, returns NULL on failure
761 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
762 $table = $this->tableName( $table );
763 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE, $fname );
764 if ( !$res ) {
765 return NULL;
768 $found = false;
770 while ( $row = $this->fetchObject( $res ) ) {
771 if ( $row->Field == $field ) {
772 $found = true;
773 break;
776 return $found;
780 * Determines whether an index exists
781 * Usually aborts on failure
782 * If errors are explicitly ignored, returns NULL on failure
784 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
785 $info = $this->indexInfo( $table, $index, $fname );
786 if ( is_null( $info ) ) {
787 return NULL;
788 } else {
789 return $info !== false;
795 * Get information about an index into an object
796 * Returns false if the index does not exist
798 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
799 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
800 # SHOW INDEX should work for 3.x and up:
801 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
802 $table = $this->tableName( $table );
803 $sql = 'SHOW INDEX FROM '.$table;
804 $res = $this->query( $sql, $fname );
805 if ( !$res ) {
806 return NULL;
809 while ( $row = $this->fetchObject( $res ) ) {
810 if ( $row->Key_name == $index ) {
811 return $row;
814 return false;
818 * Query whether a given table exists
820 function tableExists( $table ) {
821 $table = $this->tableName( $table );
822 $old = $this->ignoreErrors( true );
823 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
824 $this->ignoreErrors( $old );
825 if( $res ) {
826 $this->freeResult( $res );
827 return true;
828 } else {
829 return false;
834 * mysql_fetch_field() wrapper
835 * Returns false if the field doesn't exist
837 * @param $table
838 * @param $field
840 function fieldInfo( $table, $field ) {
841 $table = $this->tableName( $table );
842 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
843 $n = mysql_num_fields( $res );
844 for( $i = 0; $i < $n; $i++ ) {
845 $meta = mysql_fetch_field( $res, $i );
846 if( $field == $meta->name ) {
847 return $meta;
850 return false;
854 * mysql_field_type() wrapper
856 function fieldType( $res, $index ) {
857 return mysql_field_type( $res, $index );
861 * Determines if a given index is unique
863 function indexUnique( $table, $index ) {
864 $indexInfo = $this->indexInfo( $table, $index );
865 if ( !$indexInfo ) {
866 return NULL;
868 return !$indexInfo->Non_unique;
872 * INSERT wrapper, inserts an array into a table
874 * $a may be a single associative array, or an array of these with numeric keys, for
875 * multi-row insert.
877 * Usually aborts on failure
878 * If errors are explicitly ignored, returns success
880 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
881 # No rows to insert, easy just return now
882 if ( !count( $a ) ) {
883 return true;
886 $table = $this->tableName( $table );
887 if ( !is_array( $options ) ) {
888 $options = array( $options );
890 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
891 $multi = true;
892 $keys = array_keys( $a[0] );
893 } else {
894 $multi = false;
895 $keys = array_keys( $a );
898 $sql = 'INSERT ' . implode( ' ', $options ) .
899 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
901 if ( $multi ) {
902 $first = true;
903 foreach ( $a as $row ) {
904 if ( $first ) {
905 $first = false;
906 } else {
907 $sql .= ',';
909 $sql .= '(' . $this->makeList( $row ) . ')';
911 } else {
912 $sql .= '(' . $this->makeList( $a ) . ')';
914 return !!$this->query( $sql, $fname );
918 * UPDATE wrapper, takes a condition array and a SET array
920 function update( $table, $values, $conds, $fname = 'Database::update' ) {
921 $table = $this->tableName( $table );
922 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET );
923 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
924 $this->query( $sql, $fname );
928 * Makes a wfStrencoded list from an array
929 * $mode: LIST_COMMA - comma separated, no field names
930 * LIST_AND - ANDed WHERE clause (without the WHERE)
931 * LIST_SET - comma separated with field names, like a SET clause
932 * LIST_NAMES - comma separated field names
934 function makeList( $a, $mode = LIST_COMMA ) {
935 if ( !is_array( $a ) ) {
936 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
939 $first = true;
940 $list = '';
941 foreach ( $a as $field => $value ) {
942 if ( !$first ) {
943 if ( $mode == LIST_AND ) {
944 $list .= ' AND ';
945 } else {
946 $list .= ',';
948 } else {
949 $first = false;
951 if ( $mode == LIST_AND && is_numeric( $field ) ) {
952 $list .= "($value)";
953 } elseif ( $mode == LIST_AND && is_array ($value) ) {
954 $list .= $field." IN (".$this->makeList($value).") ";
955 } else {
956 if ( $mode == LIST_AND || $mode == LIST_SET ) {
957 $list .= $field.'=';
959 $list .= ($mode==LIST_NAMES?$value:$this->addQuotes( $value ));
962 return $list;
966 * Change the current database
968 function selectDB( $db ) {
969 $this->mDBname = $db;
970 return mysql_select_db( $db, $this->mConn );
974 * Starts a timer which will kill the DB thread after $timeout seconds
976 function startTimer( $timeout ) {
977 global $IP;
978 if( function_exists( 'mysql_thread_id' ) ) {
979 # This will kill the query if it's still running after $timeout seconds.
980 $tid = mysql_thread_id( $this->mConn );
981 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
986 * Stop a timer started by startTimer()
987 * Currently unimplemented.
990 function stopTimer() { }
993 * Format a table name ready for use in constructing an SQL query
995 * This does two important things: it quotes table names which as necessary,
996 * and it adds a table prefix if there is one.
998 * All functions of this object which require a table name call this function
999 * themselves. Pass the canonical name to such functions. This is only needed
1000 * when calling query() directly.
1002 * @param string $name database table name
1004 function tableName( $name ) {
1005 global $wgSharedDB;
1006 # Skip quoted literals
1007 if ( $name{0} != '`' ) {
1008 if ( $this->mTablePrefix !== '' && strpos( '.', $name ) === false ) {
1009 $name = "{$this->mTablePrefix}$name";
1011 if ( isset( $wgSharedDB ) && 'user' == $name ) {
1012 $name = "`$wgSharedDB`.`$name`";
1013 } else {
1014 # Standard quoting
1015 $name = "`$name`";
1018 return $name;
1022 * Fetch a number of table names into an array
1023 * This is handy when you need to construct SQL for joins
1025 * Example:
1026 * extract($dbr->tableNames('user','watchlist'));
1027 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1028 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1030 function tableNames() {
1031 $inArray = func_get_args();
1032 $retVal = array();
1033 foreach ( $inArray as $name ) {
1034 $retVal[$name] = $this->tableName( $name );
1036 return $retVal;
1040 * Wrapper for addslashes()
1041 * @param string $s String to be slashed.
1042 * @return string slashed string.
1044 function strencode( $s ) {
1045 return addslashes( $s );
1049 * If it's a string, adds quotes and backslashes
1050 * Otherwise returns as-is
1052 function addQuotes( $s ) {
1053 if ( is_null( $s ) ) {
1054 return 'NULL';
1055 } else {
1056 # This will also quote numeric values. This should be harmless,
1057 # and protects against weird problems that occur when they really
1058 # _are_ strings such as article titles and string->number->string
1059 # conversion is not 1:1.
1060 return "'" . $this->strencode( $s ) . "'";
1065 * Returns an appropriately quoted sequence value for inserting a new row.
1066 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1067 * subclass will return an integer, and save the value for insertId()
1069 function nextSequenceValue( $seqName ) {
1070 return NULL;
1074 * USE INDEX clause
1075 * PostgreSQL doesn't have them and returns ""
1077 function useIndexClause( $index ) {
1078 return "USE INDEX ($index)";
1082 * REPLACE query wrapper
1083 * PostgreSQL simulates this with a DELETE followed by INSERT
1084 * $row is the row to insert, an associative array
1085 * $uniqueIndexes is an array of indexes. Each element may be either a
1086 * field name or an array of field names
1088 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1089 * However if you do this, you run the risk of encountering errors which wouldn't have
1090 * occurred in MySQL
1092 * @todo migrate comment to phodocumentor format
1094 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1095 $table = $this->tableName( $table );
1097 # Single row case
1098 if ( !is_array( reset( $rows ) ) ) {
1099 $rows = array( $rows );
1102 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1103 $first = true;
1104 foreach ( $rows as $row ) {
1105 if ( $first ) {
1106 $first = false;
1107 } else {
1108 $sql .= ',';
1110 $sql .= '(' . $this->makeList( $row ) . ')';
1112 return $this->query( $sql, $fname );
1116 * DELETE where the condition is a join
1117 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1119 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1120 * join condition matches, set $conds='*'
1122 * DO NOT put the join condition in $conds
1124 * @param string $delTable The table to delete from.
1125 * @param string $joinTable The other table.
1126 * @param string $delVar The variable to join on, in the first table.
1127 * @param string $joinVar The variable to join on, in the second table.
1128 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1130 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1131 if ( !$conds ) {
1132 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1135 $delTable = $this->tableName( $delTable );
1136 $joinTable = $this->tableName( $joinTable );
1137 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1138 if ( $conds != '*' ) {
1139 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1142 return $this->query( $sql, $fname );
1146 * Returns the size of a text field, or -1 for "unlimited"
1148 function textFieldSize( $table, $field ) {
1149 $table = $this->tableName( $table );
1150 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1151 $res = $this->query( $sql, 'Database::textFieldSize' );
1152 $row = $this->fetchObject( $res );
1153 $this->freeResult( $res );
1155 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1156 $size = $m[1];
1157 } else {
1158 $size = -1;
1160 return $size;
1164 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1166 function lowPriorityOption() {
1167 return 'LOW_PRIORITY';
1171 * DELETE query wrapper
1173 * Use $conds == "*" to delete all rows
1175 function delete( $table, $conds, $fname = 'Database::delete' ) {
1176 if ( !$conds ) {
1177 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1179 $table = $this->tableName( $table );
1180 $sql = "DELETE FROM $table";
1181 if ( $conds != '*' ) {
1182 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1184 return $this->query( $sql, $fname );
1188 * INSERT SELECT wrapper
1189 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1190 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1191 * $conds may be "*" to copy the whole table
1192 * srcTable may be an array of tables.
1194 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1195 $destTable = $this->tableName( $destTable );
1196 if( is_array( $srcTable ) ) {
1197 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1198 } else {
1199 $srcTable = $this->tableName( $srcTable );
1201 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1202 ' SELECT ' . implode( ',', $varMap ) .
1203 " FROM $srcTable";
1204 if ( $conds != '*' ) {
1205 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1207 return $this->query( $sql, $fname );
1211 * Construct a LIMIT query with optional offset
1212 * This is used for query pages
1214 function limitResult($limit,$offset) {
1215 return ' LIMIT '.(is_numeric($offset)?"{$offset},":"")."{$limit} ";
1219 * Returns an SQL expression for a simple conditional.
1220 * Uses IF on MySQL.
1222 * @param string $cond SQL expression which will result in a boolean value
1223 * @param string $trueVal SQL expression to return if true
1224 * @param string $falseVal SQL expression to return if false
1225 * @return string SQL fragment
1227 function conditional( $cond, $trueVal, $falseVal ) {
1228 return " IF($cond, $trueVal, $falseVal) ";
1232 * Determines if the last failure was due to a deadlock
1234 function wasDeadlock() {
1235 return $this->lastErrno() == 1213;
1239 * Perform a deadlock-prone transaction.
1241 * This function invokes a callback function to perform a set of write
1242 * queries. If a deadlock occurs during the processing, the transaction
1243 * will be rolled back and the callback function will be called again.
1245 * Usage:
1246 * $dbw->deadlockLoop( callback, ... );
1248 * Extra arguments are passed through to the specified callback function.
1250 * Returns whatever the callback function returned on its successful,
1251 * iteration, or false on error, for example if the retry limit was
1252 * reached.
1254 function deadlockLoop() {
1255 $myFname = 'Database::deadlockLoop';
1257 $this->query( 'BEGIN', $myFname );
1258 $args = func_get_args();
1259 $function = array_shift( $args );
1260 $oldIgnore = $this->ignoreErrors( true );
1261 $tries = DEADLOCK_TRIES;
1262 if ( is_array( $function ) ) {
1263 $fname = $function[0];
1264 } else {
1265 $fname = $function;
1267 do {
1268 $retVal = call_user_func_array( $function, $args );
1269 $error = $this->lastError();
1270 $errno = $this->lastErrno();
1271 $sql = $this->lastQuery();
1273 if ( $errno ) {
1274 if ( $this->wasDeadlock() ) {
1275 # Retry
1276 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1277 } else {
1278 $this->reportQueryError( $error, $errno, $sql, $fname );
1281 } while( $this->wasDeadlock() && --$tries > 0 );
1282 $this->ignoreErrors( $oldIgnore );
1283 if ( $tries <= 0 ) {
1284 $this->query( 'ROLLBACK', $myFname );
1285 $this->reportQueryError( $error, $errno, $sql, $fname );
1286 return false;
1287 } else {
1288 $this->query( 'COMMIT', $myFname );
1289 return $retVal;
1294 * Do a SELECT MASTER_POS_WAIT()
1296 * @param string $file the binlog file
1297 * @param string $pos the binlog position
1298 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1300 function masterPosWait( $file, $pos, $timeout ) {
1301 $fname = 'Database::masterPosWait';
1302 wfProfileIn( $fname );
1305 # Commit any open transactions
1306 $this->immediateCommit();
1308 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1309 $encFile = $this->strencode( $file );
1310 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1311 $res = $this->doQuery( $sql );
1312 if ( $res && $row = $this->fetchRow( $res ) ) {
1313 $this->freeResult( $res );
1314 return $row[0];
1315 } else {
1316 return false;
1321 * Get the position of the master from SHOW SLAVE STATUS
1323 function getSlavePos() {
1324 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1325 $row = $this->fetchObject( $res );
1326 if ( $row ) {
1327 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1328 } else {
1329 return array( false, false );
1334 * Get the position of the master from SHOW MASTER STATUS
1336 function getMasterPos() {
1337 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1338 $row = $this->fetchObject( $res );
1339 if ( $row ) {
1340 return array( $row->File, $row->Position );
1341 } else {
1342 return array( false, false );
1347 * Begin a transaction, or if a transaction has already started, continue it
1349 function begin( $fname = 'Database::begin' ) {
1350 if ( !$this->mTrxLevel ) {
1351 $this->immediateBegin( $fname );
1352 } else {
1353 $this->mTrxLevel++;
1358 * End a transaction, or decrement the nest level if transactions are nested
1360 function commit( $fname = 'Database::commit' ) {
1361 if ( $this->mTrxLevel ) {
1362 $this->mTrxLevel--;
1364 if ( !$this->mTrxLevel ) {
1365 $this->immediateCommit( $fname );
1370 * Rollback a transaction
1372 function rollback( $fname = 'Database::rollback' ) {
1373 $this->query( 'ROLLBACK', $fname );
1374 $this->mTrxLevel = 0;
1378 * Begin a transaction, committing any previously open transaction
1380 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1381 $this->query( 'BEGIN', $fname );
1382 $this->mTrxLevel = 1;
1386 * Commit transaction, if one is open
1388 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1389 $this->query( 'COMMIT', $fname );
1390 $this->mTrxLevel = 0;
1394 * Return MW-style timestamp used for MySQL schema
1396 function timestamp( $ts=0 ) {
1397 return wfTimestamp(TS_MW,$ts);
1401 * Local database timestamp format or null
1403 function timestampOrNull( $ts = null ) {
1404 if( is_null( $ts ) ) {
1405 return null;
1406 } else {
1407 return $this->timestamp( $ts );
1412 * @todo document
1414 function &resultObject( &$result ) {
1415 if( empty( $result ) ) {
1416 return NULL;
1417 } else {
1418 return new ResultWrapper( $this, $result );
1423 * Return aggregated value alias
1425 function aggregateValue ($valuedata,$valuename='value') {
1426 return $valuename;
1430 * @return string wikitext of a link to the server software's web site
1432 function getSoftwareLink() {
1433 return "[http://www.mysql.com/ MySQL]";
1437 * @return string Version information from the database
1439 function getServerVersion() {
1440 return mysql_get_server_info();
1444 * Ping the server and try to reconnect if it there is no connection
1446 function ping() {
1447 return mysql_ping( $this->mConn );
1452 * Database abstraction object for mySQL
1453 * Inherit all methods and properties of Database::Database()
1455 * @package MediaWiki
1456 * @see Database
1458 class DatabaseMysql extends Database {
1459 # Inherit all
1464 * Result wrapper for grabbing data queried by someone else
1466 * @package MediaWiki
1468 class ResultWrapper {
1469 var $db, $result;
1472 * @todo document
1474 function ResultWrapper( $database, $result ) {
1475 $this->db =& $database;
1476 $this->result =& $result;
1480 * @todo document
1482 function numRows() {
1483 return $this->db->numRows( $this->result );
1487 * @todo document
1489 function &fetchObject() {
1490 return $this->db->fetchObject( $this->result );
1494 * @todo document
1496 function &fetchRow() {
1497 return $this->db->fetchRow( $this->result );
1501 * @todo document
1503 function free() {
1504 $this->db->freeResult( $this->result );
1505 unset( $this->result );
1506 unset( $this->db );
1509 function seek( $row ) {
1510 $this->db->dataSeek( $this->result, $row );
1514 #------------------------------------------------------------------------------
1515 # Global functions
1516 #------------------------------------------------------------------------------
1519 * Standard fail function, called by default when a connection cannot be
1520 * established.
1521 * Displays the file cache if possible
1523 function wfEmergencyAbort( &$conn, $error ) {
1524 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1525 global $wgSitename, $wgServer;
1527 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1528 # Hard coding strings instead.
1530 $noconnect = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server. <br />
1531 $1';
1532 $mainpage = 'Main Page';
1533 $searchdisabled = <<<EOT
1534 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1535 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1536 EOT;
1538 $googlesearch = "
1539 <!-- SiteSearch Google -->
1540 <FORM method=GET action=\"http://www.google.com/search\">
1541 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1542 <A HREF=\"http://www.google.com/\">
1543 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1544 border=\"0\" ALT=\"Google\"></A>
1545 </td>
1546 <td>
1547 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1548 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1549 <font size=-1>
1550 <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 />
1551 <input type='hidden' name='ie' value='$2'>
1552 <input type='hidden' name='oe' value='$2'>
1553 </font>
1554 </td></tr></TABLE>
1555 </FORM>
1556 <!-- SiteSearch Google -->";
1557 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1560 if( !headers_sent() ) {
1561 header( 'HTTP/1.0 500 Internal Server Error' );
1562 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1563 /* Don't cache error pages! They cause no end of trouble... */
1564 header( 'Cache-control: none' );
1565 header( 'Pragma: nocache' );
1567 $msg = wfGetSiteNotice();
1568 if($msg == '') {
1569 $msg = str_replace( '$1', $error, $noconnect );
1571 $text = $msg;
1573 if($wgUseFileCache) {
1574 if($wgTitle) {
1575 $t =& $wgTitle;
1576 } else {
1577 if($title) {
1578 $t = Title::newFromURL( $title );
1579 } elseif (@/**/$_REQUEST['search']) {
1580 $search = $_REQUEST['search'];
1581 echo $searchdisabled;
1582 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1583 $wgInputEncoding ), $googlesearch );
1584 wfErrorExit();
1585 } else {
1586 $t = Title::newFromText( $mainpage );
1590 $cache = new CacheManager( $t );
1591 if( $cache->isFileCached() ) {
1592 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1593 $cachederror . "</b></p>\n";
1595 $tag = '<div id="article">';
1596 $text = str_replace(
1597 $tag,
1598 $tag . $msg,
1599 $cache->fetchPageText() );
1603 echo $text;
1604 wfErrorExit();