[odb-users] Programmatically generating ODB queries

Boris Kolpackov boris at codesynthesis.com
Mon Sep 3 09:05:23 EDT 2012


Hi Oded,

Oded Arbel <oded at geek.co.il> writes:

> I have (1) working fine, and I'm having a bit of trouble with 2 and 3
> because I'm finding it hard to do something like reflection on the ODB
> types.

That's probably because they don't provide any support for reflection
(and we have no plans to add it).


> So - is this completely crazy and there is a simple way to go about this?

I am not sure about crazy, but it looks completely incomprehensible to me.
The way I would do it is along these lines:

template <typename O, typename T>
struct member_expr
{
  virtual 
  ~member_expr ();

  virtual odb::query<O>
  create (std::string const& op, const T& rhs) = 0;
};

template <typename O, typename T, typename M>
struct member_expr_impl: member_expr<O, T>
{
  member_expr_impl (const M& m): m_ (m) {}

  virtual odb::query<O> 
  create (std::string const& op, const T& rhs) = 0
  {
    return m_ + op + odb::query<O>::_val (rhs);
  }

  const M& m_;
};

template <typename O, typename T, typename M>
std::unique_ptr<member_expr> 
make_member_expr (const M& m)
{
  return std::unique_ptr<member_expr> (
    new member_expr_impl<O, T, M> (m));
}

std::map<std::string, std::unique_ptr<member_expr>> map;

map["name"] = make_member_expr<Employee, std::string> (odb::query<Employee>::name);
map["age"] = make_member_expr<Employee, unsigned short> (odb::query<Employee>::age);

member_expr& ae = *map["age"];
odb::query<Employee> q1 = ae.create ("<", 30);

member_expr& ne = *map["name"];
odb::query<Employee> q2 = ne.create ("=", "John");

odb::query<Employee> q (q1 && q2);

Note that I haven't tried this code myself so making sure that it works
is left as an exercise for the reader.

Boris



More information about the odb-users mailing list