From f3e83073310e5fbafb142bb8d3cd1b03ed6088e9 Mon Sep 17 00:00:00 2001 From: Boris Kolpackov Date: Fri, 28 Oct 2011 11:18:54 +0200 Subject: Implement returning of auto id using RETURNING clause in PostgreSQL Before we used a separate SELECT lastval() query which was both inefficient and error-prone in cases where INSERT may cause triggers to override the last value. --- odb/pgsql/statement.cxx | 62 +++++++++++++++++++++++++++++++------------------ 1 file changed, 40 insertions(+), 22 deletions(-) (limited to 'odb/pgsql/statement.cxx') diff --git a/odb/pgsql/statement.cxx b/odb/pgsql/statement.cxx index 671bf61..e76e081 100644 --- a/odb/pgsql/statement.cxx +++ b/odb/pgsql/statement.cxx @@ -11,6 +11,7 @@ #include // object_not_persistent +#include #include #include #include @@ -442,19 +443,18 @@ namespace odb const Oid* types, size_t types_count, binding& data, - native_binding& native_data) + native_binding& native_data, + bool returning) : statement (conn, name, stmt, types, types_count), data_ (data), native_data_ (native_data), - id_cached_ (false) + returning_ (returning) { } bool insert_statement:: execute () { - id_cached_ = false; - bind_param (native_data_, data_); auto_handle h ( @@ -481,26 +481,44 @@ namespace odb translate_error (conn_, h); } - return true; - } - - unsigned long long insert_statement:: - id () - { - if (id_cached_) - return id_; - - auto_handle h ( - PQexecParams (conn_.handle (), "select lastval ()", 0, 0, 0, 0, 0, 1)); - - if (!is_good_result (h)) - translate_error (conn_, h); + if (returning_) + { + // Get the id value that was returned using the RETURNING clause. + // + const char* v (PQgetvalue (h, 0, 0)); - id_ = endian_traits::ntoh (*reinterpret_cast ( - PQgetvalue (h, 0, 0))); - id_cached_ = true; + // While the ODB auto id type can only be INT or BIGINT, handle the + // SMALLINT integer in case we are dealing with a custom schema. + // + switch (PQftype (h, 0)) + { + case int2_oid: + { + id_ = endian_traits::ntoh ( + *reinterpret_cast (v)); + break; + } + case int4_oid: + { + id_ = endian_traits::ntoh ( + *reinterpret_cast (v)); + break; + } + case int8_oid: + { + id_ = endian_traits::ntoh ( + *reinterpret_cast (v)); + break; + } + default: + { + assert (false); + break; + } + } + } - return id_; + return true; } // -- cgit v1.1