From: Mikko Tiihonen <mikko.tiihonen@nitorcreations.com>
To: pgsql-jdbc@postgresql.org
Subject: Binary transfer support [2/7] - core
Date: Fri, 16 Sep 2011 16:14:08 +0300
Message-ID: <4E734BA0.3080605@nitorcreations.com> (raw)
Attachments:binarytransfer-core.patch (text/plain, 31.4K) download
Index: pgjdbc.tmp8/build.xml
===================================================================
--- pgjdbc.tmp8.orig/build.xml+++ pgjdbc.tmp8/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.tmp8/doc/pgjdbc.xml
===================================================================
--- pgjdbc.tmp8.orig/doc/pgjdbc.xml+++ pgjdbc.tmp8/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.tmp8/org/postgresql/Driver.java.in
===================================================================
--- pgjdbc.tmp8.orig/org/postgresql/Driver.java.in+++ pgjdbc.tmp8/org/postgresql/Driver.java.in@@ -442,6 +442,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.tmp8/org/postgresql/core/BaseConnection.java
===================================================================
--- pgjdbc.tmp8.orig/org/postgresql/core/BaseConnection.java+++ pgjdbc.tmp8/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.tmp8/org/postgresql/core/ParameterList.java
===================================================================
--- pgjdbc.tmp8.orig/org/postgresql/core/ParameterList.java+++ pgjdbc.tmp8/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.tmp8/org/postgresql/core/QueryExecutor.java
===================================================================
--- pgjdbc.tmp8.orig/org/postgresql/core/QueryExecutor.java+++ pgjdbc.tmp8/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.tmp8/org/postgresql/core/v2/FastpathParameterList.java
===================================================================
--- pgjdbc.tmp8.orig/org/postgresql/core/v2/FastpathParameterList.java+++ pgjdbc.tmp8/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.tmp8/org/postgresql/core/v2/SimpleParameterList.java
===================================================================
--- pgjdbc.tmp8.orig/org/postgresql/core/v2/SimpleParameterList.java+++ pgjdbc.tmp8/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.tmp8/org/postgresql/core/v3/CompositeParameterList.java
===================================================================
--- pgjdbc.tmp8.orig/org/postgresql/core/v3/CompositeParameterList.java+++ pgjdbc.tmp8/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.tmp8/org/postgresql/core/v3/QueryExecutorImpl.java
===================================================================
--- pgjdbc.tmp8.orig/org/postgresql/core/v3/QueryExecutorImpl.java+++ pgjdbc.tmp8/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);
}
@@ -1829,7 +1870,6 @@ public class QueryExecutorImpl implement
if (logger.logDebug())
logger.debug(" <=BE DataRow");
-
break;
case 'E': // Error Response (response to pretty much everything; backend then skips until Sync)
@@ -1908,7 +1948,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.tmp8/org/postgresql/core/v3/SimpleParameterList.java
===================================================================
--- pgjdbc.tmp8.orig/org/postgresql/core/v3/SimpleParameterList.java+++ pgjdbc.tmp8/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.tmp8/org/postgresql/ds/common/BaseDataSource.java
===================================================================
--- pgjdbc.tmp8.orig/org/postgresql/ds/common/BaseDataSource.java+++ pgjdbc.tmp8/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;
@@ -388,6 +389,28 @@ public abstract class BaseDataSource imp
{
return tcpKeepAlive;
}
+ + /**+ * 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.
@@ -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.tmp8/org/postgresql/ds/common/PGObjectFactory.java
===================================================================
--- pgjdbc.tmp8.orig/org/postgresql/ds/common/PGObjectFactory.java+++ pgjdbc.tmp8/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.tmp8/org/postgresql/jdbc2/AbstractJdbc2Connection.java
===================================================================
--- pgjdbc.tmp8.orig/org/postgresql/jdbc2/AbstractJdbc2Connection.java+++ pgjdbc.tmp8/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.tmp8/org/postgresql/jdbc2/AbstractJdbc2ResultSet.java
===================================================================
--- pgjdbc.tmp8.orig/org/postgresql/jdbc2/AbstractJdbc2ResultSet.java+++ pgjdbc.tmp8/org/postgresql/jdbc2/AbstractJdbc2ResultSet.java@@ -1693,7 +1693,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 {
@@ -1852,6 +1852,15 @@ public abstract class AbstractJdbc2Resul
checkResultSet( columnIndex );
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 +2247,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 +2687,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)
Index: pgjdbc.tmp8/org/postgresql/jdbc2/AbstractJdbc2Statement.java
===================================================================
--- pgjdbc.tmp8.orig/org/postgresql/jdbc2/AbstractJdbc2Statement.java+++ pgjdbc.tmp8/org/postgresql/jdbc2/AbstractJdbc2Statement.java@@ -34,6 +34,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)
@@ -251,6 +254,26 @@ 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();+ PreparedStatement ps = connection.prepareStatement(p_sql, resultsettype, concurrency, getResultSetHoldability());+ ps.setMaxFieldSize(getMaxFieldSize());+ ps.setFetchSize(getFetchSize());+ ps.setFetchDirection(getFetchDirection());+ ResultSet rs = ps.executeQuery();++ // Close any existing resultsets associated with this statement.+ while (firstUnclosedResult != null)+ {+ if (firstUnclosedResult.getResultSet() != null)+ firstUnclosedResult.getResultSet().close();+ firstUnclosedResult = firstUnclosedResult.getNext();+ }++ 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);
@@ -506,7 +529,17 @@ 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);+ }+
StatementResultHandler handler = new StatementResultHandler();
result = null;
connection.getQueryExecutor().execute(queryToExecute,
Index: pgjdbc.tmp8/org/postgresql/test/TestUtil.java
===================================================================
--- pgjdbc.tmp8.orig/org/postgresql/test/TestUtil.java+++ pgjdbc.tmp8/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
{
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-jdbc@postgresql.org
Cc: mikko.tiihonen@nitorcreations.com
Subject: Re: Binary transfer support [2/7] - core
In-Reply-To: <4E734BA0.3080605@nitorcreations.com>
References: <4E734BA0.3080605@nitorcreations.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
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