[odb-users] Postgresql column with default value

Boris Kolpackov boris at codesynthesis.com
Wed Dec 4 03:02:29 EST 2013


Hi Mikhail,

Mikhail Tomilov <Mikhail.Tomilov at infotecs.ru> writes:

> We considered to use callbacks but didn't get it worked the way we
> want (described above).

Unfortunately there is still no support for the RETURNING clause
in ODB. It is on our TODO list but is not yet implemented.

For now, the workaround is the same as what I have described in
my previous reply:

http://www.codesynthesis.com/pipermail/odb-users/2013-July/001457.html

That is, send the NULL value on persist() and load the computed
data member in a callback. Unfortunately, this will require a
separate query, but that's the best that can be done until proper
support for RETURNING is implemented.

Here is an outline:

// file: test.hxx
//

#include <odb/nullable.hxx>

#pragma db object callback(init)
struct test
{
  #pragma id auto
  long long id;

  odb::nullable<std::string> some_field;

  void
  init (odb::callback_event, odb::database&) const;
};

#pragma db view object(test)
struct test_computed
{
  std::string some_field;
};


// file: test.cxx
//

void test::
init (odb::callback_event e, odb::database& db) const
{
  switch (e)
  {
  case odb::callback_event::pre_persist:
    {
      // Reset some_field to NULL so that the default value is
      // assigned by the database.
      //
      const_cast<test*> (this)->some_field.reset ();
      break;
    }
  case odb::callback_event::post_persist:
    {
      // Load the computed fields using the test_computed view.
      //
      test_computed v;
      db.query<test_computed> (
        odb::query<test_computed>::id == id).begin ().load (v);
      const_cast<test*> (this)->some_field = v.some_field;
      break;
    }
  }
}

You can further optimize this by preparing and caching the query
used to load computed members (Section 4.5, "Prepared Queries").

Boris



More information about the odb-users mailing list