From 51a01cfebf933d270bf7b7fadb0fb3ca3b7a4cd5 Mon Sep 17 00:00:00 2001 From: Michael Shepanski Date: Thu, 6 Nov 2014 16:33:35 +1100 Subject: Implement {query,execute}_{one,value}() shortcut functions Useful in situations where the query is know to return at most one element (*_one) or exactly one element (*_value). --- query/driver.cxx | 50 +++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 41 insertions(+), 9 deletions(-) (limited to 'query/driver.cxx') diff --git a/query/driver.cxx b/query/driver.cxx index fbd148d..aec8ac8 100644 --- a/query/driver.cxx +++ b/query/driver.cxx @@ -22,17 +22,21 @@ typedef odb::query query; typedef odb::result result; static void -print (result& r) +print (person& p) { - for (result::iterator i (r.begin ()); i != r.end (); ++i) - { - cout << i->first () << " "; + cout << p.first () << " "; - if (!i->middle ().null ()) - cout << i->middle ().get () << " "; + if (!p.middle ().null ()) + cout << p.middle ().get () << " "; - cout << i->last () << " " << i->age () << endl; - } + cout << p.last () << " " << p.age () << endl; +} + +static void +print (result& r) +{ + for (result::iterator i (r.begin ()); i != r.end (); ++i) + print (*i); cout << endl; } @@ -90,7 +94,6 @@ main (int argc, char* argv[]) // /* person p ("", "", 0); - for (result::iterator i (r.begin ()); i != r.end (); ++i) { i.load (p); @@ -103,6 +106,35 @@ main (int argc, char* argv[]) t.commit (); } + // Use query_one() as a shortcut when there's no more than one element + // in the result. + // + { + transaction t (db->begin ()); + + auto_ptr p (db->query_one (query::age == 21)); + + if (p.get () != 0) + { + print (*p); + cout << endl; + } + + // Or we can load the state into an existing object. + // + /* + person p ("", "", 0); + + if (db->query_one (query::age == 21, p)) + { + print (p); + cout << endl; + } + */ + + t.commit (); + } + // Query that shows how to combine expressions with &&, ||, and ! // as well as use paranthesis to control evaluation order. // -- cgit v1.1