Reverting for now this undiscussed and problematic change:
[lhc/web/wiklou.git] / includes / Database.php
index 68dad73..cb4632b 100644 (file)
@@ -44,6 +44,7 @@ class Database {
        var $mTablePrefix;
        var $mFlags;
        var $mTrxLevel = 0;
+       var $mErrorCount = 0;
        /**#@-*/
 
 #------------------------------------------------------------------------------
@@ -105,6 +106,13 @@ class Database {
                return wfSetVar( $this->mTrxLevel, $level );
        }
 
+       /** 
+        * Number of errors logged, only useful when errors are ignored
+        */
+       function errorCount( $count = NULL ) {
+               return wfSetVar( $this->mErrorCount, $count );
+       }
+
        /**#@+
         * Get function
         */
@@ -148,6 +156,13 @@ class Database {
                                $this->mFlags |= DBO_TRX;
                        }
                }
+
+               /*
+               // Faster read-only access
+               if ( wfReadOnly() ) {
+                       $this->mFlags |= DBO_PERSISTENT;
+                       $this->mFlags &= ~DBO_TRX;
+               }*/
                
                /** Get the default table prefix*/
                if ( $tablePrefix == 'get from global' ) {
@@ -196,7 +211,13 @@ class Database {
                
                $success = false;
                
-               @/**/$this->mConn = mysql_connect( $server, $user, $password );
+               if ( $this->mFlags & DBO_PERSISTENT ) {
+                       @/**/$this->mConn = mysql_pconnect( $server, $user, $password );
+               } else {
+                       # Create a new connection...
+                       @/**/$this->mConn = mysql_connect( $server, $user, $password, true );
+               }
+
                if ( $dbName != '' ) {
                        if ( $this->mConn !== false ) {
                                $success = @/**/mysql_select_db( $dbName, $this->mConn );
@@ -206,12 +227,12 @@ class Database {
                        } else {
                                wfDebug( "DB connection error\n" );
                                wfDebug( "Server: $server, User: $user, Password: " . 
-                                       substr( $password, 0, 3 ) . "...\n" );
+                                       substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
                                $success = false;
                        }
                } else {
                        # Delay USE query
-                       $success = !!$this->mConn;
+                       $success = (bool)$this->mConn;
                }
                
                if ( !$success ) {
@@ -265,40 +286,68 @@ class Database {
        function query( $sql, $fname = '', $tempIgnore = false ) {
                global $wgProfiling, $wgCommandLineMode;
                
+               if ( wfReadOnly() ) {
+                       # This is a quick check for the most common kinds of write query used 
+                       # in MediaWiki, to provide extra safety in addition to UI-level checks. 
+                       # It is not intended to prevent every conceivable write query, or even 
+                       # to handle such queries gracefully.
+                       if ( preg_match( '/^(update|insert|replace|delete)/i', $sql ) ) {
+                               wfDebug( "Write query from $fname blocked\n" );
+                               return false;
+                       }
+               }
+
                if ( $wgProfiling ) {
                        # generalizeSQL will probably cut down the query to reasonable
                        # logging size most of the time. The substr is really just a sanity check.
-                       $profName = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 ); 
+                       $profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 ); 
+                       wfProfileIn( 'Database::query' );
                        wfProfileIn( $profName );
                }
                
                $this->mLastQuery = $sql;
                
-               if ( $this->debug() ) {
-                       $sqlx = substr( $sql, 0, 500 );
-                       $sqlx = wordwrap(strtr($sqlx,"\t\n",'  '));
-                       wfDebug( "SQL: $sqlx\n" );
-               }
                # Add a comment for easy SHOW PROCESSLIST interpretation
                if ( $fname ) {
                        $commentedSql = "/* $fname */ $sql";
                } else {
                        $commentedSql = $sql;
                }
-               
+
                # If DBO_TRX is set, start a transaction
                if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() && $sql != 'BEGIN' ) {
                        $this->begin();
                }
+
+               if ( $this->debug() ) {
+                       $sqlx = substr( $commentedSql, 0, 500 );
+                       $sqlx = strtr( $sqlx, "\t\n", '  ' );
+                       wfDebug( "SQL: $sqlx\n" );
+               }
                
                # Do the query and handle errors
                $ret = $this->doQuery( $commentedSql );
+
+               # Try reconnecting if the connection was lost
+               if ( false === $ret && ( $this->lastErrno() == 2013 || $this->lastErrno() == 2006 ) ) {
+                       # Transaction is gone, like it or not
+                       $this->mTrxLevel = 0;
+                       wfDebug( "Connection lost, reconnecting...\n" );
+                       if ( $this->ping() ) {
+                               wfDebug( "Reconnected\n" );
+                               $ret = $this->doQuery( $commentedSql );
+                       } else {
+                               wfDebug( "Failed\n" );
+                       }
+               }
+
                if ( false === $ret ) {
                        $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
                }
                                
                if ( $wgProfiling ) {
                        wfProfileOut( $profName );
+                       wfProfileOut( 'Database::query' );
                }
                return $ret;
        }
@@ -327,12 +376,13 @@ class Database {
                global $wgCommandLineMode, $wgFullyInitialised;
                # Ignore errors during error handling to avoid infinite recursion
                $ignore = $this->ignoreErrors( true );
+               $this->mErrorCount ++;
 
                if( $ignore || $tempIgnore ) {
                        wfDebug("SQL ERROR (ignored): " . $error . "\n");
                } else {
                        $sql1line = str_replace( "\n", "\\n", $sql );
-                       wfLogDBError("$fname\t$errno\t$error\t$sql1line\n");
+                       wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
                        wfDebug("SQL ERROR: " . $error . "\n");
                        if ( $wgCommandLineMode || !$this->mOut || empty( $wgFullyInitialised ) ) {
                                $message = "A database error has occurred\n" .
@@ -390,7 +440,8 @@ class Database {
        /**
         * Prepare & execute an SQL statement, quoting and inserting arguments
         * in the appropriate places.
-        * @param 
+        * @param string $query
+        * @param string $args ...
         */
        function safeQuery( $query, $args = null ) {
                $prepared = $this->prepare( $query, 'Database::safeQuery' );
@@ -510,8 +561,8 @@ class Database {
         * The value inserted should be fetched from nextSequenceValue()
         *
         * Example:
-        * $id = $dbw->nextSequenceValue('cur_cur_id_seq');
-        * $dbw->insert('cur',array('cur_id' => $id));
+        * $id = $dbw->nextSequenceValue('page_page_id_seq');
+        * $dbw->insert('page',array('page_id' => $id));
         * $id = $dbw->insertId();
         */
        function insertId() { return mysql_insert_id( $this->mConn ); }
@@ -526,14 +577,29 @@ class Database {
         * Get the last error number
         * See mysql_errno()
         */
-       function lastErrno() { return mysql_errno(); }
+       function lastErrno() { 
+               if ( $this->mConn ) {
+                       return mysql_errno( $this->mConn ); 
+               } else {
+                       return mysql_errno();
+               }
+       }
        
        /**
         * Get a description of the last error
         * See mysql_error() for more details
         */
-       function lastError() { return mysql_error(); }
-       
+       function lastError() { 
+               if ( $this->mConn ) {
+                       $error = mysql_error( $this->mConn ); 
+               } else {
+                       $error = mysql_error();
+               }
+               if( $error ) {
+                       $error .= ' (' . $this->mServer . ')';
+               }
+               return $error;
+       }       
        /**
         * Get the number of rows affected by the last write query
         * See mysql_affected_rows() for more details
@@ -554,7 +620,7 @@ class Database {
                $table = $this->tableName( $table );
                $sql = "UPDATE $table SET $var = '" .
                  $this->strencode( $value ) . "' WHERE ($cond)";
-               return !!$this->query( $sql, DB_MASTER, $fname );
+               return (bool)$this->query( $sql, DB_MASTER, $fname );
        }
        
        /**
@@ -584,14 +650,19 @@ class Database {
        /**
         * Returns an optional USE INDEX clause to go after the table, and a
         * string to go at the end of the query
+        *
+        * @access private
+        *
+        * @param array $options an associative array of options to be turned into
+        *              an SQL query, valid keys are listed in the function.
+        * @return array
         */
        function makeSelectOptions( $options ) {
-               if ( !is_array( $options ) ) {
-                       $options = array( $options );
-               }
-
                $tailOpts = '';
 
+               if ( isset( $options['GROUP BY'] ) ) {
+                       $tailOpts .= " GROUP BY {$options['GROUP BY']}";
+               }
                if ( isset( $options['ORDER BY'] ) ) {
                        $tailOpts .= " ORDER BY {$options['ORDER BY']}";
                } 
@@ -631,7 +702,7 @@ class Database {
                        $from = '';
                }
 
-               list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
+               list( $useIndex, $tailOpts ) = $this->makeSelectOptions( (array)$options );
                
                if( !empty( $conds ) ) {
                        if ( is_array( $conds ) ) {
@@ -652,8 +723,9 @@ class Database {
         * $conds: a condition map, terms are ANDed together. 
         *   Items with numeric keys are taken to be literal conditions
         * Takes an array of selected variables, and a condition map, which is ANDed
-        * e.g. selectRow( "page", array( "page_id" ), array( "page_namespace" => 0, "page_title" => "Astronomy" ) )
-        *   would return an object where $obj->page_id is the ID of the Astronomy article
+        * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
+        * NS_MAIN, "page_title" => "Astronomy" ) )   would return an object where
+        * $obj- >page_id is the ID of the Astronomy article
         *
         * @todo migrate documentation to phpdocumentor format
         */
@@ -854,16 +926,46 @@ class Database {
                } else {
                        $sql .= '(' . $this->makeList( $a ) . ')';
                }
-               return !!$this->query( $sql, $fname );
+               return (bool)$this->query( $sql, $fname );
        }
 
        /**
-        * UPDATE wrapper, takes a condition array and a SET array
+        * Make UPDATE options for the Database::update function
+        *
+        * @access private
+        * @param array $options The options passed to Database::update
+        * @return string
         */
-       function update( $table, $values, $conds, $fname = 'Database::update' ) {
+       function makeUpdateOptions( $options ) {
+               if( !is_array( $options ) ) {
+                       wfDebugDieBacktrace( 'makeUpdateOptions given non-array' );
+               }
+               $opts = array();
+               if ( in_array( 'LOW_PRIORITY', $options ) )
+                       $opts[] = $this->lowPriorityOption();
+               if ( in_array( 'IGNORE', $options ) ) 
+                       $opts[] = 'IGNORE';
+               return implode(' ', $opts);
+       }
+       
+       /**
+        * UPDATE wrapper, takes a condition array and a SET array
+        *
+        * @param string $table  The table to UPDATE
+        * @param array  $values An array of values to SET
+        * @param array  $conds  An array of conditions (WHERE)
+        * @param string $fname  The Class::Function calling this function
+        *                       (for the log)
+        * @param array  $options An array of UPDATE options, can be one or
+        *                        more of IGNORE, LOW_PRIORITY
+        */
+       function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
                $table = $this->tableName( $table );
-               $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET );
-               $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
+               $opts = $this->makeUpdateOptions( $options );
+               $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
+               if ( $conds != '*' ) {
+                       $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
+               }
                $this->query( $sql, $fname );
        }
        
@@ -897,9 +999,9 @@ class Database {
                                $list .= $field." IN (".$this->makeList($value).") ";
                        } else {
                                if ( $mode == LIST_AND || $mode == LIST_SET ) {
-                                       $list .= $field.'=';
+                                       $list .= "$field = ";
                                }
-                               $list .= ($mode==LIST_NAMES?$value:$this->addQuotes( $value ));
+                               $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
                        }
                }
                return $list;
@@ -946,17 +1048,18 @@ class Database {
         */
        function tableName( $name ) {
                global $wgSharedDB;
-               if ( $this->mTablePrefix !== '' ) {
-                       if ( strpos( '.', $name ) === false ) {
-                               $name = $this->mTablePrefix . $name;
+               # Skip quoted literals
+               if ( $name{0} != '`' ) {
+                       if ( $this->mTablePrefix !== '' &&  strpos( '.', $name ) === false ) {
+                               $name = "{$this->mTablePrefix}$name";
                        }
-               }
-               if ( isset( $wgSharedDB ) && 'user' == $name ) {
-                       $name = $wgSharedDB . '.' . $name;
-               }
-               if( $name == 'group' ) {
-                       $name = '`' . $name . '`';
-               }
+                       if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
+                               $name = "`$wgSharedDB`.`$name`";
+                       } else {
+                               # Standard quoting
+                               $name = "`$name`";
+                       }
+               }               
                return $name;
        }
 
@@ -993,15 +1096,14 @@ class Database {
         */
        function addQuotes( $s ) {
                if ( is_null( $s ) ) {
-                       $s = 'NULL';
+                       return 'NULL';
                } else {
                        # This will also quote numeric values. This should be harmless,
                        # and protects against weird problems that occur when they really
                        # _are_ strings such as article titles and string->number->string
                        # conversion is not 1:1.
-                       $s = "'" . $this->strencode( $s ) . "'";
+                       return "'" . $this->strencode( $s ) . "'";
                } 
-               return $s;
        }
                
        /**
@@ -1018,7 +1120,7 @@ class Database {
         * PostgreSQL doesn't have them and returns ""
         */
        function useIndexClause( $index ) {
-               return 'USE INDEX ('.$index.')';
+               return "FORCE INDEX ($index)";
        }
 
        /**
@@ -1104,7 +1206,7 @@ class Database {
        }
 
        /**
-        * @return string Always return 'LOW_PRIORITY'
+        * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
         */
        function lowPriorityOption() {
                return 'LOW_PRIORITY';
@@ -1120,9 +1222,9 @@ class Database {
                        wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
                }
                $table = $this->tableName( $table );
-               $sql = "DELETE FROM $table ";
+               $sql = "DELETE FROM $table";
                if ( $conds != '*' ) {
-                       $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
+                       $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
                }
                return $this->query( $sql, $fname );
        }
@@ -1132,10 +1234,15 @@ class Database {
         * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
         * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
         * $conds may be "*" to copy the whole table
+        * srcTable may be an array of tables.
         */
        function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
                $destTable = $this->tableName( $destTable );
-               $srcTable = $this->tableName( $srcTable );
+                if( is_array( $srcTable ) ) {
+                        $srcTable =  implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
+               } else { 
+                       $srcTable = $this->tableName( $srcTable );
+               }
                $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
                        ' SELECT ' . implode( ',', $varMap ) . 
                        " FROM $srcTable";
@@ -1195,7 +1302,7 @@ class Database {
                $this->query( 'BEGIN', $myFname );
                $args = func_get_args();
                $function = array_shift( $args );
-               $oldIgnore = $dbw->ignoreErrors( true );
+               $oldIgnore = $this->ignoreErrors( true );
                $tries = DEADLOCK_TRIES;
                if ( is_array( $function ) ) {
                        $fname = $function[0];
@@ -1209,14 +1316,14 @@ class Database {
                        $sql = $this->lastQuery();
                        
                        if ( $errno ) {
-                               if ( $dbw->wasDeadlock() ) {
+                               if ( $this->wasDeadlock() ) {
                                        # Retry
                                        usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
                                } else {
-                                       $dbw->reportQueryError( $error, $errno, $sql, $fname );
+                                       $this->reportQueryError( $error, $errno, $sql, $fname );
                                }
                        }
-               } while( $dbw->wasDeadlock && --$tries > 0 );
+               } while( $this->wasDeadlock() && --$tries > 0 );
                $this->ignoreErrors( $oldIgnore );
                if ( $tries <= 0 ) {
                        $this->query( 'ROLLBACK', $myFname );
@@ -1335,10 +1442,21 @@ class Database {
                return wfTimestamp(TS_MW,$ts);
        }
        
+       /**
+        * Local database timestamp format or null
+        */
+       function timestampOrNull( $ts = null ) {
+               if( is_null( $ts ) ) {
+                       return null;
+               } else {
+                       return $this->timestamp( $ts );
+               }
+       }
+       
        /**
         * @todo document
         */
-       function &resultObject( &$result ) {
+       function resultObject( &$result ) {
                if( empty( $result ) ) {
                        return NULL;
                } else {
@@ -1366,6 +1484,50 @@ class Database {
        function getServerVersion() {
                return mysql_get_server_info();
        }
+
+       /**
+        * Ping the server and try to reconnect if it there is no connection
+        */
+       function ping() {
+               if( function_exists( 'mysql_ping' ) ) {
+                       return mysql_ping( $this->mConn );
+               } else {
+                       wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
+                       return true;
+               }
+       }
+       
+       /**
+        * Get slave lag.
+        * At the moment, this will only work if the DB user has the PROCESS privilege
+        */
+       function getLag() {
+               $res = $this->query( 'SHOW PROCESSLIST' );
+               # Find slave SQL thread. Assumed to be the second one running, which is a bit 
+               # dubious, but unfortunately there's no easy rigorous way
+               $slaveThreads = 0;
+               while ( $row = $this->fetchObject( $res ) ) {
+                       if ( $row->User == 'system user' ) {
+                               if ( ++$slaveThreads == 2 ) {
+                                       # This is it, return the time
+                                       return $row->Time;
+                               }
+                       }
+               }
+               return false;
+       }
+
+       /**
+        * Get status information from SHOW STATUS in an associative array
+        */
+       function getStatus() {
+               $res = $this->query( 'SHOW STATUS' );
+               $status = array();
+               while ( $row = $this->fetchObject( $res ) ) {
+                       $status[$row->Variable_name] = $row->Value;
+               }
+               return $status;
+       }
 } 
 
 /**
@@ -1406,7 +1568,7 @@ class ResultWrapper {
        /**
         * @todo document
         */
-       function &fetchObject() {
+       function fetchObject() {
                return $this->db->fetchObject( $this->result );
        }
        
@@ -1425,6 +1587,10 @@ class ResultWrapper {
                unset( $this->result );
                unset( $this->db );
        }
+
+       function seek( $row ) {
+               $this->db->dataSeek( $this->result, $row );
+       }
 }
 
 #------------------------------------------------------------------------------
@@ -1437,7 +1603,7 @@ class ResultWrapper {
  * Displays the file cache if possible
  */
 function wfEmergencyAbort( &$conn, $error ) {
-       global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
+       global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
        global $wgSitename, $wgServer;
        
        # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
@@ -1480,7 +1646,7 @@ border=\"0\" ALT=\"Google\"></A>
                header( 'Cache-control: none' );
                header( 'Pragma: nocache' );
        }
-       $msg = $wgSiteNotice;
+       $msg = wfGetSiteNotice();
        if($msg == '') {
                $msg = str_replace( '$1', $error, $noconnect );
        }