3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
9 * Depends on the CacheManager
11 require_once( 'CacheManager.php' );
13 /** See Database::makeList() */
14 define( 'LIST_COMMA', 0 );
15 define( 'LIST_AND', 1 );
16 define( 'LIST_SET', 2 );
17 define( 'LIST_NAMES', 3);
18 define( 'LIST_OR', 4);
20 /** Number of times to re-try an operation in case of deadlock */
21 define( 'DEADLOCK_TRIES', 4 );
22 /** Minimum time to wait before retry, in microseconds */
23 define( 'DEADLOCK_DELAY_MIN', 500000 );
24 /** Maximum time to wait before retry */
25 define( 'DEADLOCK_DELAY_MAX', 1500000 );
30 function DBObject($data) {
44 * Database abstraction object
49 #------------------------------------------------------------------------------
51 #------------------------------------------------------------------------------
57 var $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
58 var $mOut, $mOpened = false;
67 #------------------------------------------------------------------------------
69 #------------------------------------------------------------------------------
70 # These optionally set a variable and return the previous state
73 * Fail function, takes a Database as a parameter
74 * Set to false for default, 1 for ignore errors
76 function failFunction( $function = NULL ) {
77 return wfSetVar( $this->mFailFunction
, $function );
81 * Output page, used for reporting errors
82 * FALSE means discard output
84 function &setOutputPage( &$out ) {
89 * Boolean, controls output of large amounts of debug information
91 function debug( $debug = NULL ) {
92 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
96 * Turns buffering of SQL result sets on (true) or off (false).
97 * Default is "on" and it should not be changed without good reasons.
99 function bufferResults( $buffer = NULL ) {
100 if ( is_null( $buffer ) ) {
101 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
103 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
108 * Turns on (false) or off (true) the automatic generation and sending
109 * of a "we're sorry, but there has been a database error" page on
110 * database errors. Default is on (false). When turned off, the
111 * code should use wfLastErrno() and wfLastError() to handle the
112 * situation as appropriate.
114 function ignoreErrors( $ignoreErrors = NULL ) {
115 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
119 * The current depth of nested transactions
120 * @param integer $level
122 function trxLevel( $level = NULL ) {
123 return wfSetVar( $this->mTrxLevel
, $level );
127 * Number of errors logged, only useful when errors are ignored
129 function errorCount( $count = NULL ) {
130 return wfSetVar( $this->mErrorCount
, $count );
136 function lastQuery() { return $this->mLastQuery
; }
137 function isOpen() { return $this->mOpened
; }
140 function setFlag( $flag ) {
141 $this->mFlags |
= $flag;
144 function clearFlag( $flag ) {
145 $this->mFlags
&= ~
$flag;
148 function getFlag( $flag ) {
149 return !!($this->mFlags
& $flag);
152 #------------------------------------------------------------------------------
154 #------------------------------------------------------------------------------
157 * @param string $server database server host
158 * @param string $user database user name
159 * @param string $password database user password
160 * @param string $dbname database name
164 * @param failFunction
166 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
168 function Database( $server = false, $user = false, $password = false, $dbName = false,
169 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
171 global $wgOut, $wgDBprefix, $wgCommandLineMode;
172 # Can't get a reference if it hasn't been set yet
173 if ( !isset( $wgOut ) ) {
176 $this->mOut
=& $wgOut;
178 $this->mFailFunction
= $failFunction;
179 $this->mFlags
= $flags;
181 if ( $this->mFlags
& DBO_DEFAULT
) {
182 if ( $wgCommandLineMode ) {
183 $this->mFlags
&= ~DBO_TRX
;
185 $this->mFlags |
= DBO_TRX
;
190 // Faster read-only access
191 if ( wfReadOnly() ) {
192 $this->mFlags |= DBO_PERSISTENT;
193 $this->mFlags &= ~DBO_TRX;
196 /** Get the default table prefix*/
197 if ( $tablePrefix == 'get from global' ) {
198 $this->mTablePrefix
= $wgDBprefix;
200 $this->mTablePrefix
= $tablePrefix;
204 $this->open( $server, $user, $password, $dbName );
210 * @param failFunction
213 function newFromParams( $server, $user, $password, $dbName,
214 $failFunction = false, $flags = 0 )
216 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
220 * Usually aborts on failure
221 * If the failFunction is set to a non-zero integer, returns success
223 function open( $server, $user, $password, $dbName ) {
224 # Test for missing mysql.so
225 # First try to load it
226 if (!@extension_loaded
('mysql')) {
230 # Otherwise we get a suppressed fatal error, which is very hard to track down
231 if ( !function_exists( 'mysql_connect' ) ) {
232 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
236 $this->mServer
= $server;
237 $this->mUser
= $user;
238 $this->mPassword
= $password;
239 $this->mDBname
= $dbName;
243 if ( $this->mFlags
& DBO_PERSISTENT
) {
244 @/**/$this->mConn
= mysql_pconnect( $server, $user, $password );
246 # Create a new connection...
247 if( version_compare( PHP_VERSION
, '4.2.0', 'ge' ) ) {
248 @/**/$this->mConn
= mysql_connect( $server, $user, $password, true );
250 # On PHP 4.1 the new_link parameter is not available. We cannot
251 # guarantee that we'll actually get a new connection, and this
252 # may cause some operations to fail possibly.
253 @/**/$this->mConn
= mysql_connect( $server, $user, $password );
257 if ( $dbName != '' ) {
258 if ( $this->mConn
!== false ) {
259 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
261 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
264 wfDebug( "DB connection error\n" );
265 wfDebug( "Server: $server, User: $user, Password: " .
266 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
271 $success = (bool)$this->mConn
;
275 $this->reportConnectionError();
277 $this->mOpened
= $success;
283 * Closes a database connection.
284 * if it is open : commits any open transactions
286 * @return bool operation success. true if already closed.
290 $this->mOpened
= false;
291 if ( $this->mConn
) {
292 if ( $this->trxLevel() ) {
293 $this->immediateCommit();
295 return mysql_close( $this->mConn
);
303 * @param string $msg error message ?
305 function reportConnectionError() {
306 if ( $this->mFailFunction
) {
307 if ( !is_int( $this->mFailFunction
) ) {
308 $ff = $this->mFailFunction
;
309 $ff( $this, $this->lastError() );
312 wfEmergencyAbort( $this, $this->lastError() );
317 * Usually aborts on failure
318 * If errors are explicitly ignored, returns success
320 function query( $sql, $fname = '', $tempIgnore = false ) {
321 global $wgProfiling, $wgCommandLineMode;
323 if ( wfReadOnly() ) {
324 # This is a quick check for the most common kinds of write query used
325 # in MediaWiki, to provide extra safety in addition to UI-level checks.
326 # It is not intended to prevent every conceivable write query, or even
327 # to handle such queries gracefully.
328 if ( preg_match( '/^(?:update|insert|replace|delete)/i', $sql ) ) {
329 wfDebug( "Write query from $fname blocked\n" );
334 if ( $wgProfiling ) {
335 # generalizeSQL will probably cut down the query to reasonable
336 # logging size most of the time. The substr is really just a sanity check.
337 $profName = 'query: ' . $fname . ' ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
338 wfProfileIn( 'Database::query' );
339 wfProfileIn( $profName );
342 $this->mLastQuery
= $sql;
344 # Add a comment for easy SHOW PROCESSLIST interpretation
346 $commentedSql = "/* $fname */ $sql";
348 $commentedSql = $sql;
351 # If DBO_TRX is set, start a transaction
352 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() && $sql != 'BEGIN' ) {
356 if ( $this->debug() ) {
357 $sqlx = substr( $commentedSql, 0, 500 );
358 $sqlx = strtr( $sqlx, "\t\n", ' ' );
359 wfDebug( "SQL: $sqlx\n" );
362 # Do the query and handle errors
363 $ret = $this->doQuery( $commentedSql );
365 # Try reconnecting if the connection was lost
366 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
367 # Transaction is gone, like it or not
368 $this->mTrxLevel
= 0;
369 wfDebug( "Connection lost, reconnecting...\n" );
370 if ( $this->ping() ) {
371 wfDebug( "Reconnected\n" );
372 $ret = $this->doQuery( $commentedSql );
374 wfDebug( "Failed\n" );
378 if ( false === $ret ) {
379 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
382 if ( $wgProfiling ) {
383 wfProfileOut( $profName );
384 wfProfileOut( 'Database::query' );
390 * The DBMS-dependent part of query()
391 * @param string $sql SQL query.
393 function doQuery( $sql ) {
394 if( $this->bufferResults() ) {
395 $ret = mysql_query( $sql, $this->mConn
);
397 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
406 * @param string $fname
407 * @param bool $tempIgnore
409 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
410 global $wgCommandLineMode, $wgFullyInitialised;
411 # Ignore errors during error handling to avoid infinite recursion
412 $ignore = $this->ignoreErrors( true );
413 ++
$this->mErrorCount
;
415 if( $ignore ||
$tempIgnore ) {
416 wfDebug("SQL ERROR (ignored): $error\n");
418 $sql1line = str_replace( "\n", "\\n", $sql );
419 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
420 wfDebug("SQL ERROR: " . $error . "\n");
421 if ( $wgCommandLineMode ||
!$this->mOut ||
empty( $wgFullyInitialised ) ) {
422 $message = "A database error has occurred\n" .
424 "Function: $fname\n" .
425 "Error: $errno $error\n";
426 if ( !$wgCommandLineMode ) {
427 $message = nl2br( $message );
429 wfDebugDieBacktrace( $message );
431 // this calls wfAbruptExit()
432 $this->mOut
->databaseError( $fname, $sql, $error, $errno );
435 $this->ignoreErrors( $ignore );
440 * Intended to be compatible with the PEAR::DB wrapper functions.
441 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
443 * ? = scalar value, quoted as necessary
444 * ! = raw SQL bit (a function for instance)
445 * & = filename; reads the file and inserts as a blob
446 * (we don't use this though...)
448 function prepare( $sql, $func = 'Database::prepare' ) {
449 /* MySQL doesn't support prepared statements (yet), so just
450 pack up the query for reference. We'll manually replace
452 return array( 'query' => $sql, 'func' => $func );
455 function freePrepared( $prepared ) {
456 /* No-op for MySQL */
460 * Execute a prepared query with the various arguments
461 * @param string $prepared the prepared sql
462 * @param mixed $args Either an array here, or put scalars as varargs
464 function execute( $prepared, $args = null ) {
465 if( !is_array( $args ) ) {
467 $args = func_get_args();
468 array_shift( $args );
470 $sql = $this->fillPrepared( $prepared['query'], $args );
471 return $this->query( $sql, $prepared['func'] );
475 * Prepare & execute an SQL statement, quoting and inserting arguments
476 * in the appropriate places.
477 * @param string $query
478 * @param string $args ...
480 function safeQuery( $query, $args = null ) {
481 $prepared = $this->prepare( $query, 'Database::safeQuery' );
482 if( !is_array( $args ) ) {
484 $args = func_get_args();
485 array_shift( $args );
487 $retval = $this->execute( $prepared, $args );
488 $this->freePrepared( $prepared );
493 * For faking prepared SQL statements on DBs that don't support
495 * @param string $preparedSql - a 'preparable' SQL statement
496 * @param array $args - array of arguments to fill it with
497 * @return string executable SQL
499 function fillPrepared( $preparedQuery, $args ) {
502 $this->preparedArgs
=& $args;
503 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
504 array( &$this, 'fillPreparedArg' ), $preparedQuery );
508 * preg_callback func for fillPrepared()
509 * The arguments should be in $this->preparedArgs and must not be touched
510 * while we're doing this.
512 * @param array $matches
516 function fillPreparedArg( $matches ) {
517 switch( $matches[1] ) {
518 case '\\?': return '?';
519 case '\\!': return '!';
520 case '\\&': return '&';
522 list( $n, $arg ) = each( $this->preparedArgs
);
523 switch( $matches[1] ) {
524 case '?': return $this->addQuotes( $arg );
525 case '!': return $arg;
527 # return $this->addQuotes( file_get_contents( $arg ) );
528 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
530 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
535 * @param mixed $res A SQL result
538 * Free a result object
540 function freeResult( $res ) {
541 if ( !@/**/mysql_free_result( $res ) ) {
542 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
547 * Fetch the next row from the given result object, in object form
549 function fetchObject( $res ) {
550 @/**/$row = mysql_fetch_object( $res );
551 if( mysql_errno() ) {
552 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
558 * Fetch the next row from the given result object
561 function fetchRow( $res ) {
562 @/**/$row = mysql_fetch_array( $res );
563 if (mysql_errno() ) {
564 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
570 * Get the number of rows in a result object
572 function numRows( $res ) {
573 @/**/$n = mysql_num_rows( $res );
574 if( mysql_errno() ) {
575 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
581 * Get the number of fields in a result object
582 * See documentation for mysql_num_fields()
584 function numFields( $res ) { return mysql_num_fields( $res ); }
587 * Get a field name in a result object
588 * See documentation for mysql_field_name()
590 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
593 * Get the inserted value of an auto-increment row
595 * The value inserted should be fetched from nextSequenceValue()
598 * $id = $dbw->nextSequenceValue('page_page_id_seq');
599 * $dbw->insert('page',array('page_id' => $id));
600 * $id = $dbw->insertId();
602 function insertId() { return mysql_insert_id( $this->mConn
); }
605 * Change the position of the cursor in a result object
606 * See mysql_data_seek()
608 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
611 * Get the last error number
614 function lastErrno() {
615 if ( $this->mConn
) {
616 return mysql_errno( $this->mConn
);
618 return mysql_errno();
623 * Get a description of the last error
624 * See mysql_error() for more details
626 function lastError() {
627 if ( $this->mConn
) {
628 # Even if it's non-zero, it can still be invalid
629 wfSuppressWarnings();
630 $error = mysql_error( $this->mConn
);
632 $error = mysql_error();
636 $error = mysql_error();
639 $error .= ' (' . $this->mServer
. ')';
644 * Get the number of rows affected by the last write query
645 * See mysql_affected_rows() for more details
647 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
648 /**#@-*/ // end of template : @param $result
651 * Simple UPDATE wrapper
652 * Usually aborts on failure
653 * If errors are explicitly ignored, returns success
655 * This function exists for historical reasons, Database::update() has a more standard
656 * calling convention and feature set
658 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
660 $table = $this->tableName( $table );
661 $sql = "UPDATE $table SET $var = '" .
662 $this->strencode( $value ) . "' WHERE ($cond)";
663 return (bool)$this->query( $sql, DB_MASTER
, $fname );
667 * Simple SELECT wrapper, returns a single field, input must be encoded
668 * Usually aborts on failure
669 * If errors are explicitly ignored, returns FALSE on failure
671 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
672 if ( !is_array( $options ) ) {
673 $options = array( $options );
675 $options['LIMIT'] = 1;
677 $res = $this->select( $table, $var, $cond, $fname, $options );
678 if ( $res === false ||
!$this->numRows( $res ) ) {
681 $row = $this->fetchRow( $res );
682 if ( $row !== false ) {
683 $this->freeResult( $res );
691 * Returns an optional USE INDEX clause to go after the table, and a
692 * string to go at the end of the query
696 * @param array $options an associative array of options to be turned into
697 * an SQL query, valid keys are listed in the function.
700 function makeSelectOptions( $options ) {
703 if ( isset( $options['GROUP BY'] ) ) {
704 $tailOpts .= " GROUP BY {$options['GROUP BY']}";
706 if ( isset( $options['ORDER BY'] ) ) {
707 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
709 if (isset($options['LIMIT'])) {
710 $tailOpts .= $this->limitResult('', $options['LIMIT'],
711 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
713 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
714 $tailOpts .= ' FOR UPDATE';
717 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
718 $tailOpts .= ' LOCK IN SHARE MODE';
721 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
722 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
726 return array( $useIndex, $tailOpts );
732 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
734 if( is_array( $vars ) ) {
735 $vars = implode( ',', $vars );
737 if( !is_array( $options ) ) {
738 $options = array( $options );
740 if( is_array( $table ) ) {
741 if ( @is_array
( $options['USE INDEX'] ) )
742 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
744 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
745 } elseif ($table!='') {
746 $from = ' FROM ' . $this->tableName( $table );
751 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
753 if( !empty( $conds ) ) {
754 if ( is_array( $conds ) ) {
755 $conds = $this->makeList( $conds, LIST_AND
);
757 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
759 $sql = "SELECT $vars $from $useIndex $tailOpts";
762 return $this->query( $sql, $fname );
766 * Single row SELECT wrapper
767 * Aborts or returns FALSE on error
769 * $vars: the selected variables
770 * $conds: a condition map, terms are ANDed together.
771 * Items with numeric keys are taken to be literal conditions
772 * Takes an array of selected variables, and a condition map, which is ANDed
773 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
774 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
775 * $obj- >page_id is the ID of the Astronomy article
777 * @todo migrate documentation to phpdocumentor format
779 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
780 $options['LIMIT'] = 1;
781 $res = $this->select( $table, $vars, $conds, $fname, $options );
782 if ( $res === false )
784 if ( !$this->numRows($res) ) {
785 $this->freeResult($res);
788 $obj = $this->fetchObject( $res );
789 $this->freeResult( $res );
795 * Removes most variables from an SQL query and replaces them with X or N for numbers.
796 * It's only slightly flawed. Don't use for anything important.
798 * @param string $sql A SQL Query
801 function generalizeSQL( $sql ) {
802 # This does the same as the regexp below would do, but in such a way
803 # as to avoid crashing php on some large strings.
804 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
806 $sql = str_replace ( "\\\\", '', $sql);
807 $sql = str_replace ( "\\'", '', $sql);
808 $sql = str_replace ( "\\\"", '', $sql);
809 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
810 $sql = preg_replace ('/".*"/s', "'X'", $sql);
812 # All newlines, tabs, etc replaced by single space
813 $sql = preg_replace ( "/\s+/", ' ', $sql);
816 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
822 * Determines whether a field exists in a table
823 * Usually aborts on failure
824 * If errors are explicitly ignored, returns NULL on failure
826 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
827 $table = $this->tableName( $table );
828 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE
, $fname );
835 while ( $row = $this->fetchObject( $res ) ) {
836 if ( $row->Field
== $field ) {
845 * Determines whether an index exists
846 * Usually aborts on failure
847 * If errors are explicitly ignored, returns NULL on failure
849 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
850 $info = $this->indexInfo( $table, $index, $fname );
851 if ( is_null( $info ) ) {
854 return $info !== false;
860 * Get information about an index into an object
861 * Returns false if the index does not exist
863 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
864 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
865 # SHOW INDEX should work for 3.x and up:
866 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
867 $table = $this->tableName( $table );
868 $sql = 'SHOW INDEX FROM '.$table;
869 $res = $this->query( $sql, $fname );
874 while ( $row = $this->fetchObject( $res ) ) {
875 if ( $row->Key_name
== $index ) {
883 * Query whether a given table exists
885 function tableExists( $table ) {
886 $table = $this->tableName( $table );
887 $old = $this->ignoreErrors( true );
888 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
889 $this->ignoreErrors( $old );
891 $this->freeResult( $res );
899 * mysql_fetch_field() wrapper
900 * Returns false if the field doesn't exist
905 function fieldInfo( $table, $field ) {
906 $table = $this->tableName( $table );
907 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
908 $n = mysql_num_fields( $res );
909 for( $i = 0; $i < $n; $i++
) {
910 $meta = mysql_fetch_field( $res, $i );
911 if( $field == $meta->name
) {
919 * mysql_field_type() wrapper
921 function fieldType( $res, $index ) {
922 return mysql_field_type( $res, $index );
926 * Determines if a given index is unique
928 function indexUnique( $table, $index ) {
929 $indexInfo = $this->indexInfo( $table, $index );
933 return !$indexInfo->Non_unique
;
937 * INSERT wrapper, inserts an array into a table
939 * $a may be a single associative array, or an array of these with numeric keys, for
942 * Usually aborts on failure
943 * If errors are explicitly ignored, returns success
945 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
946 # No rows to insert, easy just return now
947 if ( !count( $a ) ) {
951 $table = $this->tableName( $table );
952 if ( !is_array( $options ) ) {
953 $options = array( $options );
955 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
957 $keys = array_keys( $a[0] );
960 $keys = array_keys( $a );
963 $sql = 'INSERT ' . implode( ' ', $options ) .
964 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
968 foreach ( $a as $row ) {
974 $sql .= '(' . $this->makeList( $row ) . ')';
977 $sql .= '(' . $this->makeList( $a ) . ')';
979 return (bool)$this->query( $sql, $fname );
983 * Make UPDATE options for the Database::update function
986 * @param array $options The options passed to Database::update
989 function makeUpdateOptions( $options ) {
990 if( !is_array( $options ) ) {
991 $options = array( $options );
994 if ( in_array( 'LOW_PRIORITY', $options ) )
995 $opts[] = $this->lowPriorityOption();
996 if ( in_array( 'IGNORE', $options ) )
998 return implode(' ', $opts);
1002 * UPDATE wrapper, takes a condition array and a SET array
1004 * @param string $table The table to UPDATE
1005 * @param array $values An array of values to SET
1006 * @param array $conds An array of conditions (WHERE)
1007 * @param string $fname The Class::Function calling this function
1009 * @param array $options An array of UPDATE options, can be one or
1010 * more of IGNORE, LOW_PRIORITY
1012 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1013 $table = $this->tableName( $table );
1014 $opts = $this->makeUpdateOptions( $options );
1015 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1016 if ( $conds != '*' ) {
1017 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1019 $this->query( $sql, $fname );
1023 * Makes a wfStrencoded list from an array
1024 * $mode: LIST_COMMA - comma separated, no field names
1025 * LIST_AND - ANDed WHERE clause (without the WHERE)
1026 * LIST_SET - comma separated with field names, like a SET clause
1027 * LIST_NAMES - comma separated field names
1029 function makeList( $a, $mode = LIST_COMMA
) {
1030 if ( !is_array( $a ) ) {
1031 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
1036 foreach ( $a as $field => $value ) {
1038 if ( $mode == LIST_AND
) {
1040 } elseif($mode == LIST_OR
) {
1048 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1049 $list .= "($value)";
1050 } elseif ( $mode == LIST_AND
&& is_array ($value) ) {
1051 $list .= $field." IN (".$this->makeList($value).") ";
1053 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1054 $list .= "$field = ";
1056 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1063 * Change the current database
1065 function selectDB( $db ) {
1066 $this->mDBname
= $db;
1067 return mysql_select_db( $db, $this->mConn
);
1071 * Starts a timer which will kill the DB thread after $timeout seconds
1073 function startTimer( $timeout ) {
1075 if( function_exists( 'mysql_thread_id' ) ) {
1076 # This will kill the query if it's still running after $timeout seconds.
1077 $tid = mysql_thread_id( $this->mConn
);
1078 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
1083 * Stop a timer started by startTimer()
1084 * Currently unimplemented.
1087 function stopTimer() { }
1090 * Format a table name ready for use in constructing an SQL query
1092 * This does two important things: it quotes table names which as necessary,
1093 * and it adds a table prefix if there is one.
1095 * All functions of this object which require a table name call this function
1096 * themselves. Pass the canonical name to such functions. This is only needed
1097 * when calling query() directly.
1099 * @param string $name database table name
1101 function tableName( $name ) {
1103 # Skip quoted literals
1104 if ( $name{0} != '`' ) {
1105 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
1106 $name = "{$this->mTablePrefix}$name";
1108 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1109 $name = "`$wgSharedDB`.`$name`";
1119 * Fetch a number of table names into an array
1120 * This is handy when you need to construct SQL for joins
1123 * extract($dbr->tableNames('user','watchlist'));
1124 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1125 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1127 function tableNames() {
1128 $inArray = func_get_args();
1130 foreach ( $inArray as $name ) {
1131 $retVal[$name] = $this->tableName( $name );
1139 function tableNamesWithUseIndex( $tables, $use_index ) {
1142 foreach ( $tables as $table )
1143 if ( @$use_index[$table] !== null )
1144 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1146 $ret[] = $this->tableName( $table );
1148 return implode( ',', $ret );
1152 * Wrapper for addslashes()
1153 * @param string $s String to be slashed.
1154 * @return string slashed string.
1156 function strencode( $s ) {
1157 return addslashes( $s );
1161 * If it's a string, adds quotes and backslashes
1162 * Otherwise returns as-is
1164 function addQuotes( $s ) {
1165 if ( is_null( $s ) ) {
1168 # This will also quote numeric values. This should be harmless,
1169 # and protects against weird problems that occur when they really
1170 # _are_ strings such as article titles and string->number->string
1171 # conversion is not 1:1.
1172 return "'" . $this->strencode( $s ) . "'";
1177 * Escape string for safe LIKE usage
1179 function escapeLike( $s ) {
1180 $s=$this->strencode( $s );
1181 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1186 * Returns an appropriately quoted sequence value for inserting a new row.
1187 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1188 * subclass will return an integer, and save the value for insertId()
1190 function nextSequenceValue( $seqName ) {
1196 * PostgreSQL doesn't have them and returns ""
1198 function useIndexClause( $index ) {
1199 return "FORCE INDEX ($index)";
1203 * REPLACE query wrapper
1204 * PostgreSQL simulates this with a DELETE followed by INSERT
1205 * $row is the row to insert, an associative array
1206 * $uniqueIndexes is an array of indexes. Each element may be either a
1207 * field name or an array of field names
1209 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1210 * However if you do this, you run the risk of encountering errors which wouldn't have
1213 * @todo migrate comment to phodocumentor format
1215 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1216 $table = $this->tableName( $table );
1219 if ( !is_array( reset( $rows ) ) ) {
1220 $rows = array( $rows );
1223 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1225 foreach ( $rows as $row ) {
1231 $sql .= '(' . $this->makeList( $row ) . ')';
1233 return $this->query( $sql, $fname );
1237 * DELETE where the condition is a join
1238 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1240 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1241 * join condition matches, set $conds='*'
1243 * DO NOT put the join condition in $conds
1245 * @param string $delTable The table to delete from.
1246 * @param string $joinTable The other table.
1247 * @param string $delVar The variable to join on, in the first table.
1248 * @param string $joinVar The variable to join on, in the second table.
1249 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1251 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1253 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1256 $delTable = $this->tableName( $delTable );
1257 $joinTable = $this->tableName( $joinTable );
1258 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1259 if ( $conds != '*' ) {
1260 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1263 return $this->query( $sql, $fname );
1267 * Returns the size of a text field, or -1 for "unlimited"
1269 function textFieldSize( $table, $field ) {
1270 $table = $this->tableName( $table );
1271 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1272 $res = $this->query( $sql, 'Database::textFieldSize' );
1273 $row = $this->fetchObject( $res );
1274 $this->freeResult( $res );
1276 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
1285 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1287 function lowPriorityOption() {
1288 return 'LOW_PRIORITY';
1292 * DELETE query wrapper
1294 * Use $conds == "*" to delete all rows
1296 function delete( $table, $conds, $fname = 'Database::delete' ) {
1298 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1300 $table = $this->tableName( $table );
1301 $sql = "DELETE FROM $table";
1302 if ( $conds != '*' ) {
1303 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1305 return $this->query( $sql, $fname );
1309 * INSERT SELECT wrapper
1310 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1311 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1312 * $conds may be "*" to copy the whole table
1313 * srcTable may be an array of tables.
1315 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1316 $destTable = $this->tableName( $destTable );
1317 if( is_array( $srcTable ) ) {
1318 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1320 $srcTable = $this->tableName( $srcTable );
1322 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1323 ' SELECT ' . implode( ',', $varMap ) .
1325 if ( $conds != '*' ) {
1326 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1328 return $this->query( $sql, $fname );
1332 * Construct a LIMIT query with optional offset
1333 * This is used for query pages
1334 * $sql string SQL query we will append the limit too
1335 * $limit integer the SQL limit
1336 * $offset integer the SQL offset (default false)
1338 function limitResult($sql, $limit, $offset=false) {
1339 return " $sql LIMIT ".((is_numeric($offset) && $offset != 0)?
"{$offset},":"")."{$limit} ";
1341 function limitResultForUpdate($sql, $num) {
1342 return $this->limitResult($sql, $num, 0);
1346 * Returns an SQL expression for a simple conditional.
1349 * @param string $cond SQL expression which will result in a boolean value
1350 * @param string $trueVal SQL expression to return if true
1351 * @param string $falseVal SQL expression to return if false
1352 * @return string SQL fragment
1354 function conditional( $cond, $trueVal, $falseVal ) {
1355 return " IF($cond, $trueVal, $falseVal) ";
1359 * Determines if the last failure was due to a deadlock
1361 function wasDeadlock() {
1362 return $this->lastErrno() == 1213;
1366 * Perform a deadlock-prone transaction.
1368 * This function invokes a callback function to perform a set of write
1369 * queries. If a deadlock occurs during the processing, the transaction
1370 * will be rolled back and the callback function will be called again.
1373 * $dbw->deadlockLoop( callback, ... );
1375 * Extra arguments are passed through to the specified callback function.
1377 * Returns whatever the callback function returned on its successful,
1378 * iteration, or false on error, for example if the retry limit was
1381 function deadlockLoop() {
1382 $myFname = 'Database::deadlockLoop';
1385 $args = func_get_args();
1386 $function = array_shift( $args );
1387 $oldIgnore = $this->ignoreErrors( true );
1388 $tries = DEADLOCK_TRIES
;
1389 if ( is_array( $function ) ) {
1390 $fname = $function[0];
1395 $retVal = call_user_func_array( $function, $args );
1396 $error = $this->lastError();
1397 $errno = $this->lastErrno();
1398 $sql = $this->lastQuery();
1401 if ( $this->wasDeadlock() ) {
1403 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1405 $this->reportQueryError( $error, $errno, $sql, $fname );
1408 } while( $this->wasDeadlock() && --$tries > 0 );
1409 $this->ignoreErrors( $oldIgnore );
1410 if ( $tries <= 0 ) {
1411 $this->query( 'ROLLBACK', $myFname );
1412 $this->reportQueryError( $error, $errno, $sql, $fname );
1415 $this->query( 'COMMIT', $myFname );
1421 * Do a SELECT MASTER_POS_WAIT()
1423 * @param string $file the binlog file
1424 * @param string $pos the binlog position
1425 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1427 function masterPosWait( $file, $pos, $timeout ) {
1428 $fname = 'Database::masterPosWait';
1429 wfProfileIn( $fname );
1432 # Commit any open transactions
1433 $this->immediateCommit();
1435 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1436 $encFile = $this->strencode( $file );
1437 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1438 $res = $this->doQuery( $sql );
1439 if ( $res && $row = $this->fetchRow( $res ) ) {
1440 $this->freeResult( $res );
1441 wfProfileOut( $fname );
1444 wfProfileOut( $fname );
1450 * Get the position of the master from SHOW SLAVE STATUS
1452 function getSlavePos() {
1453 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1454 $row = $this->fetchObject( $res );
1456 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1458 return array( false, false );
1463 * Get the position of the master from SHOW MASTER STATUS
1465 function getMasterPos() {
1466 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1467 $row = $this->fetchObject( $res );
1469 return array( $row->File
, $row->Position
);
1471 return array( false, false );
1476 * Begin a transaction, or if a transaction has already started, continue it
1478 function begin( $fname = 'Database::begin' ) {
1479 if ( !$this->mTrxLevel
) {
1480 $this->immediateBegin( $fname );
1487 * End a transaction, or decrement the nest level if transactions are nested
1489 function commit( $fname = 'Database::commit' ) {
1490 if ( $this->mTrxLevel
) {
1493 if ( !$this->mTrxLevel
) {
1494 $this->immediateCommit( $fname );
1499 * Rollback a transaction
1501 function rollback( $fname = 'Database::rollback' ) {
1502 $this->query( 'ROLLBACK', $fname );
1503 $this->mTrxLevel
= 0;
1507 * Begin a transaction, committing any previously open transaction
1509 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1510 $this->query( 'BEGIN', $fname );
1511 $this->mTrxLevel
= 1;
1515 * Commit transaction, if one is open
1517 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1518 $this->query( 'COMMIT', $fname );
1519 $this->mTrxLevel
= 0;
1523 * Return MW-style timestamp used for MySQL schema
1525 function timestamp( $ts=0 ) {
1526 return wfTimestamp(TS_MW
,$ts);
1530 * Local database timestamp format or null
1532 function timestampOrNull( $ts = null ) {
1533 if( is_null( $ts ) ) {
1536 return $this->timestamp( $ts );
1543 function resultObject( $result ) {
1544 if( empty( $result ) ) {
1547 return new ResultWrapper( $this, $result );
1552 * Return aggregated value alias
1554 function aggregateValue ($valuedata,$valuename='value') {
1559 * @return string wikitext of a link to the server software's web site
1561 function getSoftwareLink() {
1562 return "[http://www.mysql.com/ MySQL]";
1566 * @return string Version information from the database
1568 function getServerVersion() {
1569 return mysql_get_server_info();
1573 * Ping the server and try to reconnect if it there is no connection
1576 if( function_exists( 'mysql_ping' ) ) {
1577 return mysql_ping( $this->mConn
);
1579 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1586 * At the moment, this will only work if the DB user has the PROCESS privilege
1589 $res = $this->query( 'SHOW PROCESSLIST' );
1590 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1591 # dubious, but unfortunately there's no easy rigorous way
1593 while ( $row = $this->fetchObject( $res ) ) {
1594 if ( $row->User
== 'system user' ) {
1595 if ( ++
$slaveThreads == 2 ) {
1596 # This is it, return the time
1605 * Get status information from SHOW STATUS in an associative array
1607 function getStatus() {
1608 $res = $this->query( 'SHOW STATUS' );
1610 while ( $row = $this->fetchObject( $res ) ) {
1611 $status[$row->Variable_name
] = $row->Value
;
1617 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1619 function maxListLen() {
1623 function encodeBlob($b) {
1627 function notNullTimestamp() {
1630 function isNullTimestamp() {
1636 * Database abstraction object for mySQL
1637 * Inherit all methods and properties of Database::Database()
1639 * @package MediaWiki
1642 class DatabaseMysql
extends Database
{
1648 * Result wrapper for grabbing data queried by someone else
1650 * @package MediaWiki
1652 class ResultWrapper
{
1658 function ResultWrapper( $database, $result ) {
1659 $this->db
=& $database;
1660 $this->result
=& $result;
1666 function numRows() {
1667 return $this->db
->numRows( $this->result
);
1673 function fetchObject() {
1674 return $this->db
->fetchObject( $this->result
);
1680 function &fetchRow() {
1681 return $this->db
->fetchRow( $this->result
);
1688 $this->db
->freeResult( $this->result
);
1689 unset( $this->result
);
1693 function seek( $row ) {
1694 $this->db
->dataSeek( $this->result
, $row );
1698 #------------------------------------------------------------------------------
1700 #------------------------------------------------------------------------------
1703 * Standard fail function, called by default when a connection cannot be
1705 * Displays the file cache if possible
1707 function wfEmergencyAbort( &$conn, $error ) {
1708 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1709 global $wgSitename, $wgServer, $wgMessageCache, $wgLogo;
1711 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1712 # Hard coding strings instead.
1714 $noconnect = "<h1><img src='$wgLogo' style='float:left;margin-right:1em' alt=''>$wgSitename is currently offline</h1><p><strong>Sorry! This site is experiencing technical difficulties.</strong></p><p><small>(Can't contact the database server: $1)</small></p>";
1715 $mainpage = 'Main Page';
1716 $searchdisabled = <<<EOT
1717 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1718 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1722 <!-- SiteSearch Google -->
1723 <FORM method=GET action=\"http://www.google.com/search\">
1724 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1725 <A HREF=\"http://www.google.com/\">
1726 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1727 border=\"0\" ALT=\"Google\"></A>
1730 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1731 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1733 <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 />
1734 <input type='hidden' name='ie' value='$2'>
1735 <input type='hidden' name='oe' value='$2'>
1739 <!-- SiteSearch Google -->";
1740 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1743 if( !headers_sent() ) {
1744 header( 'HTTP/1.0 500 Internal Server Error' );
1745 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1746 /* Don't cache error pages! They cause no end of trouble... */
1747 header( 'Cache-control: none' );
1748 header( 'Pragma: nocache' );
1751 # No database access
1752 if ( is_object( $wgMessageCache ) ) {
1753 $wgMessageCache->disable();
1756 $msg = wfGetSiteNotice();
1758 $msg = str_replace( '$1', $error, $noconnect );
1762 if($wgUseFileCache) {
1767 $t = Title
::newFromURL( $title );
1768 } elseif (@/**/$_REQUEST['search']) {
1769 $search = $_REQUEST['search'];
1770 echo $searchdisabled;
1771 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1772 $wgInputEncoding ), $googlesearch );
1775 $t = Title
::newFromText( $mainpage );
1779 $cache = new CacheManager( $t );
1780 if( $cache->isFileCached() ) {
1781 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1782 $cachederror . "</b></p>\n";
1784 $tag = '<div id="article">';
1785 $text = str_replace(
1788 $cache->fetchPageText() );