From: Adam Rauch <adam@labkey.com>
To: pgsql-jdbc@postgresql.org
Subject: Recent backward compatibility break in PreparedStatement.setObject()
Date: Wed, 30 Dec 2015 13:45:17 -0800
Message-ID: <5684506D.4040006@labkey.com> (raw)
List-Unsubscribe: <mailto:majordomo@postgresql.org?body=unsub%20pgsql-jdbc>
The PostgreSQL JDBC driver recently changed PreparedStatement behavior
with calls such as setObject(index, value, Types.VARCHAR). Previously,
the driver would call value.toString() before binding all VARCHAR
values... meaning any object could be passed as "value." In recent
updates (e.g., 9.4.1207), most non-String values now result in an exception:
Exception in thread "main" org.postgresql.util.PSQLException:
Cannot convert an instance of XXX to type String
at
org.postgresql.jdbc.PgStatement.cannotCastException(PgStatement.java:1813)
at
org.postgresql.jdbc.PgStatement.cannotCastException(PgStatement.java:1809)
at
org.postgresql.jdbc.PgStatement.castToString(PgStatement.java:1805)
at org.postgresql.jdbc.PgStatement.setObject(PgStatement.java:1540)
at org.postgresql.jdbc.PgStatement.setObject(PgStatement.java:1818)
at PGTest.main(PGTest.java:25)
This seems to have broken during the refactor to support binary transfer
for setObject(), https://github.com/pgjdbc/pgjdbc/issues/328. Was the
behavior change intentional? If so, it should probably be documented
(e.g., I didn't see any mention in the change log). If not, I'd suggest
going back to calling value.toString() for all types. I'm sure ours is
not the only application that relies on this long-standing (>10 years)
PostgreSQL JDBC behavior. FWIW, other JDBC drivers call toString() in
this situation.
Here's a contrived example that demonstrates the behavior change. This
code snippet runs fine in 1201 but fails with the exception above in 1207.
Object param =new Object() {public String toString() {return "tables";}};
try (PreparedStatement stmt = conn.prepareStatement("SELECT *FROM information_schema.tables WHERE table_name = ?"))
{
stmt.setObject(1, param, Types.VARCHAR);
try (ResultSet rs = stmt.executeQuery())
{
while (rs.next())
System.out.println(rs.getString(1));
}
}
Thanks,
Adam
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: adam@labkey.com
Subject: Re: Recent backward compatibility break in PreparedStatement.setObject()
In-Reply-To: <5684506D.4040006@labkey.com>
References: <5684506D.4040006@labkey.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