Received: from maia.hub.org (unknown [200.46.204.183]) by mail.postgresql.org (Postfix) with ESMTP id CF6E9632A2C for ; Fri, 1 May 2009 17:42:57 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.183]) (amavisd-maia, port 10024) with ESMTP id 35550-07 for ; Fri, 1 May 2009 17:42:55 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from mail3.videx.com (mail3.videx.com [65.122.251.14]) by mail.postgresql.org (Postfix) with ESMTP id 3C1296329AA for ; Fri, 1 May 2009 17:42:53 -0300 (ADT) Received: from [191.10.58.1] ([191.10.58.1]) (authenticated user adamb@videx.com) by mail3.videx.com for pgsql-jdbc@postgresql.org; Fri, 1 May 2009 13:42:50 -0700 Message-ID: <49FB5EC5.40307@videx.com> Date: Fri, 01 May 2009 13:42:45 -0700 From: Adam B User-Agent: Thunderbird 2.0.0.21 (X11/20090318) MIME-Version: 1.0 To: pgsql-jdbc@postgresql.org Subject: Re: A basic Statement.getGeneratedKeys() implementation (patch attached) References: <49FB5E2D.4020105@videx.com> In-Reply-To: <49FB5E2D.4020105@videx.com> Content-Type: multipart/mixed; boundary="------------040709000708040204070708" X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=0 tagged_above=0 required=5 tests=none X-Spam-Level: X-Archive-Number: 200905/6 X-Sequence-Number: 19556 This is a multi-part message in MIME format. --------------040709000708040204070708 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: quoted-printable As usual I forgot to attach it! Here you go=2E Adam B wrote=3A =3E Hello all=2C =3E =3E Our webapp relies heavily on JDBC=27s Statement=2EgetGeneratedKeys=28= =29=20 =3E abstraction=2E We are investigating switching from Mysql to Postgre so= I=20 =3E created a basic implementation of this feature in the 8=2E3-604 version= of=20 =3E the driver=2E The diff patch is attached=2E On Linux you can apply it= by=3A =3E =3E 1=29 Download and extract=3A postgresql-jdbc-8=2E3-604=2Esrc=2Etar=2Egz= =3E 2=29 Copy the attached patch into the folder =3E 3=29 Open a terminal to the folder and run=3A patch -p1 =3C=20 =3E getGeneratedKeys=2Epatch =3E 4=29 ant jar =3E =3E Here=27s an example usage =28nothing special=29=3A =3E =3E PreparedStatement ps =3D con=2EprepareStatement=28=22INSERT INTO fo= o =28name=29=20 =3E VALUES =28=3F=29=22=2C Statement=2ERETURN=5FGENERATED=5FKEYS=29=3B =3E ps=2EsetString=281=2C =22sweet!=22=29=3B =3E ps=2EexecuteUpdate=28=29=3B =3E ResultSet rs =3D ps=2EgetGeneratedKeys=28=29=3B =3E rs=2Enext=28=29=3B =3E System=2Eout=2Eprintln=28rs=2EgetInt=281=29=29=3B =3E ps=2Eclose=28=29=3B =3E =3E The patch modifies the following files=3A =3E org/postgresql/core/Query=2Ejava =3E org/postgresql/core/v2/V2Query=2Ejava =3E org/postgresql/core/v3/CompositeQuery=2Ejava =3E org/postgresql/core/v3/SimpleQuery=2Ejava =3E org/postgresql/jdbc2/AbstractJdbc2Statement=2Ejava =3E org/postgresql/jdbc3/AbstractJdbc3Connection=2Ejava =3E org/postgresql/jdbc3/AbstractJdbc3Statement=2Ejava =3E =3E Limitations of this implementation=3A =3E * You must use PreparedStatement =28not Statement=29 =3E * Your table can only have one auto generated column =3E * Column must have default value LIKE =27nextval=28=25seq=25=29=27= =28this is=20 =3E the case of SERIAL columns=29 =3E * Must use JDBC3 or higher have =28ie =3E=3D java 1=2E5=29 =3E * Must be running against a version of Postgre that supports the=20= =3E =22RETURNING=22 clause =28eg INSERT INTO foo =28name=29 VALUES=28=27hel= lo=27=29 RETURNING=20 =3E foo=5Fid=29 =3E =20 =3E I=27m hoping this patch will be included in the official driver=2E I= =20 =3E realize that it has some limitations but it will cover 95=25 of user ne= eds=2E =3E =3E Let me know what you think=2E Improvements are welcome=2E =3E - Adam =3E =3E =3E =3E Videx Inc=2E 1105 N=2E E=2E Circle Blvd=2E Corvallis OR 97330 =28541=29= 758-0521 =3E CONFIDENTIAL COMMUNICATION=3A The email message and any attachments are= intended only for the addressee=2E They may be privileged=2C confidential= =2C and protected from disclosure=2E If you are not the intended recipient= =2C any dissemination=2C distribution=2C or copying is expressly prohibited= =2E If you received this email message in error=2C please notify the sende= r immediately by replying to this e-mail message or by telephone =3E =3E =3E =20 Videx Inc=2E 1105 N=2E E=2E Circle Blvd=2E Corvallis OR 97330 =28541=29 758= -0521 CONFIDENTIAL COMMUNICATION=3A The email message and any attachments are int= ended only for the addressee=2E They may be privileged=2C confidential=2C= and protected from disclosure=2E If you are not the intended recipient=2C= any dissemination=2C distribution=2C or copying is expressly prohibited=2E= If you received this email message in error=2C please notify the sender i= mmediately by replying to this e-mail message or by telephone --------------040709000708040204070708 Content-Type: text/x-patch; name="getGeneratedKeys.patch" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="getGeneratedKeys.patch" diff -x .svn -rupN orig/org/postgresql/core/Query.java new/org/postgresql/core/Query.java --- orig/org/postgresql/core/Query.java 2008-01-07 22:56:27.000000000 -0800 +++ new/org/postgresql/core/Query.java 2009-05-01 11:11:08.000000000 -0700 @@ -46,7 +46,11 @@ public interface Query { */ String toString(ParameterList parameters); - /** + ///adamb getGeneratedKeys support + /**return true if this query is an INSERT with a RETURNING clause (eg INSERT INTO foo RETURNING foo_id)*/ + boolean isReturningInsert(); + + /** * Close this query and free any server-side resources associated * with it. The resources may not be immediately deallocated, but * closing a Query may make the deallocation more prompt. diff -x .svn -rupN orig/org/postgresql/core/v2/V2Query.java new/org/postgresql/core/v2/V2Query.java --- orig/org/postgresql/core/v2/V2Query.java 2008-01-07 22:56:27.000000000 -0800 +++ new/org/postgresql/core/v2/V2Query.java 2009-05-01 11:11:58.000000000 -0700 @@ -97,6 +97,12 @@ class V2Query implements Query { return sbuf.toString(); } + ///adamb getGeneratedKeys support + public boolean isReturningInsert() + { + throw new UnsupportedOperationException("Must use JDBC3 for this getGeneratedKeys hack"); + } + public void close() { } diff -x .svn -rupN orig/org/postgresql/core/v3/CompositeQuery.java new/org/postgresql/core/v3/CompositeQuery.java --- orig/org/postgresql/core/v3/CompositeQuery.java 2008-01-07 22:56:27.000000000 -0800 +++ new/org/postgresql/core/v3/CompositeQuery.java 2009-05-01 10:54:30.000000000 -0700 @@ -52,7 +52,13 @@ class CompositeQuery implements V3Query subqueries[i].close(); } - public SimpleQuery[] getSubqueries() { + ///adamb getGeneratedKeys support + public boolean isReturningInsert() + { + return subqueries[0].isReturningInsert(); + } + + public SimpleQuery[] getSubqueries() { return subqueries; } diff -x .svn -rupN orig/org/postgresql/core/v3/SimpleQuery.java new/org/postgresql/core/v3/SimpleQuery.java --- orig/org/postgresql/core/v3/SimpleQuery.java 2008-01-07 22:56:27.000000000 -0800 +++ new/org/postgresql/core/v3/SimpleQuery.java 2009-05-01 11:12:55.000000000 -0700 @@ -54,7 +54,23 @@ class SimpleQuery implements V3Query { unprepare(); } - // + ///adamb getGeneratedKeys support + public boolean isReturningInsert() + { + if (fragments[0].contains("INSERT INTO") //this check will catch most and avoid the new String instance in the second condition + || fragments[0].toUpperCase().contains("INSERT INTO")) + { + for (String fragment: fragments) + { + if (fragment.contains("RETURNING ")) + return true; + } + } + + return false; + } + + // // V3Query // @@ -121,7 +137,7 @@ class SimpleQuery implements V3Query { encodedStatementName = null; } - private final String[] fragments; + private final String[] fragments; private String statementName; private byte[] encodedStatementName; private PhantomReference cleanupRef; diff -x .svn -rupN orig/org/postgresql/jdbc2/AbstractJdbc2Statement.java new/org/postgresql/jdbc2/AbstractJdbc2Statement.java --- orig/org/postgresql/jdbc2/AbstractJdbc2Statement.java 2008-04-02 10:06:04.000000000 -0700 +++ new/org/postgresql/jdbc2/AbstractJdbc2Statement.java 2009-05-01 11:23:55.000000000 -0700 @@ -301,11 +301,24 @@ public abstract class AbstractJdbc2State executeWithFlags(0); return 0; } - if (executeWithFlags(QueryExecutor.QUERY_NO_RESULTS)) - throw new PSQLException(GT.tr("A result was returned when none was expected."), - PSQLState.TOO_MANY_RESULTS); + ///adamb getGeneratedKeys support: + //if the query has the RETURNING clause then the caller will likely want the result set + else if (preparedQuery.isReturningInsert()) + { + if (!executeWithFlags(0)) + throw new PSQLException(GT.tr("Results from RETURNING clause were not given"), PSQLState.UNEXPECTED_ERROR); - return getUpdateCount(); + //INSERT statements always return 1 (returning getUpdateCount() doesn't seem to work due to the RETURNING clause) + return 1; + } + else + { + if (executeWithFlags(QueryExecutor.QUERY_NO_RESULTS)) + throw new PSQLException(GT.tr("A result was returned when none was expected."), + PSQLState.TOO_MANY_RESULTS); + + return getUpdateCount(); + } } /* diff -x .svn -rupN orig/org/postgresql/jdbc3/AbstractJdbc3Connection.java new/org/postgresql/jdbc3/AbstractJdbc3Connection.java --- orig/org/postgresql/jdbc3/AbstractJdbc3Connection.java 2008-01-07 22:56:29.000000000 -0800 +++ new/org/postgresql/jdbc3/AbstractJdbc3Connection.java 2009-05-01 11:17:21.000000000 -0700 @@ -9,7 +9,7 @@ */ package org.postgresql.jdbc3; -import java.util.Properties; +import java.util.*; import java.sql.*; import org.postgresql.util.PSQLException; @@ -346,15 +346,77 @@ public abstract class AbstractJdbc3Conne * @since 1.4 */ public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) - throws SQLException + throws SQLException { + ///adamb getGeneratedKeys support if (autoGeneratedKeys != Statement.NO_GENERATED_KEYS) - throw new PSQLException(GT.tr("Returning autogenerated keys is not supported."), PSQLState.NOT_IMPLEMENTED); - return prepareStatement(sql); + { + //get the table being inserted into + String tableName = parseInsertTableName(sql); + if (tableName == null) + throw new PSQLException(GT.tr("Unable to parse table name from INSERT statement"), PSQLState.SYNTAX_ERROR); + + Statement st = createStatement(); + try + { + String columnQuery = "SELECT column_name FROM information_schema.columns WHERE table_name = '" + + tableName + "' AND column_default LIKE 'nextval(%seq%)'"; + + ResultSet rs = st.executeQuery(columnQuery); + + if (rs.next()) + { + String serialColumn = rs.getString(1); + + if (!rs.next()) + { + //add the RETURNING clause + return prepareStatement(sql + " RETURNING " + serialColumn); + } + //else there are more results so it's ambiguous + } + + throw new PSQLException("Auto-increment column for `" + tableName + "` could not be determined unambiguously." + + " In other words the following query did not return exactly 1 row: " + columnQuery, PSQLState.SYNTAX_ERROR); + } + finally + { + st.close(); + } + } + else + return prepareStatement(sql); } + /**extract the table name from an INSERT INTO statement. + @return null if not found. the table name will be all lower case.*/ + private String parseInsertTableName(String sql) + { + final String insert_into = "insert into "; - /** + sql = sql.toLowerCase(); + + int start = sql.indexOf(insert_into) + insert_into.length(); + if (start != -1) + { + int spc = sql.indexOf(' ', start); + int paren = sql.indexOf('(', start); + int end; + if (spc < paren && spc != -1) + end = spc; + else + end = paren; + + if (end != -1) + { + return sql.substring(start, end).trim(); + } + } + + return null; + } + + /** * Creates a default PreparedStatement object capable * of returning the auto-generated keys designated by the given array. * This array contains the indexes of the columns in the target diff -x .svn -rupN orig/org/postgresql/jdbc3/AbstractJdbc3Statement.java new/org/postgresql/jdbc3/AbstractJdbc3Statement.java --- orig/org/postgresql/jdbc3/AbstractJdbc3Statement.java 2008-01-07 22:56:29.000000000 -0800 +++ new/org/postgresql/jdbc3/AbstractJdbc3Statement.java 2009-05-01 11:15:17.000000000 -0700 @@ -106,7 +106,9 @@ public abstract class AbstractJdbc3State */ public ResultSet getGeneratedKeys() throws SQLException { - return createDriverResultSet(new Field[0], new Vector()); + //return createDriverResultSet(new Field[0], new Vector()); + ///adamb getGeneratedKeys support + return getResultSet(); } /** --------------040709000708040204070708--