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();
280 // Tell the server we're communicating with it in UTF-8.
281 // This may engage various charset conversions.
282 $this->query( 'SET NAMES utf8' );
285 $this->mOpened
= $success;
291 * Closes a database connection.
292 * if it is open : commits any open transactions
294 * @return bool operation success. true if already closed.
298 $this->mOpened
= false;
299 if ( $this->mConn
) {
300 if ( $this->trxLevel() ) {
301 $this->immediateCommit();
303 return mysql_close( $this->mConn
);
311 * @param string $msg error message ?
313 function reportConnectionError() {
314 if ( $this->mFailFunction
) {
315 if ( !is_int( $this->mFailFunction
) ) {
316 $ff = $this->mFailFunction
;
317 $ff( $this, $this->lastError() );
320 wfEmergencyAbort( $this, $this->lastError() );
325 * Usually aborts on failure
326 * If errors are explicitly ignored, returns success
328 function query( $sql, $fname = '', $tempIgnore = false ) {
329 global $wgProfiling, $wgCommandLineMode;
331 if ( wfReadOnly() ) {
332 # This is a quick check for the most common kinds of write query used
333 # in MediaWiki, to provide extra safety in addition to UI-level checks.
334 # It is not intended to prevent every conceivable write query, or even
335 # to handle such queries gracefully.
336 if ( preg_match( '/^(?:update|insert|replace|delete)/i', $sql ) ) {
337 wfDebug( "Write query from $fname blocked\n" );
342 if ( $wgProfiling ) {
343 # generalizeSQL will probably cut down the query to reasonable
344 # logging size most of the time. The substr is really just a sanity check.
346 # Who's been wasting my precious column space? -- TS
347 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
348 $profName = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
350 wfProfileIn( 'Database::query' );
351 wfProfileIn( $profName );
354 $this->mLastQuery
= $sql;
356 # Add a comment for easy SHOW PROCESSLIST interpretation
358 $commentedSql = "/* $fname */ $sql";
360 $commentedSql = $sql;
363 # If DBO_TRX is set, start a transaction
364 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() && $sql != 'BEGIN' ) {
368 if ( $this->debug() ) {
369 $sqlx = substr( $commentedSql, 0, 500 );
370 $sqlx = strtr( $sqlx, "\t\n", ' ' );
371 wfDebug( "SQL: $sqlx\n" );
374 # Do the query and handle errors
375 $ret = $this->doQuery( $commentedSql );
377 # Try reconnecting if the connection was lost
378 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
379 # Transaction is gone, like it or not
380 $this->mTrxLevel
= 0;
381 wfDebug( "Connection lost, reconnecting...\n" );
382 if ( $this->ping() ) {
383 wfDebug( "Reconnected\n" );
384 $ret = $this->doQuery( $commentedSql );
386 wfDebug( "Failed\n" );
390 if ( false === $ret ) {
391 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
394 if ( $wgProfiling ) {
395 wfProfileOut( $profName );
396 wfProfileOut( 'Database::query' );
402 * The DBMS-dependent part of query()
403 * @param string $sql SQL query.
405 function doQuery( $sql ) {
406 if( $this->bufferResults() ) {
407 $ret = mysql_query( $sql, $this->mConn
);
409 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
418 * @param string $fname
419 * @param bool $tempIgnore
421 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
422 global $wgCommandLineMode, $wgFullyInitialised;
423 # Ignore errors during error handling to avoid infinite recursion
424 $ignore = $this->ignoreErrors( true );
425 ++
$this->mErrorCount
;
427 if( $ignore ||
$tempIgnore ) {
428 wfDebug("SQL ERROR (ignored): $error\n");
430 $sql1line = str_replace( "\n", "\\n", $sql );
431 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
432 wfDebug("SQL ERROR: " . $error . "\n");
433 if ( $wgCommandLineMode ||
!$this->mOut ||
empty( $wgFullyInitialised ) ) {
434 $message = "A database error has occurred\n" .
436 "Function: $fname\n" .
437 "Error: $errno $error\n";
438 if ( !$wgCommandLineMode ) {
439 $message = nl2br( $message );
441 wfDebugDieBacktrace( $message );
443 // this calls wfAbruptExit()
444 $this->mOut
->databaseError( $fname, $sql, $error, $errno );
447 $this->ignoreErrors( $ignore );
452 * Intended to be compatible with the PEAR::DB wrapper functions.
453 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
455 * ? = scalar value, quoted as necessary
456 * ! = raw SQL bit (a function for instance)
457 * & = filename; reads the file and inserts as a blob
458 * (we don't use this though...)
460 function prepare( $sql, $func = 'Database::prepare' ) {
461 /* MySQL doesn't support prepared statements (yet), so just
462 pack up the query for reference. We'll manually replace
464 return array( 'query' => $sql, 'func' => $func );
467 function freePrepared( $prepared ) {
468 /* No-op for MySQL */
472 * Execute a prepared query with the various arguments
473 * @param string $prepared the prepared sql
474 * @param mixed $args Either an array here, or put scalars as varargs
476 function execute( $prepared, $args = null ) {
477 if( !is_array( $args ) ) {
479 $args = func_get_args();
480 array_shift( $args );
482 $sql = $this->fillPrepared( $prepared['query'], $args );
483 return $this->query( $sql, $prepared['func'] );
487 * Prepare & execute an SQL statement, quoting and inserting arguments
488 * in the appropriate places.
489 * @param string $query
490 * @param string $args ...
492 function safeQuery( $query, $args = null ) {
493 $prepared = $this->prepare( $query, 'Database::safeQuery' );
494 if( !is_array( $args ) ) {
496 $args = func_get_args();
497 array_shift( $args );
499 $retval = $this->execute( $prepared, $args );
500 $this->freePrepared( $prepared );
505 * For faking prepared SQL statements on DBs that don't support
507 * @param string $preparedSql - a 'preparable' SQL statement
508 * @param array $args - array of arguments to fill it with
509 * @return string executable SQL
511 function fillPrepared( $preparedQuery, $args ) {
514 $this->preparedArgs
=& $args;
515 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
516 array( &$this, 'fillPreparedArg' ), $preparedQuery );
520 * preg_callback func for fillPrepared()
521 * The arguments should be in $this->preparedArgs and must not be touched
522 * while we're doing this.
524 * @param array $matches
528 function fillPreparedArg( $matches ) {
529 switch( $matches[1] ) {
530 case '\\?': return '?';
531 case '\\!': return '!';
532 case '\\&': return '&';
534 list( $n, $arg ) = each( $this->preparedArgs
);
535 switch( $matches[1] ) {
536 case '?': return $this->addQuotes( $arg );
537 case '!': return $arg;
539 # return $this->addQuotes( file_get_contents( $arg ) );
540 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
542 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
547 * @param mixed $res A SQL result
550 * Free a result object
552 function freeResult( $res ) {
553 if ( !@/**/mysql_free_result( $res ) ) {
554 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
559 * Fetch the next row from the given result object, in object form
561 function fetchObject( $res ) {
562 @/**/$row = mysql_fetch_object( $res );
563 if( mysql_errno() ) {
564 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
570 * Fetch the next row from the given result object
573 function fetchRow( $res ) {
574 @/**/$row = mysql_fetch_array( $res );
575 if (mysql_errno() ) {
576 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
582 * Get the number of rows in a result object
584 function numRows( $res ) {
585 @/**/$n = mysql_num_rows( $res );
586 if( mysql_errno() ) {
587 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
593 * Get the number of fields in a result object
594 * See documentation for mysql_num_fields()
596 function numFields( $res ) { return mysql_num_fields( $res ); }
599 * Get a field name in a result object
600 * See documentation for mysql_field_name()
602 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
605 * Get the inserted value of an auto-increment row
607 * The value inserted should be fetched from nextSequenceValue()
610 * $id = $dbw->nextSequenceValue('page_page_id_seq');
611 * $dbw->insert('page',array('page_id' => $id));
612 * $id = $dbw->insertId();
614 function insertId() { return mysql_insert_id( $this->mConn
); }
617 * Change the position of the cursor in a result object
618 * See mysql_data_seek()
620 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
623 * Get the last error number
626 function lastErrno() {
627 if ( $this->mConn
) {
628 return mysql_errno( $this->mConn
);
630 return mysql_errno();
635 * Get a description of the last error
636 * See mysql_error() for more details
638 function lastError() {
639 if ( $this->mConn
) {
640 # Even if it's non-zero, it can still be invalid
641 wfSuppressWarnings();
642 $error = mysql_error( $this->mConn
);
644 $error = mysql_error();
648 $error = mysql_error();
651 $error .= ' (' . $this->mServer
. ')';
656 * Get the number of rows affected by the last write query
657 * See mysql_affected_rows() for more details
659 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
660 /**#@-*/ // end of template : @param $result
663 * Simple UPDATE wrapper
664 * Usually aborts on failure
665 * If errors are explicitly ignored, returns success
667 * This function exists for historical reasons, Database::update() has a more standard
668 * calling convention and feature set
670 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
672 $table = $this->tableName( $table );
673 $sql = "UPDATE $table SET $var = '" .
674 $this->strencode( $value ) . "' WHERE ($cond)";
675 return (bool)$this->query( $sql, DB_MASTER
, $fname );
679 * Simple SELECT wrapper, returns a single field, input must be encoded
680 * Usually aborts on failure
681 * If errors are explicitly ignored, returns FALSE on failure
683 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
684 if ( !is_array( $options ) ) {
685 $options = array( $options );
687 $options['LIMIT'] = 1;
689 $res = $this->select( $table, $var, $cond, $fname, $options );
690 if ( $res === false ||
!$this->numRows( $res ) ) {
693 $row = $this->fetchRow( $res );
694 if ( $row !== false ) {
695 $this->freeResult( $res );
703 * Returns an optional USE INDEX clause to go after the table, and a
704 * string to go at the end of the query
708 * @param array $options an associative array of options to be turned into
709 * an SQL query, valid keys are listed in the function.
712 function makeSelectOptions( $options ) {
715 if ( isset( $options['GROUP BY'] ) ) {
716 $tailOpts .= " GROUP BY {$options['GROUP BY']}";
718 if ( isset( $options['ORDER BY'] ) ) {
719 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
721 if (isset($options['LIMIT'])) {
722 $tailOpts .= $this->limitResult('', $options['LIMIT'],
723 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
725 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
726 $tailOpts .= ' FOR UPDATE';
729 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
730 $tailOpts .= ' LOCK IN SHARE MODE';
733 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
734 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
738 return array( $useIndex, $tailOpts );
744 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
746 if( is_array( $vars ) ) {
747 $vars = implode( ',', $vars );
749 if( !is_array( $options ) ) {
750 $options = array( $options );
752 if( is_array( $table ) ) {
753 if ( @is_array
( $options['USE INDEX'] ) )
754 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
756 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
757 } elseif ($table!='') {
758 $from = ' FROM ' . $this->tableName( $table );
763 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
765 if( !empty( $conds ) ) {
766 if ( is_array( $conds ) ) {
767 $conds = $this->makeList( $conds, LIST_AND
);
769 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
771 $sql = "SELECT $vars $from $useIndex $tailOpts";
774 return $this->query( $sql, $fname );
778 * Single row SELECT wrapper
779 * Aborts or returns FALSE on error
781 * $vars: the selected variables
782 * $conds: a condition map, terms are ANDed together.
783 * Items with numeric keys are taken to be literal conditions
784 * Takes an array of selected variables, and a condition map, which is ANDed
785 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
786 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
787 * $obj- >page_id is the ID of the Astronomy article
789 * @todo migrate documentation to phpdocumentor format
791 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
792 $options['LIMIT'] = 1;
793 $res = $this->select( $table, $vars, $conds, $fname, $options );
794 if ( $res === false )
796 if ( !$this->numRows($res) ) {
797 $this->freeResult($res);
800 $obj = $this->fetchObject( $res );
801 $this->freeResult( $res );
807 * Removes most variables from an SQL query and replaces them with X or N for numbers.
808 * It's only slightly flawed. Don't use for anything important.
810 * @param string $sql A SQL Query
813 function generalizeSQL( $sql ) {
814 # This does the same as the regexp below would do, but in such a way
815 # as to avoid crashing php on some large strings.
816 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
818 $sql = str_replace ( "\\\\", '', $sql);
819 $sql = str_replace ( "\\'", '', $sql);
820 $sql = str_replace ( "\\\"", '', $sql);
821 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
822 $sql = preg_replace ('/".*"/s', "'X'", $sql);
824 # All newlines, tabs, etc replaced by single space
825 $sql = preg_replace ( "/\s+/", ' ', $sql);
828 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
834 * Determines whether a field exists in a table
835 * Usually aborts on failure
836 * If errors are explicitly ignored, returns NULL on failure
838 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
839 $table = $this->tableName( $table );
840 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE
, $fname );
847 while ( $row = $this->fetchObject( $res ) ) {
848 if ( $row->Field
== $field ) {
857 * Determines whether an index exists
858 * Usually aborts on failure
859 * If errors are explicitly ignored, returns NULL on failure
861 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
862 $info = $this->indexInfo( $table, $index, $fname );
863 if ( is_null( $info ) ) {
866 return $info !== false;
872 * Get information about an index into an object
873 * Returns false if the index does not exist
875 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
876 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
877 # SHOW INDEX should work for 3.x and up:
878 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
879 $table = $this->tableName( $table );
880 $sql = 'SHOW INDEX FROM '.$table;
881 $res = $this->query( $sql, $fname );
886 while ( $row = $this->fetchObject( $res ) ) {
887 if ( $row->Key_name
== $index ) {
895 * Query whether a given table exists
897 function tableExists( $table ) {
898 $table = $this->tableName( $table );
899 $old = $this->ignoreErrors( true );
900 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
901 $this->ignoreErrors( $old );
903 $this->freeResult( $res );
911 * mysql_fetch_field() wrapper
912 * Returns false if the field doesn't exist
917 function fieldInfo( $table, $field ) {
918 $table = $this->tableName( $table );
919 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
920 $n = mysql_num_fields( $res );
921 for( $i = 0; $i < $n; $i++
) {
922 $meta = mysql_fetch_field( $res, $i );
923 if( $field == $meta->name
) {
931 * mysql_field_type() wrapper
933 function fieldType( $res, $index ) {
934 return mysql_field_type( $res, $index );
938 * Determines if a given index is unique
940 function indexUnique( $table, $index ) {
941 $indexInfo = $this->indexInfo( $table, $index );
945 return !$indexInfo->Non_unique
;
949 * INSERT wrapper, inserts an array into a table
951 * $a may be a single associative array, or an array of these with numeric keys, for
954 * Usually aborts on failure
955 * If errors are explicitly ignored, returns success
957 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
958 # No rows to insert, easy just return now
959 if ( !count( $a ) ) {
963 $table = $this->tableName( $table );
964 if ( !is_array( $options ) ) {
965 $options = array( $options );
967 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
969 $keys = array_keys( $a[0] );
972 $keys = array_keys( $a );
975 $sql = 'INSERT ' . implode( ' ', $options ) .
976 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
980 foreach ( $a as $row ) {
986 $sql .= '(' . $this->makeList( $row ) . ')';
989 $sql .= '(' . $this->makeList( $a ) . ')';
991 return (bool)$this->query( $sql, $fname );
995 * Make UPDATE options for the Database::update function
998 * @param array $options The options passed to Database::update
1001 function makeUpdateOptions( $options ) {
1002 if( !is_array( $options ) ) {
1003 $options = array( $options );
1006 if ( in_array( 'LOW_PRIORITY', $options ) )
1007 $opts[] = $this->lowPriorityOption();
1008 if ( in_array( 'IGNORE', $options ) )
1010 return implode(' ', $opts);
1014 * UPDATE wrapper, takes a condition array and a SET array
1016 * @param string $table The table to UPDATE
1017 * @param array $values An array of values to SET
1018 * @param array $conds An array of conditions (WHERE)
1019 * @param string $fname The Class::Function calling this function
1021 * @param array $options An array of UPDATE options, can be one or
1022 * more of IGNORE, LOW_PRIORITY
1024 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1025 $table = $this->tableName( $table );
1026 $opts = $this->makeUpdateOptions( $options );
1027 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1028 if ( $conds != '*' ) {
1029 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1031 $this->query( $sql, $fname );
1035 * Makes a wfStrencoded list from an array
1036 * $mode: LIST_COMMA - comma separated, no field names
1037 * LIST_AND - ANDed WHERE clause (without the WHERE)
1038 * LIST_SET - comma separated with field names, like a SET clause
1039 * LIST_NAMES - comma separated field names
1041 function makeList( $a, $mode = LIST_COMMA
) {
1042 if ( !is_array( $a ) ) {
1043 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
1048 foreach ( $a as $field => $value ) {
1050 if ( $mode == LIST_AND
) {
1052 } elseif($mode == LIST_OR
) {
1060 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1061 $list .= "($value)";
1062 } elseif ( $mode == LIST_AND
&& is_array ($value) ) {
1063 $list .= $field." IN (".$this->makeList($value).") ";
1065 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1066 $list .= "$field = ";
1068 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1075 * Change the current database
1077 function selectDB( $db ) {
1078 $this->mDBname
= $db;
1079 return mysql_select_db( $db, $this->mConn
);
1083 * Starts a timer which will kill the DB thread after $timeout seconds
1085 function startTimer( $timeout ) {
1087 if( function_exists( 'mysql_thread_id' ) ) {
1088 # This will kill the query if it's still running after $timeout seconds.
1089 $tid = mysql_thread_id( $this->mConn
);
1090 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
1095 * Stop a timer started by startTimer()
1096 * Currently unimplemented.
1099 function stopTimer() { }
1102 * Format a table name ready for use in constructing an SQL query
1104 * This does two important things: it quotes table names which as necessary,
1105 * and it adds a table prefix if there is one.
1107 * All functions of this object which require a table name call this function
1108 * themselves. Pass the canonical name to such functions. This is only needed
1109 * when calling query() directly.
1111 * @param string $name database table name
1113 function tableName( $name ) {
1115 # Skip quoted literals
1116 if ( $name{0} != '`' ) {
1117 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
1118 $name = "{$this->mTablePrefix}$name";
1120 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1121 $name = "`$wgSharedDB`.`$name`";
1131 * Fetch a number of table names into an array
1132 * This is handy when you need to construct SQL for joins
1135 * extract($dbr->tableNames('user','watchlist'));
1136 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1137 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1139 function tableNames() {
1140 $inArray = func_get_args();
1142 foreach ( $inArray as $name ) {
1143 $retVal[$name] = $this->tableName( $name );
1151 function tableNamesWithUseIndex( $tables, $use_index ) {
1154 foreach ( $tables as $table )
1155 if ( @$use_index[$table] !== null )
1156 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1158 $ret[] = $this->tableName( $table );
1160 return implode( ',', $ret );
1164 * Wrapper for addslashes()
1165 * @param string $s String to be slashed.
1166 * @return string slashed string.
1168 function strencode( $s ) {
1169 return addslashes( $s );
1173 * If it's a string, adds quotes and backslashes
1174 * Otherwise returns as-is
1176 function addQuotes( $s ) {
1177 if ( is_null( $s ) ) {
1180 # This will also quote numeric values. This should be harmless,
1181 # and protects against weird problems that occur when they really
1182 # _are_ strings such as article titles and string->number->string
1183 # conversion is not 1:1.
1184 return "'" . $this->strencode( $s ) . "'";
1189 * Escape string for safe LIKE usage
1191 function escapeLike( $s ) {
1192 $s=$this->strencode( $s );
1193 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1198 * Returns an appropriately quoted sequence value for inserting a new row.
1199 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1200 * subclass will return an integer, and save the value for insertId()
1202 function nextSequenceValue( $seqName ) {
1208 * PostgreSQL doesn't have them and returns ""
1210 function useIndexClause( $index ) {
1211 return "FORCE INDEX ($index)";
1215 * REPLACE query wrapper
1216 * PostgreSQL simulates this with a DELETE followed by INSERT
1217 * $row is the row to insert, an associative array
1218 * $uniqueIndexes is an array of indexes. Each element may be either a
1219 * field name or an array of field names
1221 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1222 * However if you do this, you run the risk of encountering errors which wouldn't have
1225 * @todo migrate comment to phodocumentor format
1227 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1228 $table = $this->tableName( $table );
1231 if ( !is_array( reset( $rows ) ) ) {
1232 $rows = array( $rows );
1235 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1237 foreach ( $rows as $row ) {
1243 $sql .= '(' . $this->makeList( $row ) . ')';
1245 return $this->query( $sql, $fname );
1249 * DELETE where the condition is a join
1250 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1252 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1253 * join condition matches, set $conds='*'
1255 * DO NOT put the join condition in $conds
1257 * @param string $delTable The table to delete from.
1258 * @param string $joinTable The other table.
1259 * @param string $delVar The variable to join on, in the first table.
1260 * @param string $joinVar The variable to join on, in the second table.
1261 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1263 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1265 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1268 $delTable = $this->tableName( $delTable );
1269 $joinTable = $this->tableName( $joinTable );
1270 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1271 if ( $conds != '*' ) {
1272 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1275 return $this->query( $sql, $fname );
1279 * Returns the size of a text field, or -1 for "unlimited"
1281 function textFieldSize( $table, $field ) {
1282 $table = $this->tableName( $table );
1283 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1284 $res = $this->query( $sql, 'Database::textFieldSize' );
1285 $row = $this->fetchObject( $res );
1286 $this->freeResult( $res );
1288 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
1297 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1299 function lowPriorityOption() {
1300 return 'LOW_PRIORITY';
1304 * DELETE query wrapper
1306 * Use $conds == "*" to delete all rows
1308 function delete( $table, $conds, $fname = 'Database::delete' ) {
1310 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1312 $table = $this->tableName( $table );
1313 $sql = "DELETE FROM $table";
1314 if ( $conds != '*' ) {
1315 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1317 return $this->query( $sql, $fname );
1321 * INSERT SELECT wrapper
1322 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1323 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1324 * $conds may be "*" to copy the whole table
1325 * srcTable may be an array of tables.
1327 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1328 $destTable = $this->tableName( $destTable );
1329 if( is_array( $srcTable ) ) {
1330 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1332 $srcTable = $this->tableName( $srcTable );
1334 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1335 ' SELECT ' . implode( ',', $varMap ) .
1337 if ( $conds != '*' ) {
1338 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1340 return $this->query( $sql, $fname );
1344 * Construct a LIMIT query with optional offset
1345 * This is used for query pages
1346 * $sql string SQL query we will append the limit too
1347 * $limit integer the SQL limit
1348 * $offset integer the SQL offset (default false)
1350 function limitResult($sql, $limit, $offset=false) {
1351 return " $sql LIMIT ".((is_numeric($offset) && $offset != 0)?
"{$offset},":"")."{$limit} ";
1353 function limitResultForUpdate($sql, $num) {
1354 return $this->limitResult($sql, $num, 0);
1358 * Returns an SQL expression for a simple conditional.
1361 * @param string $cond SQL expression which will result in a boolean value
1362 * @param string $trueVal SQL expression to return if true
1363 * @param string $falseVal SQL expression to return if false
1364 * @return string SQL fragment
1366 function conditional( $cond, $trueVal, $falseVal ) {
1367 return " IF($cond, $trueVal, $falseVal) ";
1371 * Determines if the last failure was due to a deadlock
1373 function wasDeadlock() {
1374 return $this->lastErrno() == 1213;
1378 * Perform a deadlock-prone transaction.
1380 * This function invokes a callback function to perform a set of write
1381 * queries. If a deadlock occurs during the processing, the transaction
1382 * will be rolled back and the callback function will be called again.
1385 * $dbw->deadlockLoop( callback, ... );
1387 * Extra arguments are passed through to the specified callback function.
1389 * Returns whatever the callback function returned on its successful,
1390 * iteration, or false on error, for example if the retry limit was
1393 function deadlockLoop() {
1394 $myFname = 'Database::deadlockLoop';
1397 $args = func_get_args();
1398 $function = array_shift( $args );
1399 $oldIgnore = $this->ignoreErrors( true );
1400 $tries = DEADLOCK_TRIES
;
1401 if ( is_array( $function ) ) {
1402 $fname = $function[0];
1407 $retVal = call_user_func_array( $function, $args );
1408 $error = $this->lastError();
1409 $errno = $this->lastErrno();
1410 $sql = $this->lastQuery();
1413 if ( $this->wasDeadlock() ) {
1415 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1417 $this->reportQueryError( $error, $errno, $sql, $fname );
1420 } while( $this->wasDeadlock() && --$tries > 0 );
1421 $this->ignoreErrors( $oldIgnore );
1422 if ( $tries <= 0 ) {
1423 $this->query( 'ROLLBACK', $myFname );
1424 $this->reportQueryError( $error, $errno, $sql, $fname );
1427 $this->query( 'COMMIT', $myFname );
1433 * Do a SELECT MASTER_POS_WAIT()
1435 * @param string $file the binlog file
1436 * @param string $pos the binlog position
1437 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1439 function masterPosWait( $file, $pos, $timeout ) {
1440 $fname = 'Database::masterPosWait';
1441 wfProfileIn( $fname );
1444 # Commit any open transactions
1445 $this->immediateCommit();
1447 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1448 $encFile = $this->strencode( $file );
1449 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1450 $res = $this->doQuery( $sql );
1451 if ( $res && $row = $this->fetchRow( $res ) ) {
1452 $this->freeResult( $res );
1453 wfProfileOut( $fname );
1456 wfProfileOut( $fname );
1462 * Get the position of the master from SHOW SLAVE STATUS
1464 function getSlavePos() {
1465 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1466 $row = $this->fetchObject( $res );
1468 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1470 return array( false, false );
1475 * Get the position of the master from SHOW MASTER STATUS
1477 function getMasterPos() {
1478 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1479 $row = $this->fetchObject( $res );
1481 return array( $row->File
, $row->Position
);
1483 return array( false, false );
1488 * Begin a transaction, or if a transaction has already started, continue it
1490 function begin( $fname = 'Database::begin' ) {
1491 if ( !$this->mTrxLevel
) {
1492 $this->immediateBegin( $fname );
1499 * End a transaction, or decrement the nest level if transactions are nested
1501 function commit( $fname = 'Database::commit' ) {
1502 if ( $this->mTrxLevel
) {
1505 if ( !$this->mTrxLevel
) {
1506 $this->immediateCommit( $fname );
1511 * Rollback a transaction
1513 function rollback( $fname = 'Database::rollback' ) {
1514 $this->query( 'ROLLBACK', $fname );
1515 $this->mTrxLevel
= 0;
1519 * Begin a transaction, committing any previously open transaction
1521 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1522 $this->query( 'BEGIN', $fname );
1523 $this->mTrxLevel
= 1;
1527 * Commit transaction, if one is open
1529 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1530 $this->query( 'COMMIT', $fname );
1531 $this->mTrxLevel
= 0;
1535 * Return MW-style timestamp used for MySQL schema
1537 function timestamp( $ts=0 ) {
1538 return wfTimestamp(TS_MW
,$ts);
1542 * Local database timestamp format or null
1544 function timestampOrNull( $ts = null ) {
1545 if( is_null( $ts ) ) {
1548 return $this->timestamp( $ts );
1555 function resultObject( $result ) {
1556 if( empty( $result ) ) {
1559 return new ResultWrapper( $this, $result );
1564 * Return aggregated value alias
1566 function aggregateValue ($valuedata,$valuename='value') {
1571 * @return string wikitext of a link to the server software's web site
1573 function getSoftwareLink() {
1574 return "[http://www.mysql.com/ MySQL]";
1578 * @return string Version information from the database
1580 function getServerVersion() {
1581 return mysql_get_server_info();
1585 * Ping the server and try to reconnect if it there is no connection
1588 if( function_exists( 'mysql_ping' ) ) {
1589 return mysql_ping( $this->mConn
);
1591 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1598 * At the moment, this will only work if the DB user has the PROCESS privilege
1601 $res = $this->query( 'SHOW PROCESSLIST' );
1602 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1603 # dubious, but unfortunately there's no easy rigorous way
1605 while ( $row = $this->fetchObject( $res ) ) {
1606 if ( $row->User
== 'system user' ) {
1607 if ( ++
$slaveThreads == 2 ) {
1608 # This is it, return the time
1617 * Get status information from SHOW STATUS in an associative array
1619 function getStatus() {
1620 $res = $this->query( 'SHOW STATUS' );
1622 while ( $row = $this->fetchObject( $res ) ) {
1623 $status[$row->Variable_name
] = $row->Value
;
1629 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1631 function maxListLen() {
1635 function encodeBlob($b) {
1639 function notNullTimestamp() {
1642 function isNullTimestamp() {
1648 * Database abstraction object for mySQL
1649 * Inherit all methods and properties of Database::Database()
1651 * @package MediaWiki
1654 class DatabaseMysql
extends Database
{
1660 * Result wrapper for grabbing data queried by someone else
1662 * @package MediaWiki
1664 class ResultWrapper
{
1670 function ResultWrapper( $database, $result ) {
1671 $this->db
=& $database;
1672 $this->result
=& $result;
1678 function numRows() {
1679 return $this->db
->numRows( $this->result
);
1685 function fetchObject() {
1686 return $this->db
->fetchObject( $this->result
);
1692 function &fetchRow() {
1693 return $this->db
->fetchRow( $this->result
);
1700 $this->db
->freeResult( $this->result
);
1701 unset( $this->result
);
1705 function seek( $row ) {
1706 $this->db
->dataSeek( $this->result
, $row );
1710 #------------------------------------------------------------------------------
1712 #------------------------------------------------------------------------------
1715 * Standard fail function, called by default when a connection cannot be
1717 * Displays the file cache if possible
1719 function wfEmergencyAbort( &$conn, $error ) {
1720 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1721 global $wgSitename, $wgServer, $wgMessageCache, $wgLogo;
1723 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1724 # Hard coding strings instead.
1726 $noconnect = "<h1><img src='$wgLogo' style='float:left;margin-right:1em' alt=''>$wgSitename has a problem</h1><p><strong>Sorry! This site is experiencing technical difficulties.</strong></p><p>Try waiting a few minutes and reloading.</p><p><small>(Can't contact the database server: $1)</small></p>";
1727 $mainpage = 'Main Page';
1728 $searchdisabled = <<<EOT
1729 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1730 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1734 <!-- SiteSearch Google -->
1735 <FORM method=GET action=\"http://www.google.com/search\">
1736 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1737 <A HREF=\"http://www.google.com/\">
1738 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1739 border=\"0\" ALT=\"Google\"></A>
1742 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1743 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1745 <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 />
1746 <input type='hidden' name='ie' value='$2'>
1747 <input type='hidden' name='oe' value='$2'>
1751 <!-- SiteSearch Google -->";
1752 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1755 if( !headers_sent() ) {
1756 header( 'HTTP/1.0 500 Internal Server Error' );
1757 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1758 /* Don't cache error pages! They cause no end of trouble... */
1759 header( 'Cache-control: none' );
1760 header( 'Pragma: nocache' );
1763 # No database access
1764 if ( is_object( $wgMessageCache ) ) {
1765 $wgMessageCache->disable();
1768 $msg = wfGetSiteNotice();
1770 $msg = str_replace( '$1', $error, $noconnect );
1774 if($wgUseFileCache) {
1779 $t = Title
::newFromURL( $title );
1780 } elseif (@/**/$_REQUEST['search']) {
1781 $search = $_REQUEST['search'];
1782 echo $searchdisabled;
1783 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1784 $wgInputEncoding ), $googlesearch );
1787 $t = Title
::newFromText( $mainpage );
1791 $cache = new CacheManager( $t );
1792 if( $cache->isFileCached() ) {
1793 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1794 $cachederror . "</b></p>\n";
1796 $tag = '<div id="article">';
1797 $text = str_replace(
1800 $cache->fetchPageText() );