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