Horizon
sqlite.hpp
1 #pragma once
2 #include <sqlite3.h>
3 #include <string>
4 #include <tuple>
5 #include <stdexcept>
6 
7 namespace horizon {
8 enum class ObjectType;
9 class UUID;
10 } // namespace horizon
11 
12 namespace horizon::SQLite {
13 class noncopyable {
14 protected:
15  noncopyable() = default;
16  ~noncopyable() = default;
17 
18  noncopyable(noncopyable &&) = default;
19  noncopyable &operator=(noncopyable &&) = default;
20 
21  noncopyable(noncopyable const &) = delete;
22  noncopyable &operator=(noncopyable const &) = delete;
23 };
24 
25 class Query : noncopyable {
26 public:
27  Query(class Database &d, const std::string &sql);
28  Query(class Database &d, const char *sql, int size = -1);
29  ~Query();
30  bool step();
31  template <class T> T get(int idx) const
32  {
33  T r;
34  get(idx, r);
35  return r;
36  }
37 
38  void bind(int idx, const std::string &v, bool copy = true);
39  void bind(const char *name, const std::string &v, bool copy = true);
40  void bind(int idx, int v);
41  void bind(const char *name, int v);
42  void bind_int64(int idx, sqlite3_int64 v);
43  void bind_int64(const char *name, sqlite3_int64 v);
44  void bind(int idx, const horizon::UUID &v);
45  void bind(const char *name, const horizon::UUID &v);
46  void bind(int idx, ObjectType type);
47  void bind(const char *name, ObjectType type);
48  void reset();
49 
50 private:
51  class Database &db;
52  sqlite3_stmt *stmt;
53 
54  void get(int idx, std::string &r) const;
55  void get(int idx, UUID &r) const;
56  void get(int idx, int &r) const;
57  void get(int idx, sqlite3_int64 &r) const;
58  void get(int idx, ObjectType &r) const;
59 };
60 
61 class Error : public std::runtime_error {
62 public:
63  Error(int a_rc, const char *what) : std::runtime_error(what), rc(a_rc)
64  {
65  }
66  const int rc;
67 };
68 
69 class Database {
70  friend Query;
71 
72 public:
73  Database(const std::string &filename, int flags = SQLITE_OPEN_READONLY, int timeout_ms = 0);
74  ~Database();
75  void execute(const std::string &query);
76  void execute(const char *query);
77  int get_user_version();
78 
79 private:
80  sqlite3 *db = nullptr;
81 };
82 } // namespace horizon::SQLite
Definition: sqlite.hpp:69
Definition: sqlite.hpp:61
Definition: sqlite.hpp:25
Definition: sqlite.hpp:13
This class encapsulates a UUID and allows it to be uses as a value type.
Definition: uuid.hpp:16