blob: e0c995287564f0610ded8fa636dd44b7ac03adf9 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
|
// file : inheritance/polymorphism/driver.cxx
// copyright : not copyrighted - public domain
#include <memory> // std::auto_ptr
#include <iostream>
#include <odb/database.hxx>
#include <odb/transaction.hxx>
#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<database> db (create_database (argc, argv));
unsigned long id1, id2;
// Add a few employee and contractor objects to the database.
//
{
auto_ptr<person> p1 (new employee ("John", "Doe", true));
auto_ptr<person> 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<person> p1 (db->load<person> (id1)); // Loads employee.
auto_ptr<person> p2 (db->load<person> (id2)); // Loads contractor.
t.commit ();
p1->print ();
p2->print ();
}
// Make John Doe a permanent employee.
//
{
transaction t (db->begin ());
auto_ptr<employee> e (db->load<employee> (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<person> query;
typedef odb::result<person> result;
transaction t (db->begin ());
result r (db->query<person> (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<person> p (db->load<person> (id1)); // Loads employee.
db->erase (*p); // Erases employee.
db->erase<person> (id2); // Erases contractor.
t.commit ();
}
}
catch (const odb::exception& e)
{
cerr << e.what () << endl;
return 1;
}
}
|