From fe69aa1a2b29e577b86026f7bb56a19f5b3bdfef Mon Sep 17 00:00:00 2001 From: Boris Kolpackov Date: Tue, 30 Nov 2010 18:13:45 +0200 Subject: Add container example --- container/driver.cxx | 120 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 container/driver.cxx (limited to 'container/driver.cxx') diff --git a/container/driver.cxx b/container/driver.cxx new file mode 100644 index 0000000..07b3bd9 --- /dev/null +++ b/container/driver.cxx @@ -0,0 +1,120 @@ +// file : container/driver.cxx +// author : Boris Kolpackov +// copyright : not copyrighted - public domain + +#include // std::auto_ptr +#include + +#include +#include + +#include "database.hxx" // create_database + +#include "person.hxx" +#include "person-odb.hxx" + +using namespace std; +using namespace odb; + +void +print (const person& p) +{ + cout << p.first () << " " << p.last () << endl; + + // Print nicknames. + // + for (person::name_list::const_iterator i (p.nicknames ().begin ()); + i != p.nicknames ().end (); ++i) + { + cout << " nickname: " << *i << endl; + } + + // Print emails. + // + for (person::email_set::const_iterator i (p.emails ().begin ()); + i != p.emails ().end (); ++i) + { + cout << " email: " << *i << endl; + } + + // Print weights. + // + for (person::age_weight_map::const_iterator i (p.age_weight ().begin ()); + i != p.age_weight ().end (); ++i) + { + cout << " weight at " << i->first << ": " << i->second << endl; + } +} + +int +main (int argc, char* argv[]) +{ + try + { + auto_ptr db (create_database (argc, argv)); + + unsigned long id; + + // Create a persistent person objects. + // + { + person joe ("Joe", "Dirt"); + + joe.nicknames ().push_back ("JD"); + joe.nicknames ().push_back ("Squeaky"); + + joe.emails ().insert ("joe@example.com"); + joe.emails ().insert ("joe.dirt@example.com"); + + joe.age_weight ()[5] = 15.6F; + joe.age_weight ()[10] = 23.3F; + joe.age_weight ()[15] = 29.8F; + + transaction t (db->begin ()); + id = db->persist (joe); + t.commit (); + } + + // Load the object and print what we've got. Then change some + // information and update it in the database. + // + { + transaction t1 (db->begin ()); + auto_ptr j (db->load (id)); + t1.commit (); + + print (*j); + + // Ann another nickname. + // + j->nicknames ().push_back ("Cleaner"); + + // The joe@example.com email is no longer working. + // + j->emails ().erase ("joe@example.com"); + + // Update a weight sample. + // + j->age_weight ()[15] = 28.8F; + + transaction t2 (db->begin ()); + db->update (*j); + t2.commit (); + } + + // Load and print the updated object. + // + { + transaction t (db->begin ()); + auto_ptr j (db->load (id)); + t.commit (); + + print (*j); + } + } + catch (const odb::exception& e) + { + cerr << e.what () << endl; + return 1; + } +} -- cgit v1.1