From 9cfb5dcf71a5cb40b0b2fa6e7b8b633ba0ed5336 Mon Sep 17 00:00:00 2001 From: Boris Kolpackov Date: Wed, 15 Sep 2010 18:13:58 +0200 Subject: Expand the hello example --- hello/driver.cxx | 72 +++++++++++++++++++++++++++++++++++++++++++++++--------- hello/person.hxx | 9 ++++++- 2 files changed, 69 insertions(+), 12 deletions(-) (limited to 'hello') diff --git a/hello/driver.cxx b/hello/driver.cxx index 2c3edff..b14ced8 100644 --- a/hello/driver.cxx +++ b/hello/driver.cxx @@ -23,31 +23,39 @@ main (int argc, char* argv[]) { auto_ptr db (create_database (argc, argv)); + unsigned long john_id, jane_id, joe_id; + // Create a few persistent person objects. // { - person john_doe ("John", "Doe", 29); - person jane_doe ("Jane", "Doe", 28); - person joe_dirt ("Joe", "Dirt", 31); + person john ("John", "Doe", 33); + person jane ("Jane", "Doe", 32); + person joe ("Joe", "Dirt", 30); transaction t (db->begin_transaction ()); - db->persist (john_doe); - db->persist (jane_doe); - db->persist (joe_dirt); + db->persist (john); + db->persist (jane); + db->persist (joe); t.commit (); + + // Save object ids for later use. + // + john_id = john.id (); + jane_id = jane.id (); + joe_id = joe.id (); } - // Say hello to those under 30. + typedef odb::query query; + typedef odb::result result; + + // Say hello to those over 30. // { - typedef odb::query query; - typedef odb::result result; - transaction t (db->begin_transaction ()); - result r (db->query (query::age < 30)); + result r (db->query (query::age > 30)); for (result::iterator i (r.begin ()); i != r.end (); ++i) { @@ -56,6 +64,48 @@ main (int argc, char* argv[]) t.commit (); } + + // Joe Dirt just had a birthday, so update his age. + // + { + transaction t (db->begin_transaction ()); + + auto_ptr joe (db->load (joe_id)); + joe->age (joe->age () + 1); + db->store (*joe); + + t.commit (); + } + + /* + // Alternative implementation without using the id. + // + { + transaction t (db->begin_transaction ()); + + result r (db->query (query::first == "Joe" && + query::last == "Dirt")); + + result::iterator i (r.begin ()); + + if (i != r.end ()) + { + auto_ptr joe (*i); + joe->age (joe->age () + 1); + db->store (*joe); + } + + t.commit (); + } + */ + + // John Doe is no longer in our database. + // + { + transaction t (db->begin_transaction ()); + db->erase (john_id); + t.commit (); + } } catch (const odb::exception& e) { diff --git a/hello/person.hxx b/hello/person.hxx index 4730ff0..7a939c7 100644 --- a/hello/person.hxx +++ b/hello/person.hxx @@ -10,8 +10,9 @@ #include #pragma db object -struct person +class person { +public: person (const std::string& first, const std::string& last, unsigned short age) @@ -37,6 +38,12 @@ struct person return age_; } + void + age (unsigned short age) + { + age_ = age; + } + public: unsigned long id () const -- cgit v1.1