1#include "MyDb.hpp"
2
3// File: MyDb.cpp
4
5// Class constructor. Requires a path to the location
6// where the database is located, and a database name
7MyDb::MyDb(std::string &path, std::string &dbName,
8           bool isSecondary)
9    : db_(NULL, 0),               // Instantiate Db object
10      dbFileName_(path + dbName), // Database file name
11      cFlags_(DB_CREATE)          // If the database doesn't yet exist,
12                                  // allow it to be created.
13{
14    try
15    {
16        // Redirect debugging information to std::cerr
17        db_.set_error_stream(&std::cerr);
18
19        // If this is a secondary database, support
20        // sorted duplicates
21        if (isSecondary)
22            db_.set_flags(DB_DUPSORT);
23
24        // Open the database
25        db_.open(NULL, dbFileName_.c_str(), NULL, DB_BTREE, cFlags_, 0);
26    }
27    // DbException is not a subclass of std::exception, so we
28    // need to catch them both.
29    catch(DbException &e)
30    {
31        std::cerr << "Error opening database: " << dbFileName_ << "\n";
32        std::cerr << e.what() << std::endl;
33    }
34    catch(std::exception &e)
35    {
36        std::cerr << "Error opening database: " << dbFileName_ << "\n";
37        std::cerr << e.what() << std::endl;
38    }
39}
40
41// Private member used to close a database. Called from the class
42// destructor.
43void
44MyDb::close()
45{
46    // Close the db
47    try
48    {
49        db_.close(0);
50        std::cout << "Database " << dbFileName_
51                  << " is closed." << std::endl;
52    }
53    catch(DbException &e)
54    {
55            std::cerr << "Error closing database: " << dbFileName_ << "\n";
56            std::cerr << e.what() << std::endl;
57    }
58    catch(std::exception &e)
59    {
60        std::cerr << "Error closing database: " << dbFileName_ << "\n";
61        std::cerr << e.what() << std::endl;
62    }
63}
64