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  return get(idx, T());
34  }
35 
36  template <class T> struct convert {
37  using to_int = int;
38  };
39 
40  template <class... Ts> std::tuple<Ts...> get_columns(typename convert<Ts>::to_int... idxs) const
41  {
42  return std::make_tuple(get(idxs, Ts())...);
43  }
44 
45  void bind(int idx, const std::string &v, bool copy = true);
46  void bind(const char *name, const std::string &v, bool copy = true);
47  void bind(int idx, int v);
48  void bind(const char *name, int v);
49  void bind(int idx, const horizon::UUID &v);
50  void bind(const char *name, const horizon::UUID &v);
51  void bind(int idx, ObjectType type);
52  void bind(const char *name, ObjectType type);
53  void reset();
54 
55 private:
56  class Database &db;
57  sqlite3_stmt *stmt;
58 
59  std::string get(int idx, std::string) const;
60  int get(int idx, int) const;
61  ObjectType get(int idx, ObjectType) const;
62 };
63 
64 class Error : public std::runtime_error {
65 public:
66  Error(int a_rc, const char *what) : std::runtime_error(what), rc(a_rc)
67  {
68  }
69  const int rc;
70 };
71 
72 class Database {
73  friend Query;
74 
75 public:
76  Database(const std::string &filename, int flags = SQLITE_OPEN_READONLY, int timeout_ms = 0);
77  ~Database();
78  void execute(const std::string &query);
79  void execute(const char *query);
80  int get_user_version();
81 
82 private:
83  sqlite3 *db = nullptr;
84 };
85 } // namespace horizon::SQLite
Definition: sqlite.hpp:72
Definition: sqlite.hpp:64
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
Definition: sqlite.hpp:36