pg.ddx.io  pgsql-jdbc@postgresql.org mailing list archive  
help / color / mirror / Atom feed
Binary transfer patches v15
3+ messages / 2 participants
[nested] [flat]

* Binary transfer patches v15
@ 2011-09-21 22:22  Mikko Tiihonen <mikko.tiihonen@nitorcreations.com>
  0 siblings, 2 replies; 3+ messages in thread

From: Mikko Tiihonen @ 2011-09-21 22:22 UTC (permalink / raw)
  To: pgsql-jdbc

I believe these are now ready for merging to cvs head. The patch set now passes all tests on jdk7u2 + postgres 9.1.0.

Changes from last week:
- Rebased to latest cvs
- Fixed connection leak in jdbc3/DatabaseMetaDataTest.java
    => now it is possible to run the unit tests with max_connections=2 in postgresql.conf
- Fixed ForceBinaryTransfer bug in DatabaseEncodingTest
    => Required a new field to Jdbc2ResultSet to keep the real statement alive
       (Thanks to Oliver for the good analysis on the problem)
- Fixed UpdateableResultTest.testUpdateStreams with binary transfers
    => now ResultSet.refreshRow() informs lower level code that the results are for
       updateable result set and should not use binary transfer

Any comments on what still needs to be done before this is accepted?

-Mikko

Attachments: download all (7 files, .tar.gz)

1-bugfixes.patch (text/plain, 1.4K) download Index: pgjdbc/org/postgresql/jdbc2/AbstractJdbc2DatabaseMetaData.java =================================================================== --- pgjdbc.orig/org/postgresql/jdbc2/AbstractJdbc2DatabaseMetaData.java +++ pgjdbc/org/postgresql/jdbc2/AbstractJdbc2DatabaseMetaData.java @@ -2510,7 +2510,7 @@ public abstract class AbstractJdbc2Datab tuple[13] = null; // sql data type (unused) tuple[14] = null; // sql datetime sub (unused) tuple[15] = tuple[6]; // char octet length - tuple[16] = rs.getBytes("attnum"); // ordinal position + tuple[16] = connection.encodeString(String.valueOf(rs.getInt("attnum"))); // ordinal position tuple[17] = connection.encodeString(rs.getBoolean("attnotnull") ? "NO" : "YES"); // Is nullable if (jdbcVersion >= 3) { Index: pgjdbc/org/postgresql/test/jdbc3/DatabaseMetaDataTest.java =================================================================== --- pgjdbc.orig/org/postgresql/test/jdbc3/DatabaseMetaDataTest.java +++ pgjdbc/org/postgresql/test/jdbc3/DatabaseMetaDataTest.java @@ -40,6 +40,7 @@ public class DatabaseMetaDataTest extend stmt.execute("DROP TABLE domtab"); stmt.execute("DROP DOMAIN mydom"); } + TestUtil.closeDB(_conn); } public void testGetColumnsForDomain() throws Exception
2-binarytransfer-core.patch (text/plain, 35.1K) download Index: pgjdbc/build.xml =================================================================== --- pgjdbc.orig/build.xml +++ pgjdbc/build.xml @@ -369,6 +369,8 @@ <property name="preparethreshold" value="5" /> <property name="loglevel" value="0" /> <property name="protocolVersion" value="0" /> + <property name="binarytransfer" value="true" /> + <property name="forcebinary" value="true" /> <!-- The tests now build to a separate directory and jarfile from the driver build, to ensure we're really testing against the jar we just @@ -411,6 +413,8 @@ <sysproperty key="preparethreshold" value="${preparethreshold}" /> <sysproperty key="loglevel" value="${loglevel}" /> <sysproperty key="protocolVersion" value="${protocolVersion}" /> + <sysproperty key="binaryTransfer" value="${binarytransfer}" /> + <sysproperty key="org.postgresql.forcebinary" value="${forcebinary}" /> <classpath> <pathelement location="${jardir}/postgresql.jar" /> Index: pgjdbc/doc/pgjdbc.xml =================================================================== --- pgjdbc.orig/doc/pgjdbc.xml +++ pgjdbc/doc/pgjdbc.xml @@ -567,6 +567,26 @@ Connection conn = DriverManager.getConne </varlistentry> <varlistentry> + <term><varname>binaryTransfer</varname> = <type>boolean</type></term> + <listitem> + <para> + The postgresql protocol v3 supports both binary and text transfer + of fields. When binaryTransfer is enabled the driver + requests binary transfer for all supported types. Using the binary + transfer is more optimal for both the server and the client. + + Previously driver versions supported only text transfers. The old + functionality can be obtained by setting this field to false. + + Currently the following column types currently support binary encoding: + <literal>BYTEA</literal>, <literal>TIMEx</literal>, + <literal>TIMESTAMP*</literal>, <literal>DATE</literal>, + <literal>INT*</literal> and <literal>FLOAT*</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> <term><varname>prepareThreshold</varname> = <type>int</type></term> <listitem> <para> Index: pgjdbc/org/postgresql/Driver.java.in =================================================================== --- pgjdbc.orig/org/postgresql/Driver.java.in +++ pgjdbc/org/postgresql/Driver.java.in @@ -443,6 +443,8 @@ public class Driver implements java.sql. "When connections that are not explicitly closed are garbage collected, log the stacktrace from the opening of the connection to trace the leak source."}, { "prepareThreshold", Boolean.FALSE, "Default statement prepare threshold (numeric)." }, + { "binaryTransfer", Boolean.FALSE, + "Use binary format for sending and receiving data if possible." }, { "charSet", Boolean.FALSE, "When connecting to a pre-7.3 server, the database encoding to assume is in use." }, { "compatible", Boolean.FALSE, Index: pgjdbc/org/postgresql/core/BaseConnection.java =================================================================== --- pgjdbc.orig/org/postgresql/core/BaseConnection.java +++ pgjdbc/org/postgresql/core/BaseConnection.java @@ -146,4 +146,13 @@ public interface BaseConnection extends * @return a ProtocolConnection.TRANSACTION_* constant. */ public int getTransactionState(); + + /** + * Returns true if value for the given oid should be sent using binary + * transfer. False if value should be sent using text transfer. + * + * @param oid The oid to check. + * @return True for binary transfer, false for text transfer. + */ + public boolean binaryTransferSend(int oid); } Index: pgjdbc/org/postgresql/core/ParameterList.java =================================================================== --- pgjdbc.orig/org/postgresql/core/ParameterList.java +++ pgjdbc/org/postgresql/core/ParameterList.java @@ -123,6 +123,17 @@ public interface ParameterList { void setBytea(int index, InputStream stream, int length) throws SQLException; /** + * Binds given byte[] value to a parameter. The bytes must already + * be in correct format matching the OID. + * + * @param index the 1-based parameter index to bind. + * @param value the bytes to send. + * @param oid the type OID of the parameter. + * @throws SQLException on error or if <code>index</code> is out of range + */ + void setBinaryParameter(int index, byte[] value, int oid) throws SQLException; + + /** * Binds a SQL NULL value to a parameter. * Associated with the parameter is a typename for the parameter that * should correspond to an entry in pg_types. Index: pgjdbc/org/postgresql/core/QueryExecutor.java =================================================================== --- pgjdbc.orig/org/postgresql/core/QueryExecutor.java +++ pgjdbc/org/postgresql/core/QueryExecutor.java @@ -98,6 +98,11 @@ public interface QueryExecutor { static int QUERY_DISALLOW_BATCHING = 128; /** + * Flag for query execution to avoid using binary transfer. + */ + static int QUERY_NO_BINARY_TRANSFER = 256; + + /** * Execute a Query, passing results to a provided ResultHandler. * * @param query the query to execute; must be a query returned from Index: pgjdbc/org/postgresql/core/v2/FastpathParameterList.java =================================================================== --- pgjdbc.orig/org/postgresql/core/v2/FastpathParameterList.java +++ pgjdbc/org/postgresql/core/v2/FastpathParameterList.java @@ -155,6 +155,10 @@ class FastpathParameterList implements P Arrays.fill(paramValues, null); } + public void setBinaryParameter(int index, byte[] value, int oid) { + throw new UnsupportedOperationException(); + } + private final Object[] paramValues; } Index: pgjdbc/org/postgresql/core/v2/SimpleParameterList.java =================================================================== --- pgjdbc.orig/org/postgresql/core/v2/SimpleParameterList.java +++ pgjdbc/org/postgresql/core/v2/SimpleParameterList.java @@ -168,6 +168,10 @@ class SimpleParameterList implements Par Arrays.fill(paramValues, null); } + public void setBinaryParameter(int index, byte[] value, int oid) { + throw new UnsupportedOperationException(); + } + private final Object[] paramValues; private final boolean useEStringSyntax; Index: pgjdbc/org/postgresql/core/v3/CompositeParameterList.java =================================================================== --- pgjdbc.orig/org/postgresql/core/v3/CompositeParameterList.java +++ pgjdbc/org/postgresql/core/v3/CompositeParameterList.java @@ -84,6 +84,11 @@ class CompositeParameterList implements subparams[sub].setStringParameter(index - offsets[sub], value, oid); } + public void setBinaryParameter(int index, byte[] value, int oid) throws SQLException { + int sub = findSubParam(index); + subparams[sub].setBinaryParameter(index - offsets[sub], value, oid); + } + public void setBytea(int index, byte[] data, int offset, int length) throws SQLException { int sub = findSubParam(index); subparams[sub].setBytea(index - offsets[sub], data, offset, length); Index: pgjdbc/org/postgresql/core/v3/QueryExecutorImpl.java =================================================================== --- pgjdbc.orig/org/postgresql/core/v3/QueryExecutorImpl.java +++ pgjdbc/org/postgresql/core/v3/QueryExecutorImpl.java @@ -1153,6 +1153,9 @@ public class QueryExecutorImpl implement query.unprepare(); processDeadParsedQueries(); + // Remove any cached Field values + query.setFields(null); + String statementName = null; if (!oneShot) { @@ -1241,7 +1244,8 @@ public class QueryExecutorImpl implement pendingParseQueue.add(new Object[]{query, query.getStatementName()}); } - private void sendBind(SimpleQuery query, SimpleParameterList params, Portal portal) throws IOException { + private void sendBind(SimpleQuery query, SimpleParameterList params, + Portal portal, boolean noBinaryTransfer) throws IOException { // // Send Bind. // @@ -1275,12 +1279,27 @@ public class QueryExecutorImpl implement encodedSize += (long)4 + params.getV3Length(i); } + // This is not the number of binary fields, but the total number + // of fields if any of them are binary or zero if all of them + // are text. + + int numBinaryFields = 0; + Field[] fields = query.getFields(); + if (!noBinaryTransfer && fields != null) { + for (int i = 0; i < fields.length; ++i) { + if (useBinary(fields[i])) { + fields[i].setFormat(Field.BINARY_FORMAT); + numBinaryFields = fields.length; + } + } + } + encodedSize = 4 + (encodedPortalName == null ? 0 : encodedPortalName.length) + 1 + (encodedStatementName == null ? 0 : encodedStatementName.length) + 1 + 2 + params.getParameterCount() * 2 + 2 + encodedSize - + 2; + + 2 + numBinaryFields * 2; // backend's MaxAllocSize is the largest message that can // be received from a client. If we have a bigger value @@ -1335,7 +1354,10 @@ public class QueryExecutorImpl implement } } - pgStream.SendInteger2(0); // # of result format codes (0) + pgStream.SendInteger2(numBinaryFields); // # of result format codes + for (int i = 0; i < numBinaryFields; ++i) { + pgStream.SendInteger2(fields[i].getFormat()); + } pendingBindQueue.add(portal); @@ -1345,6 +1367,19 @@ public class QueryExecutorImpl implement } } + /** + * Returns true if the specified field should be retrieved using binary + * encoding. + * + * @param field The field whose Oid type to analyse. + * @return True if {@link Field#BINARY_FORMAT} should be used, false if + * {@link Field#BINARY_FORMAT}. + */ + private boolean useBinary(Field field) { + int oid = field.getOID(); + return protoConnection.useBinaryForReceive(oid); + } + private void sendDescribePortal(SimpleQuery query, Portal portal) throws IOException { // // Send Describe. @@ -1485,6 +1520,7 @@ public class QueryExecutorImpl implement boolean describeOnly = (flags & QueryExecutor.QUERY_DESCRIBE_ONLY) != 0; boolean usePortal = (flags & QueryExecutor.QUERY_FORWARD_CURSOR) != 0 && !noResults && !noMeta && fetchSize > 0 && !describeOnly; boolean oneShot = (flags & QueryExecutor.QUERY_ONESHOT) != 0 && !usePortal; + boolean noBinaryTransfer = (flags & QUERY_NO_BINARY_TRANSFER) != 0; // Work out how many rows to fetch in this pass. @@ -1544,13 +1580,18 @@ public class QueryExecutorImpl implement portal = new Portal(query, portalName); } - sendBind(query, params, portal); + sendBind(query, params, portal, noBinaryTransfer); // A statement describe will also output a RowDescription, // so don't reissue it here if we've already done so. // - if (!noMeta && !describeStatement && !query.isPortalDescribed()) - sendDescribePortal(query, portal); + if (!noMeta && !describeStatement) { + // don't send describe if we already have cached the + // descriptionrow from previous executions + if (query.getFields() == null) { + sendDescribePortal(query, portal); + } + } sendExecute(query, portal, rows); } @@ -1908,7 +1949,8 @@ public class QueryExecutorImpl implement if (doneAfterRowDescNoData) { Object describeData[] = (Object[])pendingDescribeStatementQueue.get(describeIndex++); - Query currentQuery = (Query)describeData[0]; + SimpleQuery currentQuery = (SimpleQuery)describeData[0]; + currentQuery.setFields(fields); handler.handleResultRows(currentQuery, fields, tuples, null); tuples = null; Index: pgjdbc/org/postgresql/core/v3/SimpleParameterList.java =================================================================== --- pgjdbc.orig/org/postgresql/core/v3/SimpleParameterList.java +++ pgjdbc/org/postgresql/core/v3/SimpleParameterList.java @@ -32,11 +32,14 @@ class SimpleParameterList implements V3P private final static int OUT = 2; private final static int INOUT = IN|OUT; + private final static int TEXT = 0; + private final static int BINARY = 4; + SimpleParameterList(int paramCount, ProtocolConnectionImpl protoConnection) { this.paramValues = new Object[paramCount]; this.paramTypes = new int[paramCount]; this.encoded = new byte[paramCount][]; - this.direction = new int[paramCount]; + this.flags = new int[paramCount]; this.protoConnection = protoConnection; } @@ -45,10 +48,10 @@ class SimpleParameterList implements V3P if (index < 1 || index > paramValues.length) throw new PSQLException(GT.tr("The column index is out of range: {0}, number of columns: {1}.", new Object[]{new Integer(index), new Integer(paramValues.length)}), PSQLState.INVALID_PARAMETER_VALUE ); - direction[index-1] |= OUT; + flags[index-1] |= OUT; } - private void bind(int index, Object value, int oid) throws SQLException { + private void bind(int index, Object value, int oid, int binary) throws SQLException { if (index < 1 || index > paramValues.length) throw new PSQLException(GT.tr("The column index is out of range: {0}, number of columns: {1}.", new Object[]{new Integer(index), new Integer(paramValues.length)}), PSQLState.INVALID_PARAMETER_VALUE ); @@ -56,7 +59,7 @@ class SimpleParameterList implements V3P encoded[index] = null; paramValues[index] = value ; - direction[index] |= IN; + flags[index] = direction(index) | IN | binary; // If we are setting something to an UNSPECIFIED NULL, don't overwrite // our existing type for it. We don't need the correct type info to @@ -77,7 +80,7 @@ class SimpleParameterList implements V3P int count=0; for( int i=paramTypes.length; --i >= 0;) { - if ((direction[i] & OUT) == OUT ) + if ((direction(i) & OUT) == OUT) { count++; } @@ -93,7 +96,7 @@ class SimpleParameterList implements V3P int count=0; for( int i=0; i< paramTypes.length;i++) { - if (direction[i] != OUT ) + if (direction(i) != OUT ) { count++; } @@ -107,27 +110,31 @@ class SimpleParameterList implements V3P data[2] = (byte)(value >> 8); data[1] = (byte)(value >> 16); data[0] = (byte)(value >> 24); - bind(index, data, Oid.INT4); + bind(index, data, Oid.INT4, BINARY); } public void setLiteralParameter(int index, String value, int oid) throws SQLException { - bind(index, value, oid); + bind(index, value, oid, TEXT); } public void setStringParameter(int index, String value, int oid) throws SQLException { - bind(index, value, oid); + bind(index, value, oid, TEXT); + } + + public void setBinaryParameter(int index, byte[] value, int oid) throws SQLException { + bind(index, value, oid, BINARY); } public void setBytea(int index, byte[] data, int offset, int length) throws SQLException { - bind(index, new StreamWrapper(data, offset, length), Oid.BYTEA); + bind(index, new StreamWrapper(data, offset, length), Oid.BYTEA, BINARY); } public void setBytea(int index, InputStream stream, int length) throws SQLException { - bind(index, new StreamWrapper(stream, length), Oid.BYTEA); + bind(index, new StreamWrapper(stream, length), Oid.BYTEA, BINARY); } public void setNull(int index, int oid) throws SQLException { - bind(index, NULL_OBJECT, oid); + bind(index, NULL_OBJECT, oid, BINARY); } public String toString(int index) { @@ -174,7 +181,7 @@ class SimpleParameterList implements V3P public void checkAllParametersSet() throws SQLException { for (int i = 0; i < paramTypes.length; ++i) { - if (direction[i] != OUT && paramValues[i] == null) + if (direction(i) != OUT && paramValues[i] == null) throw new PSQLException(GT.tr("No value specified for parameter {0}.", new Integer(i + 1)), PSQLState.INVALID_PARAMETER_VALUE); } } @@ -183,7 +190,7 @@ class SimpleParameterList implements V3P { for (int i=0; i<paramTypes.length; ++i) { - if (direction[i] == OUT) + if (direction(i) == OUT) { paramTypes[i] = Oid.VOID; paramValues[i] = "null"; @@ -240,8 +247,11 @@ class SimpleParameterList implements V3P } boolean isBinary(int index) { - // Currently, only StreamWrapper uses the binary parameter form. - return (paramValues[index-1] instanceof StreamWrapper); + return (flags[index-1] & BINARY) != 0; + } + + private int direction(int index) { + return flags[index] & INOUT; } int getV3Length(int index) { @@ -302,7 +312,7 @@ class SimpleParameterList implements V3P SimpleParameterList newCopy = new SimpleParameterList(paramValues.length, protoConnection); System.arraycopy(paramValues, 0, newCopy.paramValues, 0, paramValues.length); System.arraycopy(paramTypes, 0, newCopy.paramTypes, 0, paramTypes.length); - System.arraycopy(direction, 0, newCopy.direction, 0, direction.length); + System.arraycopy(flags, 0, newCopy.flags, 0, flags.length); return newCopy; } @@ -310,7 +320,7 @@ class SimpleParameterList implements V3P Arrays.fill(paramValues, null); Arrays.fill(paramTypes, 0); Arrays.fill(encoded, null); - Arrays.fill(direction, 0); + Arrays.fill(flags, 0); } public SimpleParameterList[] getSubparams() { return null; @@ -318,7 +328,7 @@ class SimpleParameterList implements V3P private final Object[] paramValues; private final int[] paramTypes; - private final int[] direction; + private final int[] flags; private final byte[][] encoded; private final ProtocolConnectionImpl protoConnection; Index: pgjdbc/org/postgresql/ds/common/BaseDataSource.java =================================================================== --- pgjdbc.orig/org/postgresql/ds/common/BaseDataSource.java +++ pgjdbc/org/postgresql/ds/common/BaseDataSource.java @@ -51,6 +51,7 @@ public abstract class BaseDataSource imp private int portNumber = 0; private int prepareThreshold = 5; private int unknownLength = Integer.MAX_VALUE; + private boolean binaryTransfer = true; private int loginTimeout = 0; // in seconds private int socketTimeout = 0; // in seconds private boolean ssl = false; @@ -390,6 +391,28 @@ public abstract class BaseDataSource imp } /** + * Sets protocol transfer mode. + * See {@link org.postgresql.PGConnection#setBinaryTransfer(boolean)} for details. + * + * @param enabled True if the binary transfer mode is used for supported field types, + * false if text based transfer is used. + */ + public void setBinaryTransfer(boolean enabled) + { + this.binaryTransfer = enabled; + } + + /** + * Gets the protocol transfer mode. + * + * @see #setBinaryTransfer(boolean) + */ + public boolean getBinaryTransfer() + { + return binaryTransfer; + } + + /** * Generates a DriverManager URL from the other properties supplied. */ private String getUrl() @@ -423,6 +446,9 @@ public abstract class BaseDataSource imp sb.append("&ApplicationName="); sb.append(applicationName); } + if (binaryTransfer) { + sb.append("&binaryTransfer=true"); + } return sb.toString(); } @@ -457,6 +483,7 @@ public abstract class BaseDataSource imp ref.add(new StringRefAddr("prepareThreshold", Integer.toString(prepareThreshold))); ref.add(new StringRefAddr("unknownLength", Integer.toString(unknownLength))); + ref.add(new StringRefAddr("binaryTransfer", Boolean.toString(binaryTransfer))); ref.add(new StringRefAddr("loginTimeout", Integer.toString(loginTimeout))); ref.add(new StringRefAddr("socketTimeout", Integer.toString(socketTimeout))); @@ -494,6 +521,7 @@ public abstract class BaseDataSource imp out.writeInt(logLevel); out.writeInt(protocolVersion); out.writeObject(applicationName); + out.writeBoolean(binaryTransfer); } protected void readBaseObject(ObjectInputStream in) throws IOException, ClassNotFoundException @@ -514,6 +542,7 @@ public abstract class BaseDataSource imp logLevel = in.readInt(); protocolVersion = in.readInt(); applicationName = (String)in.readObject(); + binaryTransfer = in.readBoolean(); } public void initializeFrom(BaseDataSource source) throws IOException, ClassNotFoundException { Index: pgjdbc/org/postgresql/ds/common/PGObjectFactory.java =================================================================== --- pgjdbc.orig/org/postgresql/ds/common/PGObjectFactory.java +++ pgjdbc/org/postgresql/ds/common/PGObjectFactory.java @@ -114,6 +114,10 @@ public class PGObjectFactory implements if (prepareThreshold != null) ds.setPrepareThreshold(Integer.parseInt(prepareThreshold)); + String binaryTransfer = getProperty(ref, "binaryTransfer"); + if (binaryTransfer != null) + ds.setBinaryTransfer(Boolean.parseBoolean(binaryTransfer)); + return ds; } Index: pgjdbc/org/postgresql/jdbc2/AbstractJdbc2Connection.java =================================================================== --- pgjdbc.orig/org/postgresql/jdbc2/AbstractJdbc2Connection.java +++ pgjdbc/org/postgresql/jdbc2/AbstractJdbc2Connection.java @@ -74,6 +74,11 @@ public abstract class AbstractJdbc2Conne // Current warnings; there might be more on protoConnection too. public SQLWarning firstWarning = null; + /** BitSet of oids that use binary transfer when sending to server. */ + private BitSet useBinarySendForOids; + /** BitSet of oids that use binary transfer when receiving from server. */ + private BitSet useBinaryReceiveForOids; + public abstract DatabaseMetaData getMetaData() throws SQLException; // @@ -116,6 +121,14 @@ public abstract class AbstractJdbc2Conne catch (Exception e) { } + boolean binaryTransfer = true; + try + { + binaryTransfer = Boolean.valueOf(info.getProperty("binaryTransfer", "true")).booleanValue(); + } + catch (Exception e) + { + } //Print out the driver version number if (logger.logInfo()) @@ -126,6 +139,20 @@ public abstract class AbstractJdbc2Conne this.dbVersionNumber = protoConnection.getServerVersion(); this.compatible = info.getProperty("compatible", Driver.MAJORVERSION + "." + Driver.MINORVERSION); + // Formats that currently have binary protocol support + BitSet binaryOids = new BitSet(); + if (binaryTransfer && protoConnection.getProtocolVersion() >= 3) { + binaryOids.set(Oid.BYTEA); + } + + // split for receive and send for better control + useBinarySendForOids = new BitSet(); + useBinarySendForOids.or(binaryOids); + useBinaryReceiveForOids = new BitSet(); + useBinaryReceiveForOids.or(binaryOids); + + protoConnection.setBinaryReceiveOids(useBinaryReceiveForOids); + if (logger.logDebug()) { logger.debug(" compatible = " + compatible); @@ -1111,4 +1138,8 @@ public abstract class AbstractJdbc2Conne copyManager = new CopyManager(this); return copyManager; } + + public boolean binaryTransferSend(int oid) { + return useBinarySendForOids.get(oid); + } } Index: pgjdbc/org/postgresql/jdbc2/AbstractJdbc2ResultSet.java =================================================================== --- pgjdbc.orig/org/postgresql/jdbc2/AbstractJdbc2ResultSet.java +++ pgjdbc/org/postgresql/jdbc2/AbstractJdbc2ResultSet.java @@ -56,6 +56,7 @@ public abstract class AbstractJdbc2Resul private int fetchdirection = ResultSet.FETCH_UNKNOWN; protected final BaseConnection connection; // the connection we belong to protected final BaseStatement statement; // the statement we belong to + private Statement realStatement; // the real statement we belong to (when using forced binary prepared statement test hack) protected final Field fields[]; // Field metadata for this resultset. protected final Query originalQuery; // Query we originated from @@ -1187,7 +1188,8 @@ public abstract class AbstractJdbc2Resul } if ( connection.getLogger().logDebug() ) connection.getLogger().debug("selecting " + selectSQL.toString()); - selectStatement = ((java.sql.Connection) connection).prepareStatement(selectSQL.toString()); + // because updateable result sets do not yet support binary transfers we must request refresh with updateable result set to get field data in correct format + selectStatement = ((java.sql.Connection) connection).prepareStatement(selectSQL.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); for ( int j = 0, i = 1; j < numKeys; j++, i++) @@ -1693,7 +1695,7 @@ public abstract class AbstractJdbc2Resul case Types.BINARY: case Types.LONGVARBINARY: case Types.VARBINARY: - if (fields[columnIndex].getFormat() == Field.BINARY_FORMAT) { + if (isBinary(columnIndex + 1)) { rowBuffer[columnIndex] = (byte[]) valueObject; } else { try { @@ -1853,6 +1855,15 @@ public abstract class AbstractJdbc2Resul if (wasNullFlag) return null; + // convert binary fields to their text format + if (isBinary(columnIndex)) { + Object obj = internalGetObject(columnIndex, fields[columnIndex - 1]); + if (obj == null) { + return null; + } + return trimString(columnIndex, obj.toString()); + } + Encoding encoding = connection.getEncoding(); try { @@ -2238,7 +2249,7 @@ public abstract class AbstractJdbc2Resul if (wasNullFlag) return null; - if (fields[columnIndex - 1].getFormat() == Field.BINARY_FORMAT) + if (isBinary(columnIndex)) { //If the data is already binary then just return it return this_row[columnIndex - 1]; @@ -2678,6 +2689,16 @@ public abstract class AbstractJdbc2Resul wasNullFlag = (this_row[column - 1] == null); } + /** + * Returns true if the value of the given column is in binary format. + * + * @param column The column to check. Range starts from 1. + * @return True if the column is in binary format. + */ + protected boolean isBinary(int column) { + return fields[column - 1].getFormat() == Field.BINARY_FORMAT; + } + //----------------- Formatting Methods ------------------- public static boolean toBoolean(String s) @@ -2974,5 +2995,11 @@ public abstract class AbstractJdbc2Resul void addRows(Vector tuples) { rows.addAll(tuples); } + + + public void registerRealStatement(Statement realStatement) { + this.realStatement = realStatement; + } + } Index: pgjdbc/org/postgresql/jdbc2/AbstractJdbc2Statement.java =================================================================== --- pgjdbc.orig/org/postgresql/jdbc2/AbstractJdbc2Statement.java +++ pgjdbc/org/postgresql/jdbc2/AbstractJdbc2Statement.java @@ -35,6 +35,9 @@ import org.postgresql.util.GT; */ public abstract class AbstractJdbc2Statement implements BaseStatement { + // only for testing purposes. even single shot statements will use binary transfers + public static final boolean ForceBinaryTransfers = Boolean.getBoolean("org.postgresql.forcebinary"); + protected ArrayList batchStatements = null; protected ArrayList batchParameters = null; protected final int resultsettype; // the resultset type to return (ResultSet.TYPE_xxx) @@ -253,6 +256,27 @@ public abstract class AbstractJdbc2State throw new PSQLException(GT.tr("Can''t use query methods that take a query string on a PreparedStatement."), PSQLState.WRONG_OBJECT_TYPE); + if (ForceBinaryTransfers) { + clearWarnings(); + // Close any existing resultsets associated with this statement. + while (firstUnclosedResult != null) + { + if (firstUnclosedResult.getResultSet() != null) + firstUnclosedResult.getResultSet().close(); + firstUnclosedResult = firstUnclosedResult.getNext(); + } + + PreparedStatement ps = connection.prepareStatement(p_sql, resultsettype, concurrency, getResultSetHoldability()); + ps.setMaxFieldSize(getMaxFieldSize()); + ps.setFetchSize(getFetchSize()); + ps.setFetchDirection(getFetchDirection()); + AbstractJdbc2ResultSet rs = (AbstractJdbc2ResultSet) ps.executeQuery(); + rs.registerRealStatement(this); + + result = firstUnclosedResult = new ResultWrapper(rs); + return rs; + } + if (!executeWithFlags(p_sql, 0)) throw new PSQLException(GT.tr("No results were returned by the query."), PSQLState.NO_DATA); @@ -509,6 +533,20 @@ public abstract class AbstractJdbc2State if (connection.getAutoCommit()) flags |= QueryExecutor.QUERY_SUPPRESS_BEGIN; + // updateable result sets do not yet support binary updates + if (concurrency != ResultSet.CONCUR_READ_ONLY) + flags |= QueryExecutor.QUERY_NO_BINARY_TRANSFER; + + if (ForceBinaryTransfers) { + int flags2 = flags | QueryExecutor.QUERY_DESCRIBE_ONLY; + StatementResultHandler handler2 = new StatementResultHandler(); + connection.getQueryExecutor().execute(queryToExecute, queryParameters, handler2, 0, 0, flags2); + ResultWrapper result2 = handler2.getResults(); + if (result2 != null) { + result2.getResultSet().close(); + } + } + StatementResultHandler handler = new StatementResultHandler(); result = null; connection.getQueryExecutor().execute(queryToExecute, Index: pgjdbc/org/postgresql/test/TestUtil.java =================================================================== --- pgjdbc.orig/org/postgresql/test/TestUtil.java +++ pgjdbc/org/postgresql/test/TestUtil.java @@ -29,13 +29,19 @@ public class TestUtil protocolVersion = "&protocolVersion=" + getProtocolVersion(); } + String binaryTransfer = ""; + if (getBinaryTransfer() != null && !getBinaryTransfer().equals("")) { + binaryTransfer = "&binaryTransfer=" + getBinaryTransfer(); + } + return "jdbc:postgresql://" + getServer() + ":" + getPort() + "/" + getDatabase() + "?prepareThreshold=" + getPrepareThreshold() + "&loglevel=" + getLogLevel() - + protocolVersion; + + protocolVersion + + binaryTransfer; } /* @@ -99,6 +105,14 @@ public class TestUtil return Integer.parseInt(System.getProperty("loglevel")); } + /* + * Returns the binary transfer mode to use + */ + public static String getBinaryTransfer() + { + return System.getProperty("binaryTransfer"); + } + private static boolean initialized = false; public static void initDriver() throws Exception { Index: pgjdbc/org/postgresql/core/ProtocolConnection.java =================================================================== --- pgjdbc.orig/org/postgresql/core/ProtocolConnection.java +++ pgjdbc/org/postgresql/core/ProtocolConnection.java @@ -12,6 +12,7 @@ package org.postgresql.core; import org.postgresql.PGNotification; import java.sql.*; +import java.util.BitSet; /** * Provides access to protocol-level connection operations. @@ -132,4 +133,11 @@ public interface ProtocolConnection { * @return the version of the implementation */ public int getProtocolVersion(); + + /** + * Sets the oids that should be received using binary encoding. + * + * @param useBinaryForOids The oids to request with binary encoding. + */ + public void setBinaryReceiveOids(BitSet useBinaryForOids); } Index: pgjdbc/org/postgresql/core/v2/ProtocolConnectionImpl.java =================================================================== --- pgjdbc.orig/org/postgresql/core/v2/ProtocolConnectionImpl.java +++ pgjdbc/org/postgresql/core/v2/ProtocolConnectionImpl.java @@ -13,6 +13,7 @@ package org.postgresql.core.v2; import java.sql.*; import java.io.IOException; import java.util.ArrayList; +import java.util.BitSet; import org.postgresql.PGNotification; import org.postgresql.core.*; @@ -201,6 +202,10 @@ class ProtocolConnectionImpl implements return 2; } + public void setBinaryReceiveOids(BitSet ignored) { + // ignored for v2 connections + } + private String serverVersion; private int cancelPid; private int cancelKey; Index: pgjdbc/org/postgresql/core/v3/ProtocolConnectionImpl.java =================================================================== --- pgjdbc.orig/org/postgresql/core/v3/ProtocolConnectionImpl.java +++ pgjdbc/org/postgresql/core/v3/ProtocolConnectionImpl.java @@ -16,6 +16,7 @@ import org.postgresql.core.*; import java.sql.*; import java.io.IOException; import java.util.ArrayList; +import java.util.BitSet; import java.util.Properties; /** @@ -200,6 +201,20 @@ class ProtocolConnectionImpl implements return 3; } + public boolean useBinaryForReceive(int oid) { + return useBinaryForOids.get(oid); + } + + public void setBinaryReceiveOids(BitSet oids) { + useBinaryForOids.clear(); + useBinaryForOids.or(oids); + } + + /** + * Bit set that has a bit set for each oid which should be received + * using binary format. + */ + private final BitSet useBinaryForOids = new BitSet(); private String serverVersion; private int cancelPid; private int cancelKey;
3-debugging.patch (text/plain, 6.0K) download Index: pgjdbc/org/postgresql/core/Field.java =================================================================== --- pgjdbc.orig/org/postgresql/core/Field.java +++ pgjdbc/org/postgresql/core/Field.java @@ -197,4 +197,9 @@ public class Field return schemaName; } + public String toString() { + return "Field("+ (columnName != null ? columnName : "") + "," + + Oid.toString(oid) + "," + length + "," + + (format == TEXT_FORMAT ? 'T' : 'B') + ")"; + } } Index: pgjdbc/org/postgresql/core/Oid.java =================================================================== --- pgjdbc.orig/org/postgresql/core/Oid.java +++ pgjdbc/org/postgresql/core/Oid.java @@ -9,6 +9,8 @@ */ package org.postgresql.core; +import java.lang.reflect.Field; + /** * Provides constants for well-known backend OIDs for the types we commonly * use. @@ -67,4 +69,24 @@ public class Oid { public static final int XML = 142; public static final int XML_ARRAY = 143; + /** + * Returns the name of the oid as string. + * + * @param oid The oid to convert to name. + * @return The name of the oid or "<unknown>" if oid no constant for + * oid value has been defined. + */ + public static String toString(int oid) { + try { + Field[] fields = Oid.class.getFields(); + for (int i = 0; i < fields.length; ++i) { + if (fields[i].getInt(null) == oid) { + return fields[i].getName(); + } + } + } catch (IllegalAccessException e) { + // never happens + } + return "<unknown>"; + } } Index: pgjdbc/org/postgresql/core/v3/QueryExecutorImpl.java =================================================================== --- pgjdbc.orig/org/postgresql/core/v3/QueryExecutorImpl.java +++ pgjdbc/org/postgresql/core/v3/QueryExecutorImpl.java @@ -1851,7 +1851,7 @@ public class QueryExecutorImpl implement break; case 'D': // Data Transfer (ongoing Execute response) - Object tuple = null; + byte[][] tuple = null; try { tuple = pgStream.ReceiveTupleV3(); } catch(OutOfMemoryError oome) { @@ -1868,8 +1868,19 @@ public class QueryExecutorImpl implement tuples.addElement(tuple); } - if (logger.logDebug()) - logger.debug(" <=BE DataRow"); + if (logger.logDebug()) { + int length; + if (tuple == null) { + length = -1; + } else { + length = 0; + for (int i=0; i< tuple.length; ++i) { + if (tuple[i] == null) continue; + length += tuple[i].length; + } + } + logger.debug(" <=BE DataRow(len=" + length + ")"); + } break; @@ -2113,6 +2124,9 @@ public class QueryExecutorImpl implement "", /* name not yet determined */ typeOid, typeLength, typeModifier, tableOid, positionInTable); fields[i].setFormat(formatType); + + if (logger.logDebug()) + logger.debug(" " + fields[i]); } return fields; Index: pgjdbc/org/postgresql/core/v3/SimpleQuery.java =================================================================== --- pgjdbc.orig/org/postgresql/core/v3/SimpleQuery.java +++ pgjdbc/org/postgresql/core/v3/SimpleQuery.java @@ -120,9 +120,21 @@ class SimpleQuery implements V3Query { return encodedStatementName; } + /** + * Sets the fields that this query will return. + * + * @param fields The fields that this query will return. + */ void setFields(Field[] fields) { this.fields = 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() { return fields; } @@ -171,6 +183,10 @@ class SimpleQuery implements V3Query { private final ProtocolConnectionImpl protoConnection; private String statementName; private byte[] encodedStatementName; + /** + * The stored fields from previous query of a prepared statement, + * if executed before. Always null for non-prepared statements. + */ private Field[] fields; private boolean portalDescribed; private boolean statementDescribed; Index: pgjdbc/org/postgresql/jdbc2/AbstractJdbc2Connection.java =================================================================== --- pgjdbc.orig/org/postgresql/jdbc2/AbstractJdbc2Connection.java +++ pgjdbc/org/postgresql/jdbc2/AbstractJdbc2Connection.java @@ -158,6 +158,8 @@ public abstract class AbstractJdbc2Conne logger.debug(" compatible = " + compatible); logger.debug(" loglevel = " + logLevel); logger.debug(" prepare threshold = " + prepareThreshold); + logger.debug(" types using binary send = " + oidsToString(useBinarySendForOids)); + logger.debug(" types using binary receive = " + oidsToString(useBinaryReceiveForOids)); } // @@ -204,6 +206,21 @@ public abstract class AbstractJdbc2Conne } } + private String oidsToString(BitSet oids) { + StringBuffer sb = new StringBuffer(); + int oid = -1; + while ((oid = oids.nextSetBit(oid + 1)) != -1) { + sb.append(Oid.toString(oid)); + sb.append(','); + } + if (sb.length() > 0) { + sb.setLength(sb.length() - 1); + } else { + sb.append(" <none>"); + } + return sb.toString(); + } + private final TimestampUtils timestampUtils; public TimestampUtils getTimestampUtils() { return timestampUtils; }
4-integertypes.patch (text/plain, 13.9K) download Index: pgjdbc/org/postgresql/jdbc2/AbstractJdbc2Connection.java =================================================================== --- pgjdbc.orig/org/postgresql/jdbc2/AbstractJdbc2Connection.java +++ pgjdbc/org/postgresql/jdbc2/AbstractJdbc2Connection.java @@ -143,6 +143,11 @@ public abstract class AbstractJdbc2Conne BitSet binaryOids = new BitSet(); if (binaryTransfer && protoConnection.getProtocolVersion() >= 3) { binaryOids.set(Oid.BYTEA); + binaryOids.set(Oid.INT2); + binaryOids.set(Oid.INT4); + binaryOids.set(Oid.INT8); + binaryOids.set(Oid.FLOAT4); + binaryOids.set(Oid.FLOAT8); } // split for receive and send for better control Index: pgjdbc/org/postgresql/jdbc2/AbstractJdbc2ResultSet.java =================================================================== --- pgjdbc.orig/org/postgresql/jdbc2/AbstractJdbc2ResultSet.java +++ pgjdbc/org/postgresql/jdbc2/AbstractJdbc2ResultSet.java @@ -26,6 +26,7 @@ import java.util.Calendar; import java.util.Locale; import org.postgresql.core.*; import org.postgresql.largeobject.*; +import org.postgresql.util.ByteConverter; import org.postgresql.util.PGobject; import org.postgresql.util.PGbytea; import org.postgresql.util.PGtokenizer; @@ -1880,6 +1881,12 @@ public abstract class AbstractJdbc2Resul checkResultSet(columnIndex); if (wasNullFlag) return false; // SQL NULL + + if (isBinary(columnIndex)) { + int col = columnIndex - 1; + return readDoubleValue(this_row[col], fields[col].getOID(), + "boolean") == 1; + } return toBoolean( getString(columnIndex) ); } @@ -1893,6 +1900,15 @@ public abstract class AbstractJdbc2Resul if (wasNullFlag) return 0; // SQL NULL + if (isBinary(columnIndex)) { + int col = columnIndex - 1; + // there is no Oid for byte so must always do conversion from + // some other numeric type + return (byte) + readLongValue(this_row[col], fields[col].getOID(), Byte.MIN_VALUE, + Byte.MAX_VALUE, "byte"); + } + String s = getString(columnIndex); if (s != null ) @@ -1942,6 +1958,16 @@ public abstract class AbstractJdbc2Resul if (wasNullFlag) return 0; // SQL NULL + if (isBinary(columnIndex)) { + int col = columnIndex - 1; + int oid = fields[col].getOID(); + if (oid == Oid.INT2) { + return ByteConverter.int2(this_row[col], 0); + } + return (short) readLongValue(this_row[col], oid, Short.MIN_VALUE, + Short.MAX_VALUE, "short"); + } + String s = getFixedString(columnIndex); if (s != null) @@ -1984,6 +2010,16 @@ public abstract class AbstractJdbc2Resul if (wasNullFlag) return 0; // SQL NULL + if (isBinary(columnIndex)) { + int col = columnIndex - 1; + int oid = fields[col].getOID(); + if (oid == Oid.INT4) { + return ByteConverter.int4(this_row[col], 0); + } + return (int) readLongValue(this_row[col], oid, Integer.MIN_VALUE, + Integer.MAX_VALUE, "int"); + } + Encoding encoding = connection.getEncoding(); if (encoding.hasAsciiNumbers()) { try { @@ -2000,6 +2036,16 @@ public abstract class AbstractJdbc2Resul if (wasNullFlag) return 0; // SQL NULL + if (isBinary(columnIndex)) { + int col = columnIndex - 1; + int oid = fields[col].getOID(); + if (oid == Oid.INT8) { + return ByteConverter.int8(this_row[col], 0); + } + return readLongValue(this_row[col], oid, Long.MIN_VALUE, + Long.MAX_VALUE, "long"); + } + Encoding encoding = connection.getEncoding(); if (encoding.hasAsciiNumbers()) { try { @@ -2199,6 +2245,15 @@ public abstract class AbstractJdbc2Resul if (wasNullFlag) return 0; // SQL NULL + if (isBinary(columnIndex)) { + int col = columnIndex - 1; + int oid = fields[col].getOID(); + if (oid == Oid.FLOAT4) { + return ByteConverter.float4(this_row[col], 0); + } + return (float) readDoubleValue(this_row[col], oid, "float"); + } + return toFloat( getFixedString(columnIndex) ); } @@ -2208,6 +2263,15 @@ public abstract class AbstractJdbc2Resul if (wasNullFlag) return 0; // SQL NULL + if (isBinary(columnIndex)) { + int col = columnIndex - 1; + int oid = fields[col].getOID(); + if (oid == Oid.FLOAT8) { + return ByteConverter.float8(this_row[col], 0); + } + return readDoubleValue(this_row[col], oid, "double"); + } + return toDouble( getFixedString(columnIndex) ); } @@ -2926,6 +2990,88 @@ public abstract class AbstractJdbc2Resul } } + /** + * Converts any numeric binary field to double value. This method + * does no overflow checking. + * + * @param bytes The bytes of the numeric field. + * @param oid The oid of the field. + * @param targetType The target type. Used for error reporting. + * @return The value as double. + * @throws PSQLException If the field type is not supported numeric type. + */ + private double readDoubleValue(byte[] bytes, int oid, + String targetType) throws PSQLException { + // currently implemented binary encoded fields + switch (oid) { + case Oid.INT2: + return ByteConverter.int2(bytes, 0); + case Oid.INT4: + return ByteConverter.int4(bytes, 0); + case Oid.INT8: + // might not fit but there still should be no overflow checking + return ByteConverter.int8(bytes, 0); + case Oid.FLOAT4: + return ByteConverter.float4(bytes, 0); + case Oid.FLOAT8: + return ByteConverter.float8(bytes, 0); + } + throw new PSQLException (GT.tr("Cannot convert the column of type {0} to requested type {1}.", + new Object[]{Oid.toString(oid), targetType}), + PSQLState.DATA_TYPE_MISMATCH); + } + + /** + * Converts any numeric binary field to long value. + * <p> + * This method is used by getByte,getShort,getInt and getLong. + * It must support a subset of the following java types that use Binary + * encoding. (fields that use text encoding use a different code path). + * <p> + * <code>byte,short,int,long,float,double,BigDecimal,boolean,string</code>. + + * @param bytes The bytes of the numeric field. + * @param oid The oid of the field. + * @param minVal the minimum value allowed. + * @param minVal the maximum value allowed. + * @param targetType The target type. Used for error reporting. + * @return The value as long. + * @throws PSQLException If the field type is not supported numeric type + * or if the value is out of range. + */ + private long readLongValue(byte[] bytes, int oid, long minVal, long maxVal, + String targetType) + throws PSQLException { + long val; + // currently implemented binary encoded fields + switch (oid) { + case Oid.INT2: + val = ByteConverter.int2(bytes, 0); + break; + case Oid.INT4: + val = ByteConverter.int4(bytes, 0); + break; + case Oid.INT8: + val = ByteConverter.int8(bytes, 0); + break; + case Oid.FLOAT4: + val = (long) ByteConverter.float4(bytes, 0); + break; + case Oid.FLOAT8: + val = (long) ByteConverter.float8(bytes, 0); + break; + default: + throw new PSQLException (GT.tr("Cannot convert the column of type {0} to requested type {1}.", + new Object[]{Oid.toString(oid), targetType}), + PSQLState.DATA_TYPE_MISMATCH); + } + if (val < minVal || val > maxVal) { + throw new PSQLException(GT.tr("Bad value for type {0} : {1}", new Object[]{targetType, Long.valueOf(val)}), + PSQLState.NUMERIC_VALUE_OUT_OF_RANGE); + } + return val; + } + protected void updateValue(int columnIndex, Object value) throws SQLException { checkUpdateable(); Index: pgjdbc/org/postgresql/util/ByteConverter.java =================================================================== --- /dev/null +++ pgjdbc/org/postgresql/util/ByteConverter.java @@ -0,0 +1,157 @@ +/*------------------------------------------------------------------------- + * + * Copyright (c) 2006, PostgreSQL Global Development Group + * + * IDENTIFICATION + * $PostgreSQL: pgjdbc/org/postgresql/util/ByteConverter.java,v 1.1 2006/10/30 18:30:16 jurka Exp $ + * + *------------------------------------------------------------------------- + */ +package org.postgresql.util; + +/** + * Helper methods to parse java base types from byte arrays. + * + * @author Mikko Tiihonen + */ +public class ByteConverter { + + private ByteConverter() { + // prevent instantiation of static helper class + } + + /** + * Parses a long value from the byte array. + * + * @param bytes The byte array to parse. + * @param idx The starting index of the parse in the byte array. + * @return parsed long value. + */ + public static long int8(byte[] bytes, int idx) { + return + ((long)(bytes[idx+0] & 255) << 56) + + ((long)(bytes[idx+1] & 255) << 48) + + ((long)(bytes[idx+2] & 255) << 40) + + ((long)(bytes[idx+3] & 255) << 32) + + ((long)(bytes[idx+4] & 255) << 24) + + ((long)(bytes[idx+5] & 255) << 16) + + ((long)(bytes[idx+6] & 255) << 8) + + (bytes[idx+7] & 255); + } + + /** + * Parses an int value from the byte array. + * + * @param bytes The byte array to parse. + * @param idx The starting index of the parse in the byte array. + * @return parsed int value. + */ + public static int int4(byte[] bytes, int idx) { + return + ((bytes[idx ] & 255) << 24) + + ((bytes[idx+1] & 255) << 16) + + ((bytes[idx+2] & 255) << 8) + + ((bytes[idx+3] & 255) ); + } + + /** + * Parses a short value from the byte array. + * + * @param bytes The byte array to parse. + * @param idx The starting index of the parse in the byte array. + * @return parsed short value. + */ + public static short int2(byte[] bytes, int idx) { + return (short) + (((bytes[idx ] & 255) << 8) + + ((bytes[idx+1] & 255) )); + } + + /** + * Parses a float value from the byte array. + * + * @param bytes The byte array to parse. + * @param idx The starting index of the parse in the byte array. + * @return parsed float value. + */ + public static float float4(byte[] bytes, int idx) { + return Float.intBitsToFloat(int4(bytes, idx)); + } + + /** + * Parses a double value from the byte array. + * + * @param bytes The byte array to parse. + * @param idx The starting index of the parse in the byte array. + * @return parsed double value. + */ + public static double float8(byte[] bytes, int idx) { + return Double.longBitsToDouble(int8(bytes, idx)); + } + + /** + * Encodes a long value to the byte array. + * + * @param target The byte array to encode to. + * @param idx The starting index in the byte array. + * @param value The value to encode. + */ + public static void int8(byte[] target, int idx, long value) { + target[idx+0] = (byte) (value >>> 56); + target[idx+1] = (byte) (value >>> 48); + target[idx+2] = (byte) (value >>> 40); + target[idx+3] = (byte) (value >>> 32); + target[idx+4] = (byte) (value >>> 24); + target[idx+5] = (byte) (value >>> 16); + target[idx+6] = (byte) (value >>> 8); + target[idx+7] = (byte) value; + } + + /** + * Encodes a int value to the byte array. + * + * @param target The byte array to encode to. + * @param idx The starting index in the byte array. + * @param value The value to encode. + */ + public static void int4(byte[] target, int idx, int value) { + target[idx+0] = (byte) (value >>> 24); + target[idx+1] = (byte) (value >>> 16); + target[idx+2] = (byte) (value >>> 8); + target[idx+3] = (byte) value; + } + + /** + * Encodes a int value to the byte array. + * + * @param target The byte array to encode to. + * @param idx The starting index in the byte array. + * @param value The value to encode. + */ + public static void int2(byte[] target, int idx, int value) { + target[idx+0] = (byte) (value >>> 8); + target[idx+1] = (byte) value; + } + + /** + * Encodes a int value to the byte array. + * + * @param target The byte array to encode to. + * @param idx The starting index in the byte array. + * @param value The value to encode. + */ + public static void float4(byte[] target, int idx, float value) { + int4(target, idx, Float.floatToRawIntBits(value)); + } + + /** + * Encodes a int value to the byte array. + * + * @param target The byte array to encode to. + * @param idx The starting index in the byte array. + * @param value The value to encode. + */ + public static void float8(byte[] target, int idx, double value) { + int8(target, idx, Double.doubleToRawLongBits(value)); + } +}
5-datetypes.patch (text/plain, 23.3K) download Index: pgjdbc/org/postgresql/core/ProtocolConnection.java =================================================================== --- pgjdbc.orig/org/postgresql/core/ProtocolConnection.java +++ pgjdbc/org/postgresql/core/ProtocolConnection.java @@ -140,4 +140,12 @@ public interface ProtocolConnection { * @param useBinaryForOids The oids to request with binary encoding. */ public void setBinaryReceiveOids(BitSet useBinaryForOids); + + /** + * Returns true if server uses integer instead of double for binary + * date and time encodings. + * + * @return the server integer_datetime setting. + */ + public boolean getIntegerDateTimes(); } Index: pgjdbc/org/postgresql/core/v2/ProtocolConnectionImpl.java =================================================================== --- pgjdbc.orig/org/postgresql/core/v2/ProtocolConnectionImpl.java +++ pgjdbc/org/postgresql/core/v2/ProtocolConnectionImpl.java @@ -206,6 +206,11 @@ class ProtocolConnectionImpl implements // ignored for v2 connections } + public boolean getIntegerDateTimes() { + // not supported in v2 protocol + return false; + } + private String serverVersion; private int cancelPid; private int cancelKey; Index: pgjdbc/org/postgresql/core/v3/ConnectionFactoryImpl.java =================================================================== --- pgjdbc.orig/org/postgresql/core/v3/ConnectionFactoryImpl.java +++ pgjdbc/org/postgresql/core/v3/ConnectionFactoryImpl.java @@ -11,6 +11,7 @@ package org.postgresql.core.v3; import java.util.Properties; +import java.util.TimeZone; import java.sql.*; import java.io.IOException; @@ -99,7 +100,8 @@ public class ConnectionFactoryImpl exten { "database", database }, { "client_encoding", "UTF8" }, { "DateStyle", "ISO" }, - { "extra_float_digits", "2" } + { "extra_float_digits", "2" }, + { "TimeZone", createPostgresTimeZone() }, }; sendStartupPacket(newStream, params, logger); @@ -167,6 +169,32 @@ public class ConnectionFactoryImpl exten } } + /** + * Convert Java time zone to postgres time zone. + * All others stay the same except that GMT+nn changes to GMT-nn and + * vise versa. + * + * @return The current JVM time zone in postgresql format. + */ + private String createPostgresTimeZone() { + String tz = TimeZone.getDefault().getID(); + if (tz.length() <= 3 || !tz.startsWith("GMT")) { + return tz; + } + char sign = tz.charAt(3); + String start; + if (sign == '+') { + start = "GMT-"; + } else if (sign == '-') { + start = "GMT+"; + } else { + // unknown type + return tz; + } + + return start + tz.substring(4); + } + private PGStream enableSSL(PGStream pgStream, boolean requireSSL, Properties info, Logger logger) throws IOException, SQLException { if (logger.logDebug()) logger.debug(" FE=> SSLRequest"); @@ -507,6 +535,15 @@ public class ConnectionFactoryImpl exten else throw new PSQLException(GT.tr("Protocol error. Session setup failed."), PSQLState.PROTOCOL_VIOLATION); } + else if (name.equals("integer_datetimes")) + { + if (value.equals("on")) + protoConnection.setIntegerDateTimes(true); + else if (value.equals("off")) + protoConnection.setIntegerDateTimes(false); + else + throw new PSQLException(GT.tr("Protocol error. Session setup failed."), PSQLState.PROTOCOL_VIOLATION); + } break; Index: pgjdbc/org/postgresql/core/v3/ProtocolConnectionImpl.java =================================================================== --- pgjdbc.orig/org/postgresql/core/v3/ProtocolConnectionImpl.java +++ pgjdbc/org/postgresql/core/v3/ProtocolConnectionImpl.java @@ -210,6 +210,20 @@ class ProtocolConnectionImpl implements useBinaryForOids.or(oids); } + public void setIntegerDateTimes(boolean state) { + integerDateTimes = state; + } + + public boolean getIntegerDateTimes() { + return integerDateTimes; + } + + /** + * True if server uses integers for date and time fields. False if + * server uses double. + */ + private boolean integerDateTimes; + /** * Bit set that has a bit set for each oid which should be received * using binary format. Index: pgjdbc/org/postgresql/jdbc2/AbstractJdbc2Connection.java =================================================================== --- pgjdbc.orig/org/postgresql/jdbc2/AbstractJdbc2Connection.java +++ pgjdbc/org/postgresql/jdbc2/AbstractJdbc2Connection.java @@ -148,6 +148,19 @@ public abstract class AbstractJdbc2Conne binaryOids.set(Oid.INT8); binaryOids.set(Oid.FLOAT4); binaryOids.set(Oid.FLOAT8); + binaryOids.set(Oid.TIME); + binaryOids.set(Oid.DATE); + binaryOids.set(Oid.TIMETZ); + binaryOids.set(Oid.TIMESTAMP); + binaryOids.set(Oid.TIMESTAMPTZ); + } + // the pre 8.0 servers do not disclose their internal encoding for + // time fields so do not try to use them. + if (!haveMinimumCompatibleVersion("8.0")) { + binaryOids.clear(Oid.TIME); + binaryOids.clear(Oid.TIMETZ); + binaryOids.clear(Oid.TIMESTAMP); + binaryOids.clear(Oid.TIMESTAMPTZ); } // split for receive and send for better control @@ -156,6 +169,13 @@ public abstract class AbstractJdbc2Conne useBinaryReceiveForOids = new BitSet(); useBinaryReceiveForOids.or(binaryOids); + /* + * Does not pass unit tests because unit tests expect setDate to have + * millisecond accuracy whereas the binary transfer only supports + * date accuracy. + */ + useBinarySendForOids.clear(Oid.DATE); + protoConnection.setBinaryReceiveOids(useBinaryReceiveForOids); if (logger.logDebug()) @@ -165,6 +185,7 @@ public abstract class AbstractJdbc2Conne logger.debug(" prepare threshold = " + prepareThreshold); logger.debug(" types using binary send = " + oidsToString(useBinarySendForOids)); logger.debug(" types using binary receive = " + oidsToString(useBinaryReceiveForOids)); + logger.debug(" integer date/time = " + protoConnection.getIntegerDateTimes()); } // @@ -185,7 +206,8 @@ public abstract class AbstractJdbc2Conne } // Initialize timestamp stuff - timestampUtils = new TimestampUtils(haveMinimumServerVersion("7.4"), haveMinimumServerVersion("8.2")); + timestampUtils = new TimestampUtils(haveMinimumServerVersion("7.4"), haveMinimumServerVersion("8.2"), + !protoConnection.getIntegerDateTimes()); // Initialize common queries. commitQuery = getQueryExecutor().createSimpleQuery("COMMIT"); Index: pgjdbc/org/postgresql/jdbc2/AbstractJdbc2ResultSet.java =================================================================== --- pgjdbc.orig/org/postgresql/jdbc2/AbstractJdbc2ResultSet.java +++ pgjdbc/org/postgresql/jdbc2/AbstractJdbc2ResultSet.java @@ -21,6 +21,7 @@ import java.sql.*; import java.util.HashMap; import java.util.Iterator; import java.util.StringTokenizer; +import java.util.TimeZone; import java.util.Vector; import java.util.Calendar; import java.util.Locale; @@ -404,6 +405,22 @@ public abstract class AbstractJdbc2Resul if (wasNullFlag) return null; + if (isBinary(i)) { + int col = i - 1; + int oid = fields[col].getOID(); + TimeZone tz = cal == null ? null : cal.getTimeZone(); + if (oid == Oid.DATE) { + return connection.getTimestampUtils().toDateBin(tz, this_row[col]); + } else if (oid == Oid.TIMESTAMP || oid == Oid.TIMESTAMPTZ) { + // JDBC spec says getDate of Timestamp must be supported + return connection.getTimestampUtils().convertToDate(getTimestamp(i, cal), tz); + } else { + throw new PSQLException (GT.tr("Cannot convert the column of type {0} to requested type {1}.", + new Object[]{Oid.toString(oid), "date"}), + PSQLState.DATA_TYPE_MISMATCH); + } + } + if (cal != null) cal = (Calendar)cal.clone(); @@ -417,6 +434,22 @@ public abstract class AbstractJdbc2Resul if (wasNullFlag) return null; + if (isBinary(i)) { + int col = i - 1; + int oid = fields[col].getOID(); + TimeZone tz = cal == null ? null : cal.getTimeZone(); + if (oid == Oid.TIME || oid == Oid.TIMETZ) { + return connection.getTimestampUtils().toTimeBin(tz, this_row[col]); + } else if (oid == Oid.TIMESTAMP || oid == Oid.TIMESTAMPTZ) { + // JDBC spec says getTime of Timestamp must be supported + return connection.getTimestampUtils().convertToTime(getTimestamp(i, cal), tz); + } else { + throw new PSQLException (GT.tr("Cannot convert the column of type {0} to requested type {1}.", + new Object[]{Oid.toString(oid), "time"}), + PSQLState.DATA_TYPE_MISMATCH); + } + } + if (cal != null) cal = (Calendar)cal.clone(); @@ -430,6 +463,29 @@ public abstract class AbstractJdbc2Resul if (wasNullFlag) return null; + if (isBinary(i)) { + int col = i - 1; + int oid = fields[col].getOID(); + if (oid == Oid.TIMESTAMPTZ || oid == Oid.TIMESTAMP) { + boolean hasTimeZone = oid == Oid.TIMESTAMPTZ; + TimeZone tz = cal == null ? null : cal.getTimeZone(); + return connection.getTimestampUtils().toTimestampBin(tz, this_row[col], hasTimeZone); + } else { + // JDBC spec says getTimestamp of Time and Date must be supported + long millis; + if (oid == Oid.TIME || oid == Oid.TIMETZ) { + millis = getTime(i, cal).getTime(); + } else if (oid == Oid.DATE) { + millis = getDate(i, cal).getTime(); + } else { + throw new PSQLException (GT.tr("Cannot convert the column of type {0} to requested type {1}.", + new Object[]{Oid.toString(oid), "timestamp"}), + PSQLState.DATA_TYPE_MISMATCH); + } + return new Timestamp(millis); + } + } + if (cal != null) cal = (Calendar)cal.clone(); @@ -1862,6 +1918,10 @@ public abstract class AbstractJdbc2Resul if (obj == null) { return null; } + // hack to be compatible with text protocol + if (obj instanceof java.util.Date) { + return connection.getTimestampUtils().timeToString((java.util.Date) obj); + } return trimString(columnIndex, obj.toString()); } Index: pgjdbc/org/postgresql/jdbc2/AbstractJdbc2Statement.java =================================================================== --- pgjdbc.orig/org/postgresql/jdbc2/AbstractJdbc2Statement.java +++ pgjdbc/org/postgresql/jdbc2/AbstractJdbc2Statement.java @@ -17,6 +17,7 @@ import java.math.*; import java.sql.*; import java.util.ArrayList; import java.util.TimerTask; +import java.util.TimeZone; import java.util.Vector; import java.util.Calendar; @@ -3132,6 +3133,13 @@ public abstract class AbstractJdbc2State return; } + if (connection.binaryTransferSend(Oid.DATE)) { + byte[] val = new byte[4]; + TimeZone tz = cal != null ? cal.getTimeZone() : null; + connection.getTimestampUtils().toBinDate(tz, val, d); + preparedParameters.setBinaryParameter(i, val, Oid.DATE); + return; + } if (cal != null) cal = (Calendar)cal.clone(); Index: pgjdbc/org/postgresql/jdbc2/TimestampUtils.java =================================================================== --- pgjdbc.orig/org/postgresql/jdbc2/TimestampUtils.java +++ pgjdbc/org/postgresql/jdbc2/TimestampUtils.java @@ -17,6 +17,8 @@ import java.util.TimeZone; import java.util.SimpleTimeZone; import org.postgresql.PGStatement; +import org.postgresql.core.Oid; +import org.postgresql.util.ByteConverter; import org.postgresql.util.GT; import org.postgresql.util.PSQLState; import org.postgresql.util.PSQLException; @@ -26,9 +28,15 @@ import org.postgresql.util.PSQLException * Misc utils for handling time and date values. */ public class TimestampUtils { + /** + * Number of milliseconds in one day. + */ + private static final int ONEDAY = 24 * 3600 * 1000; + private StringBuffer sbuf = new StringBuffer(); private Calendar defaultCal = new GregorianCalendar(); + private final TimeZone defaultTz = defaultCal.getTimeZone(); private Calendar calCache; private int calCacheZone; @@ -36,9 +44,15 @@ public class TimestampUtils { private final boolean min74; private final boolean min82; - TimestampUtils(boolean min74, boolean min82) { + /** + * True if the backend uses doubles for time values. False if long is used. + */ + private final boolean usesDouble; + + TimestampUtils(boolean min74, boolean min82, boolean usesDouble) { this.min74 = min74; this.min82 = min82; + this.usesDouble = usesDouble; } private Calendar getCalendar(int sign, int hr, int min, int sec) { @@ -622,4 +636,277 @@ public class TimestampUtils { return '\0'; } + /** + * Returns the SQL Date object matching the given bytes with + * {@link Oid#DATE}. + * + * @param tz The timezone used. + * @param bytes The binary encoded date value. + * @return The parsed date object. + * @throws PSQLException If binary format could not be parsed. + */ + public Date toDateBin(TimeZone tz, byte[] bytes) throws PSQLException { + if (bytes.length != 4) { + throw new PSQLException(GT.tr("Unsupported binary encoding of {0}.", + "date"), PSQLState.BAD_DATETIME_FORMAT); + } + int days = ByteConverter.int4(bytes, 0); + if (tz == null) { + tz = defaultTz; + } + long secs = toJavaSecs(days * 86400L); + long millis = secs * 1000L; + int offset = tz.getOffset(millis); + return new Date(millis - offset); + } + + /** + * Returns the SQL Time object matching the given bytes with + * {@link Oid#TIME} or {@link Oid#TIMETZ}. + * + * @param tz The timezone used when received data is {@link Oid#TIME}, + * ignored if data already contains {@link Oid#TIMETZ}. + * @param bytes The binary encoded time value. + * @return The parsed time object. + * @throws PSQLException If binary format could not be parsed. + */ + public Time toTimeBin(TimeZone tz, byte[] bytes) throws PSQLException { + if ((bytes.length != 8 && bytes.length != 12)) { + throw new PSQLException(GT.tr("Unsupported binary encoding of {0}.", + "time"), PSQLState.BAD_DATETIME_FORMAT); + } + + long millis; + int timeOffset; + + if (usesDouble) { + double time = ByteConverter.float8(bytes, 0); + + millis = (long) (time * 1000); + } else { + long time = ByteConverter.int8(bytes, 0); + + millis = time / 1000; + } + + if (bytes.length == 12) { + timeOffset = ByteConverter.int4(bytes, 8); + timeOffset *= -1000; + } else { + if (tz == null) { + tz = defaultTz; + } + + timeOffset = tz.getOffset(millis); + } + + millis -= timeOffset; + return new Time(millis); + } + + /** + * Returns the SQL Timestamp object matching the given bytes with + * {@link Oid#TIMESTAMP} or {@link Oid#TIMESTAMPTZ}. + * + * @param tz The timezone used when received data is {@link Oid#TIMESTAMP}, + * ignored if data already contains {@link Oid#TIMESTAMPTZ}. + * @param bytes The binary encoded timestamp value. + * @param timestamptz True if the binary is in GMT. + * @return The parsed timestamp object. + * @throws PSQLException If binary format could not be parsed. + */ + public Timestamp toTimestampBin(TimeZone tz, byte[] bytes, boolean timestamptz) + throws PSQLException { + + if (bytes.length != 8) { + throw new PSQLException(GT.tr("Unsupported binary encoding of {0}.", + "timestamp"), PSQLState.BAD_DATETIME_FORMAT); + } + + long secs; + int nanos; + + if (usesDouble) { + double time = ByteConverter.float8(bytes, 0); + if (time == Double.POSITIVE_INFINITY) { + return new Timestamp(PGStatement.DATE_POSITIVE_INFINITY); + } else if (time == Double.NEGATIVE_INFINITY) { + return new Timestamp(PGStatement.DATE_NEGATIVE_INFINITY); + } + + secs = (long) time; + nanos = (int) ((time - secs) * 1000000); + } else { + long time = ByteConverter.int8(bytes, 0); + + // compatibility with text based receiving, not strictly necessary + // and can actually be confusing because there are timestamps + // that are larger than infinite + if (time == Long.MAX_VALUE) { + return new Timestamp(PGStatement.DATE_POSITIVE_INFINITY); + } else if (time == Long.MIN_VALUE) { + return new Timestamp(PGStatement.DATE_NEGATIVE_INFINITY); + } + + secs = time / 1000000; + nanos = (int) (time - secs * 1000000); + } + if (nanos < 0) { + secs--; + nanos += 1000000; + } + nanos *= 1000; + + secs = toJavaSecs(secs); + long millis = secs * 1000L; + if (!timestamptz) { + if (tz == null) { + tz = defaultTz; + } + millis -= tz.getOffset(millis); + } + + Timestamp ts = new Timestamp(millis); + ts.setNanos(nanos); + return ts; + } + + /** + * Extracts the date part from a timestamp. + * + * @param timestamp The timestamp from which to extract the date. + * @param tz The time zone of the date. + * @return The extracted date. + */ + public Date convertToDate(Timestamp timestamp, TimeZone tz) { + long millis = timestamp.getTime(); + // no adjustments for the inifity hack values + if (millis <= PGStatement.DATE_NEGATIVE_INFINITY || + millis >= PGStatement.DATE_POSITIVE_INFINITY) { + return new Date(millis); + } + if (tz == null) { + tz = defaultTz; + } + int offset = tz.getOffset(millis); + long timePart = millis % ONEDAY; + if (timePart + offset >= ONEDAY) { + millis += ONEDAY; + } + millis -= timePart; + millis -= offset; + + return new Date(millis); + } + + /** + * Extracts the time part from a timestamp. + * + * @param timestamp The timestamp from which to extract the time. + * @param tz The time zone of the time. + * @return The extracted time. + */ + public Time convertToTime(Timestamp timestamp, TimeZone tz) { + long millis = timestamp.getTime(); + if (tz == null) { + tz = defaultTz; + } + int offset = tz.getOffset(millis); + long low = - tz.getOffset(millis); + long high = low + ONEDAY; + if (millis < low) { + do { millis += ONEDAY; } while (millis < low); + } else if (millis >= high) { + do { millis -= ONEDAY; } while (millis > high); + } + + return new Time(millis); + } + + /** + * Returns the given time value as String matching what the + * current postgresql server would send in text mode. + */ + public String timeToString(java.util.Date time) { + long millis = time.getTime(); + if (millis <= PGStatement.DATE_NEGATIVE_INFINITY) { + return "-infinity"; + } + if (millis >= PGStatement.DATE_POSITIVE_INFINITY) { + return "infinity"; + } + return time.toString(); + } + + /** + * Converts the given postgresql seconds to java seconds. + * Reverse engineered by inserting varying dates to postgresql + * and tuning the formula until the java dates matched. + * See {@link #toPgSecs} for the reverse operation. + * + * @param secs Postgresql seconds. + * @return Java seconds. + */ + private static long toJavaSecs(long secs) { + // postgres epoc to java epoc + secs += 946684800L; + + // Julian/Gregorian calendar cutoff point + if (secs < -12219292800L) { // October 4, 1582 -> October 15, 1582 + secs += 86400 * 10; + if (secs < -14825808000L) { // 1500-02-28 -> 1500-03-01 + int extraLeaps = (int) ((secs + 14825808000L) / 3155760000L); + extraLeaps--; + extraLeaps -= extraLeaps / 4; + secs += extraLeaps * 86400L; + } + } + return secs; + } + + /** + * Converts the given java seconds to postgresql seconds. + * See {@link #toJavaSecs} for the reverse operation. + * The conversion is valid for any year 100 BC onwards. + * + * @param secs Postgresql seconds. + * @return Java seconds. + */ + private static long toPgSecs(long secs) { + // java epoc to postgres epoc + secs -= 946684800L; + + // Julian/Greagorian calendar cutoff point + if (secs < -13165977600L) { // October 15, 1582 -> October 4, 1582 + secs -= 86400 * 10; + if (secs < -15773356800L) { // 1500-03-01 -> 1500-02-28 + int years = (int) ((secs + 15773356800L) / -3155823050L); + years++; + years -= years/4; + secs += years * 86400; + } + } + + return secs; + } + + /** + * Converts the SQL Date to binary representation for {@link Oid#DATE}. + * + * @param tz The timezone used. + * @param bytes The binary encoded date value. + * @throws PSQLException If binary format could not be parsed. + */ + public void toBinDate(TimeZone tz, byte[] bytes, Date value) throws PSQLException { + long millis = value.getTime(); + + if (tz == null) { + tz = defaultTz; + } + millis += tz.getOffset(millis); + + long secs = toPgSecs(millis / 1000); + ByteConverter.int4(bytes, 0, (int) (secs / 86400)); + } + }
6-more-tests.patch (text/plain, 1.6K) download Index: pgjdbc/org/postgresql/test/jdbc2/ServerPreparedStmtTest.java =================================================================== --- pgjdbc.orig/org/postgresql/test/jdbc2/ServerPreparedStmtTest.java +++ pgjdbc/org/postgresql/test/jdbc2/ServerPreparedStmtTest.java @@ -53,6 +53,19 @@ public class ServerPreparedStmtTest exte TestUtil.closeDB(con); } + public void testEmptyResults() throws Exception + { + PreparedStatement pstmt = con.prepareStatement("SELECT * FROM testsps WHERE id = ?"); + ((PGStatement)pstmt).setUseServerPrepare(true); + for (int i=0; i<10; ++i) { + pstmt.setInt(1, -1); + ResultSet rs = pstmt.executeQuery(); + assertFalse(rs.next()); + rs.close(); + } + pstmt.close(); + } + public void testPreparedExecuteCount() throws Exception { PreparedStatement pstmt = con.prepareStatement("UPDATE testsps SET id = id + 44"); Index: pgjdbc/org/postgresql/test/jdbc2/StatementTest.java =================================================================== --- pgjdbc.orig/org/postgresql/test/jdbc2/StatementTest.java +++ pgjdbc/org/postgresql/test/jdbc2/StatementTest.java @@ -502,4 +502,15 @@ public class StatementTest extends TestC timer.cancel(); } } + + public void testResultSetTwice() throws SQLException + { + Statement stmt = con.createStatement(); + + ResultSet rs = stmt.executeQuery("select {fn abs(-2.3)} as abs "); + assertNotNull(rs); + + ResultSet rsOther = stmt.getResultSet(); + assertNotNull(rsOther); + } }
7-ide-testing.patch (text/plain, 2.2K) download Index: pgjdbc/org/postgresql/test/TestUtil.java =================================================================== --- pgjdbc.orig/org/postgresql/test/TestUtil.java +++ pgjdbc/org/postgresql/test/TestUtil.java @@ -9,6 +9,9 @@ */ package org.postgresql.test; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; import java.sql.*; import java.util.Properties; @@ -49,7 +52,7 @@ public class TestUtil */ public static String getServer() { - return System.getProperty("server"); + return System.getProperty("server", "localhost"); } /* @@ -57,7 +60,7 @@ public class TestUtil */ public static int getPort() { - return Integer.parseInt(System.getProperty("port")); + return Integer.parseInt(System.getProperty("port", System.getProperty("def_pgport"))); } /* @@ -65,12 +68,12 @@ public class TestUtil */ public static int getPrepareThreshold() { - return Integer.parseInt(System.getProperty("preparethreshold")); + return Integer.parseInt(System.getProperty("preparethreshold", "5")); } public static int getProtocolVersion() { - return Integer.parseInt(System.getProperty("protocolVersion")); + return Integer.parseInt(System.getProperty("protocolVersion", "0")); } /* @@ -102,7 +105,7 @@ public class TestUtil */ public static int getLogLevel() { - return Integer.parseInt(System.getProperty("loglevel")); + return Integer.parseInt(System.getProperty("loglevel", "0")); } /* @@ -120,6 +123,16 @@ public class TestUtil if (initialized) return; + Properties p = new Properties(); + try { + p.load(new FileInputStream("build.properties")); + p.load(new FileInputStream("build.local.properties")); + } catch (IOException ex) { + // ignore + } + p.putAll(System.getProperties()); + System.getProperties().putAll(p); + if (getLogLevel() > 0) { // Ant's junit task likes to buffer stdout/stderr and tends to run out of memory. // So we put debugging output to a file instead.
^ permalink raw reply [nested|flat] 3+ messages in thread

* Re: Binary transfer patches v15
@ 2011-09-21 22:44  Dave Cramer <pg@fastcrypt.com>
  parent: Mikko Tiihonen <mikko.tiihonen@nitorcreations.com>
  1 sibling, 0 replies; 3+ messages in thread

From: Dave Cramer @ 2011-09-21 22:44 UTC (permalink / raw)
  To: Mikko Tiihonen <mikko.tiihonen@nitorcreations.com>; +Cc: pgsql-jdbc

Mikko,

Great, I'll try this as soon as possible. I did have a problem with
running out of connections in the test. Did you ever see that ?


Dave Cramer

dave.cramer(at)credativ(dot)ca
http://www.credativ.ca




On Wed, Sep 21, 2011 at 6:22 PM, Mikko Tiihonen
<mikko.tiihonen@nitorcreations.com> wrote:
> I believe these are now ready for merging to cvs head. The patch set now
> passes all tests on jdk7u2 + postgres 9.1.0.
>
> Changes from last week:
> - Rebased to latest cvs
> - Fixed connection leak in jdbc3/DatabaseMetaDataTest.java
>   => now it is possible to run the unit tests with max_connections=2 in
> postgresql.conf
> - Fixed ForceBinaryTransfer bug in DatabaseEncodingTest
>   => Required a new field to Jdbc2ResultSet to keep the real statement alive
>      (Thanks to Oliver for the good analysis on the problem)
> - Fixed UpdateableResultTest.testUpdateStreams with binary transfers
>   => now ResultSet.refreshRow() informs lower level code that the results
> are for
>      updateable result set and should not use binary transfer
>
> Any comments on what still needs to be done before this is accepted?
>
> -Mikko
>
>
>
> --
> Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
> To make changes to your subscription:
> http://www.postgresql.org/mailpref/pgsql-jdbc
>
>



^ permalink  raw  reply  [nested|flat] 3+ messages in thread

* Re: Binary transfer patches v15
@ 2011-09-22 12:54  Dave Cramer <pg@fastcrypt.com>
  parent: Mikko Tiihonen <mikko.tiihonen@nitorcreations.com>
  1 sibling, 0 replies; 3+ messages in thread

From: Dave Cramer @ 2011-09-22 12:54 UTC (permalink / raw)
  To: Mikko Tiihonen <mikko.tiihonen@nitorcreations.com>; +Cc: pgsql-jdbc

Mikko,

As this is a development branch I have committed as is so that others
can easily build and test it. Thanks for the great work!

Dave Cramer

dave.cramer(at)credativ(dot)ca
http://www.credativ.ca




On Wed, Sep 21, 2011 at 6:22 PM, Mikko Tiihonen
<mikko.tiihonen@nitorcreations.com> wrote:
> I believe these are now ready for merging to cvs head. The patch set now
> passes all tests on jdk7u2 + postgres 9.1.0.
>
> Changes from last week:
> - Rebased to latest cvs
> - Fixed connection leak in jdbc3/DatabaseMetaDataTest.java
>   => now it is possible to run the unit tests with max_connections=2 in
> postgresql.conf
> - Fixed ForceBinaryTransfer bug in DatabaseEncodingTest
>   => Required a new field to Jdbc2ResultSet to keep the real statement alive
>      (Thanks to Oliver for the good analysis on the problem)
> - Fixed UpdateableResultTest.testUpdateStreams with binary transfers
>   => now ResultSet.refreshRow() informs lower level code that the results
> are for
>      updateable result set and should not use binary transfer
>
> Any comments on what still needs to be done before this is accepted?
>
> -Mikko
>
>
>
> --
> Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
> To make changes to your subscription:
> http://www.postgresql.org/mailpref/pgsql-jdbc
>
>



^ permalink  raw  reply  [nested|flat] 3+ messages in thread


end of thread, other threads:[~2011-09-22 12:54 UTC | newest]

Thread overview: 3+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2011-09-21 22:22 Binary transfer patches v15 Mikko Tiihonen <mikko.tiihonen@nitorcreations.com>
2011-09-21 22:44 ` Dave Cramer <pg@fastcrypt.com>
2011-09-22 12:54 ` Dave Cramer <pg@fastcrypt.com>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox