From ab994fdada3eebc794d6b1686f55a35420e4d758 Mon Sep 17 00:00:00 2001 From: Boris Kolpackov Date: Wed, 25 Apr 2012 10:45:32 +0200 Subject: New example, inheritance/polymorphism Also move the inheritance example to inheritance/reuse. --- inheritance/polymorphism/driver.cxx | 102 ++++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 inheritance/polymorphism/driver.cxx (limited to 'inheritance/polymorphism/driver.cxx') diff --git a/inheritance/polymorphism/driver.cxx b/inheritance/polymorphism/driver.cxx new file mode 100644 index 0000000..e0c9952 --- /dev/null +++ b/inheritance/polymorphism/driver.cxx @@ -0,0 +1,102 @@ +// file : inheritance/polymorphism/driver.cxx +// copyright : not copyrighted - public domain + +#include // std::auto_ptr +#include + +#include +#include + +#include "database.hxx" // create_database + +#include "employee.hxx" +#include "employee-odb.hxx" + +using namespace std; +using namespace odb::core; + +int +main (int argc, char* argv[]) +{ + try + { + auto_ptr db (create_database (argc, argv)); + + unsigned long id1, id2; + + // Add a few employee and contractor objects to the database. + // + { + auto_ptr p1 (new employee ("John", "Doe", true)); + auto_ptr p2 (new contractor ("Jane", "Doe", "jane@doe.com")); + + transaction t (db->begin ()); + id1 = db->persist (*p1); // Stores employee. + id2 = db->persist (*p2); // Stores contractor. + t.commit (); + } + + // Load polymorphic objects given their object ids. + // + { + transaction t (db->begin ()); + auto_ptr p1 (db->load (id1)); // Loads employee. + auto_ptr p2 (db->load (id2)); // Loads contractor. + t.commit (); + + p1->print (); + p2->print (); + } + + // Make John Doe a permanent employee. + // + { + transaction t (db->begin ()); + + auto_ptr e (db->load (id1)); + e->temporary (false); + person& p (*e); + db->update (p); // Updates employee. + + t.commit (); + } + + // Query all the person objects that have Doe as the last name. + // + { + typedef odb::query query; + typedef odb::result result; + + transaction t (db->begin ()); + + result r (db->query (query::last == "Doe")); + + for (result::iterator i (r.begin ()); i != r.end (); ++i) + { + // We can check the discriminator before loading the object. + // + string d (i.discriminator ()); + cout << "discriminator: " << d << endl; + + i->print (); // Can be employee or contractor. + } + + t.commit (); + } + + // Erase the objects from the database. + // + { + transaction t (db->begin ()); + auto_ptr p (db->load (id1)); // Loads employee. + db->erase (*p); // Erases employee. + db->erase (id2); // Erases contractor. + t.commit (); + } + } + catch (const odb::exception& e) + { + cerr << e.what () << endl; + return 1; + } +} -- cgit v1.1