clang-tags
C/C++ source code indexing tool based on libclang
 All Classes Functions Variables Typedefs Groups Pages
database.hxx
1 #pragma once
2 
3 #include <string>
4 #include <memory>
5 #include <sqlite3.h>
6 #include <stdexcept>
7 
8 namespace Sqlite {
9  // Forward declarations
10  class Statement;
11 
18  struct Error : public std::runtime_error {
23  Error (const std::string & what)
24  : std::runtime_error (what)
25  {}
26  };
27 
30  class Database {
31  public:
39  Database (const std::string & fileName) {
40  sqlite3 *db;
41  int ret = sqlite3_open (fileName.c_str(), &db);
42  db_.reset (new Sqlite3_ (db));
43 
44  if (ret != SQLITE_OK) {
45  throw Error (errMsg());
46  }
47  }
48 
56  int execute (char const *const sql);
57 
67  Statement prepare (char const *const sql);
68 
73  const char * errMsg () {
74  return sqlite3_errmsg(raw());
75  }
76 
81  int lastInsertRowId () {
82  return sqlite3_last_insert_rowid (raw());
83  }
84 
85  private:
86  sqlite3 * raw () { return db_->db_; }
87 
88  struct Sqlite3_ {
89  sqlite3 *db_;
90  Sqlite3_ (sqlite3 *db) : db_ (db) {}
91  ~Sqlite3_ () { sqlite3_close (db_); }
92  };
93  std::shared_ptr<Sqlite3_> db_;
94 
95  friend class Statement;
96  };
97 
99 }