[odb-users] Re: lastval as primary key of the newly inserted entity returns wrong value

Konstantin Mikhailov ekimka at gmail.com
Fri Oct 28 02:50:24 EDT 2011

Unfortunatelly we must use audit triggers and have no chance to
switch to the different orm. So, after digging a sources we
invent a quick workaround (please note -- we're using the 'id' of
type bigint in all our tables as primary key - so the returning
clause is hardcoded).

 --- statement.cxx.orig  2011-10-28 11:23:44.626672918 +0600
+++ statement.cxx       2011-10-28 11:41:54.622687716 +0600
@@ -443,7 +443,7 @@
                      size_t types_count,
                      binding& data,
                      native_binding& native_data)
-        : statement (conn, name, stmt, types, types_count),
+        : statement (conn, name, stmt + " returning id", types,
          data_ (data),
          native_data_ (native_data),
          id_cached_ (false)
@@ -481,6 +481,10 @@
        translate_error (conn_, h);

+      id_ = endian_traits::ntoh (*reinterpret_cast<unsigned long long*> (
+                                   PQgetvalue (h, 0, 0)));
+      id_cached_ = true;
      return true;

On Fri, Oct 28, 2011 at 10:58 AM, Konstantin Mikhailov <ekimka at gmail.com>wrote:

> It looks like the odb trying to use lastval posgresql function call
> (odb\pgsql\statement.cxx, l. 485) to obtain the primary key value
> of the newly inserted entity when using id with auto pragma.
> In case of any triggers involved into entity insertion (for example audit
> triggers which can insert an audit record in different table(s)) and
> accessing another (or even the same sequence used to generate
> primary key) the odb behaviour can lead to very big problem. It
> returns and assign to the persistent object wrong id.
> The only workaround in the current version (1.6.0) - do not use the
> auto pragma with id column if you have the triggers.

More information about the odb-users mailing list