diff -urN --exclude=CVS --exclude='*.class' --exclude='*.jar' pgjdbc.clean/org/postgresql/core/Query.java pgjdbc/org/postgresql/core/Query.java
--- pgjdbc.clean/org/postgresql/core/Query.java	2005-01-11 10:25:43.000000000 +0200
+++ pgjdbc/org/postgresql/core/Query.java	2006-11-17 00:18:01.000000000 +0200
@@ -54,4 +54,20 @@
      * A closed Query should not be executed.
      */
     void close();
+    
+    /**
+     * Sets the fields that this query will return.
+     * 
+     * @param fields The fields that this query will return.
+     */
+    void setFields(Field[] fields);
+    
+    /**
+     * Returns the fields that this query will return. If the result set fields
+     * are not known returns null.
+     * 
+     * @return the fields that this query will return.
+     */
+    Field[] getFields();
+
 }
diff -urN --exclude=CVS --exclude='*.class' --exclude='*.jar' pgjdbc.clean/org/postgresql/core/v2/V2Query.java pgjdbc/org/postgresql/core/v2/V2Query.java
--- pgjdbc.clean/org/postgresql/core/v2/V2Query.java	2006-11-02 17:31:14.000000000 +0200
+++ pgjdbc/org/postgresql/core/v2/V2Query.java	2006-11-17 00:23:42.000000000 +0200
@@ -95,6 +95,13 @@
     public void close() {
     }
 
+    public Field[] getFields() {
+        return null;
+    }
+
+    public void setFields(Field[] fields) {
+    }
+
     String[] getFragments() {
         return fragments;
     }
diff -urN --exclude=CVS --exclude='*.class' --exclude='*.jar' pgjdbc.clean/org/postgresql/core/v3/CompositeQuery.java pgjdbc/org/postgresql/core/v3/CompositeQuery.java
--- pgjdbc.clean/org/postgresql/core/v3/CompositeQuery.java	2005-01-11 10:25:44.000000000 +0200
+++ pgjdbc/org/postgresql/core/v3/CompositeQuery.java	2006-11-17 00:18:01.000000000 +0200
@@ -56,6 +56,13 @@
         return subqueries;
     }
 
+    public Field[] getFields() {
+        return null;
+    }
+
+    public void setFields(Field[] fields) {
+    }
+
     private final SimpleQuery[] subqueries;
     private final int[] offsets;
 }
diff -urN --exclude=CVS --exclude='*.class' --exclude='*.jar' pgjdbc.clean/org/postgresql/core/v3/QueryExecutorImpl.java pgjdbc/org/postgresql/core/v3/QueryExecutorImpl.java
--- pgjdbc.clean/org/postgresql/core/v3/QueryExecutorImpl.java	2006-11-02 17:31:14.000000000 +0200
+++ pgjdbc/org/postgresql/core/v3/QueryExecutorImpl.java	2006-11-17 00:45:16.000000000 +0200
@@ -805,12 +805,22 @@
                 encodedSize += (long)4 + params.getV3Length(i);
         }
 
+        int binaryResults = 0;
+        Field[] fields = query.getFields();
+        if (fields != null) {
+            for (int i = 0; i < fields.length; ++i) {
+                if (useBinary(fields[i])) {
+                    binaryResults = i + 1;
+                }
+            }
+        }
+        
         encodedSize = 4
                       + (encodedPortalName == null ? 0 : encodedPortalName.length) + 1
                       + (encodedStatementName == null ? 0 : encodedStatementName.length) + 1
                       + 2 + params.getParameterCount() * 2
                       + 2 + encodedSize
-                      + 2;
+                      + 2 + binaryResults * 2;
 
         // backend's MaxAllocSize is the largest message that can
         // be received from a client.  If we have a bigger value
@@ -865,7 +875,11 @@
             }
         }
 
-        pgStream.SendInteger2(0);   // # of result format codes (0)
+        pgStream.SendInteger2(binaryResults);   // # of result format codes
+        for (int i = 0; i < binaryResults; ++i) {
+            pgStream.SendInteger2(useBinary(fields[i]) ? Field.BINARY_FORMAT :
+                Field.TEXT_FORMAT);
+        }
 
         pendingBindQueue.add(portal);
 
@@ -874,6 +888,10 @@
             throw bindException;
         }
     }
+    
+    private boolean useBinary(Field field) {
+        return field.getOID() == Oid.BYTEA;
+    }
 
     private void sendDescribePortal(Portal portal) throws IOException {
         //
diff -urN --exclude=CVS --exclude='*.class' --exclude='*.jar' pgjdbc.clean/org/postgresql/core/v3/SimpleQuery.java pgjdbc/org/postgresql/core/v3/SimpleQuery.java
--- pgjdbc.clean/org/postgresql/core/v3/SimpleQuery.java	2006-08-06 21:02:45.000000000 +0300
+++ pgjdbc/org/postgresql/core/v3/SimpleQuery.java	2006-11-17 00:19:58.000000000 +0200
@@ -54,6 +54,14 @@
         unprepare();
     }
 
+    public Field[] getFields() {
+        return fields;
+    }
+
+    public void setFields(Field[] fields) {
+        this.fields = fields;
+    }
+
     //
     // V3Query
     //
@@ -126,6 +134,8 @@
     private byte[] encodedStatementName;
     private PhantomReference cleanupRef;
     private int[] preparedTypes;
+    private static final byte[] EMPTY_STATEMENTNAME = new byte[] { 0 };
+    private Field[] fields;
 
     final static SimpleParameterList NO_PARAMETERS = new SimpleParameterList(0);
 }
diff -urN --exclude=CVS --exclude='*.class' --exclude='*.jar' pgjdbc.clean/org/postgresql/jdbc2/AbstractJdbc2Statement.java pgjdbc/org/postgresql/jdbc2/AbstractJdbc2Statement.java
--- pgjdbc.clean/org/postgresql/jdbc2/AbstractJdbc2Statement.java	2006-11-05 07:58:22.000000000 +0200
+++ pgjdbc/org/postgresql/jdbc2/AbstractJdbc2Statement.java	2006-11-17 00:18:57.000000000 +0200
@@ -191,6 +191,9 @@
             try
             {
                 ResultSet rs = AbstractJdbc2Statement.this.createResultSet(fromQuery, fields, tuples, cursor);
+                if (preparedQuery != null) {
+                    preparedQuery.setFields(fields);
+                }                
                 append(new ResultWrapper(rs));
             }
             catch (SQLException e)
diff -urN --exclude=CVS --exclude='*.class' --exclude='*.jar' pgjdbc.clean/org/postgresql/test/jdbc3/ByteaBenchTest.java pgjdbc/org/postgresql/test/jdbc3/ByteaBenchTest.java
--- pgjdbc.clean/org/postgresql/test/jdbc3/ByteaBenchTest.java	1970-01-01 02:00:00.000000000 +0200
+++ pgjdbc/org/postgresql/test/jdbc3/ByteaBenchTest.java	2006-11-17 01:24:40.000000000 +0200
@@ -0,0 +1,197 @@
+/*-------------------------------------------------------------------------
+*
+* Copyright (c) 2004-2005, PostgreSQL Global Development Group
+*
+* IDENTIFICATION
+*   $PostgreSQL: pgjdbc/org/postgresql/test/jdbc3/BenchTest.java,v 1.1 2006/07/24 02:31:44 oliver Exp $
+*
+*-------------------------------------------------------------------------
+*/
+package org.postgresql.test.jdbc3;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Properties;
+
+import junit.framework.TestCase;
+
+import org.postgresql.test.TestUtil;
+
+public class ByteaBenchTest extends TestCase {
+
+    /**
+     * Number of times the table is queried.
+     */
+    private static final int QUERY_LOOP = 512;
+
+    /**
+     * Number of rows in temporary table.
+     */
+    private static final int[] SIZES = { 512, 2048, 4096, 16384 , 65536, 1048576 };
+
+    /**
+     * How many tries long to prime the jit.
+     */
+    private static final int PRIME_LOOP = 2000;
+
+    /**
+     * How many times to run the timing and print the times.
+     */
+    private static final int TIMING_LOOP = 10;
+    
+    private Connection _conn;
+
+    private String queryString;
+
+    private PreparedStatement query;
+    
+    public ByteaBenchTest(String name) {
+        super(name);
+    }
+
+    protected void setUp() throws Exception {
+        _conn = openDB();
+        _conn.setAutoCommit(false);
+
+        createTable();
+
+        query = _conn.prepareStatement("SELECT val FROM hold WHERE key=?");
+    }
+    
+    protected Connection openDB() throws Exception {
+        Properties p = new Properties();
+        p.setProperty("prepareThreshold", "1");
+        return TestUtil.openDB(p);
+    }
+
+    private void createTable() throws SQLException {
+	Statement stmt = _conn.createStatement();
+        stmt.execute("CREATE TEMP TABLE hold(key int, val bytea) " +
+                     " ON COMMIT PRESERVE ROWS");
+        stmt.close();
+
+        PreparedStatement insert =
+            _conn.prepareStatement("INSERT INTO hold (key, val) VALUES (?, ?)");
+        
+        StringBuilder sb = new StringBuilder();
+        sb.append("INSERT INTO hold (key");
+        for (int i=0; i<SIZES.length; ++i) {
+            insert.setInt(1, SIZES[i]);
+            insert.setBytes(2, createBytes(SIZES[i]));
+            assertEquals(1, insert.executeUpdate());
+        }
+        insert.close();
+        _conn.commit();
+    }
+
+    private byte[] createBytes(int len) {
+        byte[] b = new byte[len];
+        for (int i = 0; i < b.length; ++i) {
+            b[i] = (byte) i;
+        }
+        return b;
+    }
+
+    protected void tearDown() throws SQLException {
+	query.close();
+        dropTable();
+        TestUtil.closeDB(_conn);
+    }
+
+    private void dropTable() {
+	Statement stmt;
+	try {
+	    stmt = _conn.createStatement();
+	    stmt.execute("DROP TABLE hold");
+	    stmt.close();
+           _conn.commit();
+	} catch (SQLException e) {
+	    // ignored
+	}
+    }
+
+    public void testBenchmark() throws Exception {
+        System.out.print("Warming JIT for benchmark loop: ");
+        int printed = -1;
+        for (int i=0; i<PRIME_LOOP; ++i) {
+            for (int s = 0; s < SIZES.length; ++s)
+            query(SIZES[s]);
+            int readyNess = (PRIME_LOOP - i - 1) * 10 / PRIME_LOOP;
+            if (readyNess != printed) {
+                printed = readyNess;
+                System.out.print(printed);
+                clearGC();
+            }
+        }
+        System.out.println();
+        
+        // let jit do it's magic and flush all initial garbage
+        clearGC();
+        
+        System.in.read();
+        
+        double[] best = new double[SIZES.length];
+        long[] maxMemUse = new long[SIZES.length];
+        for (int s = 0; s < SIZES.length; ++s) {
+            int size = SIZES[s];
+            long start, stop;
+            int queries = QUERY_LOOP;
+            if (size > 16384) {
+                queries /= size / 16384;
+            } else {
+                queries *= 16384 / size;
+            }
+            System.out.printf("Transferring %.1fMB of data in %.1fkb chunks\n",
+                              size * queries / 1024.0 / 1024, size / 1024.0);
+            for (int i=0; i<TIMING_LOOP; ++i) {
+                start = System.currentTimeMillis();
+                for (int j=0; j<queries; ++j) {
+                    query(size);
+                }
+                stop = System.currentTimeMillis();
+                _conn.commit();
+
+                Runtime rt = Runtime.getRuntime();
+                long memUse = rt.totalMemory() - rt.freeMemory();
+                if (memUse > maxMemUse[s]) {
+                    maxMemUse[s] = memUse;
+                }
+                clearGC();
+
+                double speed = queries * 1000.0 / (stop-start) * size;
+                speed /= 1024 * 1024;
+                if (speed > best[s]) {
+                    best[s] = speed;
+                }
+                System.out.printf(" %7db speed:%5.1fMB/s (best %5.1fMB/s) memory: %5.1fMB (worst %5.1fMB)\n",
+                        size, speed, best[s], memUse/1024.0/1024.0, maxMemUse[s]/1024.0/1024.0);
+            }
+        }
+        
+        for (int s = 0; s < SIZES.length; ++s) {
+            System.out.printf("%7db speed: %5.1fMB/s memory: %5.1fMB\n",
+                    SIZES[s],
+                    best[s], maxMemUse[s]/1024.0/1024.0);
+        }
+    }
+
+    private void clearGC() throws InterruptedException {
+        Thread.sleep(10);
+        System.runFinalization();
+        System.gc();
+        Thread.sleep(90);
+    }
+
+    private void query(int size) throws SQLException {
+        query.setInt(1, size);
+        ResultSet rs = query.executeQuery();
+        assertTrue(rs.next());
+        byte[] bytes = rs.getBytes(1);
+        assertEquals(size, bytes.length);
+        assertFalse(rs.next());
+        rs.close();
+    }
+}
