aboutsummaryrefslogtreecommitdiff
path: root/composite/driver.cxx
blob: 346e76847f91903957528a596c1133e6381e8b8a (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
103
104
// file      : composite/driver.cxx
// author    : Boris Kolpackov <boris@codesynthesis.com>
// 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 "person.hxx"
#include "person-odb.hxx"

using namespace std;
using namespace odb::core;

int
main (int argc, char* argv[])
{
  try
  {
    auto_ptr<database> db (create_database (argc, argv));

    // Create a person object.
    //
    unsigned int id;
    {
      person p ("Joe", "Dirt", "Mr", phone_numbers ("555 5555", "666 6666"));

      transaction t (db->begin ());
      id = db->persist (p);
      t.commit ();
    }

    // Update the extra name information.
    //
    {
      transaction t (db->begin ());

      auto_ptr<person> joe (db->load<person> (id));
      name_extras& ne (joe->name ().extras ());
      ne.nickname ("Squeaky");
      ne.aliases ().push_back (basic_name ("Anthony", "Clean"));

      db->update (*joe);

      t.commit ();
    }

    // Print the name and phone numbers.
    //
    {
      transaction t (db->begin ());
      auto_ptr<person> joe (db->load<person> (id));
      t.commit ();

      name& n (joe->name ());

      cout << n.title () << " " << n.first () << " " << n.last () << endl;

      name_extras& ne (n.extras ());

      if (!ne.nickname ().empty ())
        cout << "  nickname: " << ne.nickname () << endl;

      for (basic_names::iterator i (ne.aliases ().begin ());
           i != ne.aliases ().end ();
           ++i)
      {
        cout << "  alias: " << i->first () << " " << i->last () << endl;
      }

      cout << "  phone 1: " << joe->phone ().first << endl;
      cout << "  phone 2: " << joe->phone ().second << endl;
    }

    // Query the database for a person object.
    //
    {
      typedef odb::query<person> query;
      typedef odb::result<person> result;

      transaction t (db->begin ());

      result r (db->query<person> (
                  query::name.extras.nickname == "Squeaky"));

      if (!r.empty ())
      {
        name& n (r.begin ()->name ());
        cout << n.title () << " " << n.first () << " " << n.last () << endl;
      }

      t.commit ();
    }
  }
  catch (const odb::exception& e)
  {
    cerr << e.what () << endl;
    return 1;
  }
}