about summary refs log tree commit diff stats
path: root/hkutil/database.h
blob: c15fa52e89e662e49a9f23b26eeaa3aab43ec5fc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
#ifndef DATABASE_H_0B0A47D2
#define DATABASE_H_0B0A47D2

#include <sqlite3.h>
#include <fstream>
#include <sstream>
#include <string>
#include <stdexcept>
#include <list>
#include <memory>
#include "../vendor/variant.hpp"
#include "string.h"

namespace hatkirby {

  class sqlite3_error : public std::runtime_error {
  public:

    sqlite3_error(
      const std::string& what,
      sqlite3* ppdb)
        : std::runtime_error(generateWhat(what, ppdb))
    {
    }

  private:

    static std::string generateWhat(
      const std::string& what,
      sqlite3* ppdb)
    {
      std::string errmsg(sqlite3_errmsg(ppdb));

      return what + " (" + errmsg + ")";
    }

  };

  enum class dbmode {
    read,
    readwrite,
    create
  };

  using binding =
    mpark::variant<
      std::string,
      int>;

  using column =
    std::tuple<
      std::string,
      binding>;

  class database {
  public:

    // Constructor

    explicit database(
      std::string path,
      dbmode mode)
    {
      if (mode == dbmode::create)
      {
        // If there is already a file at this path, overwrite it.
        if (std::ifstream(path))
        {
          if (std::remove(path.c_str()))
          {
            throw std::logic_error("Could not overwrite file at path");
          }
        }
      }

      sqlite3* tempDb;

      int flags;

      if (mode == dbmode::read)
      {
        flags = SQLITE_OPEN_READONLY;
      } else {
        flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
      }

      int ret = sqlite3_open_v2(
        path.c_str(),
        &tempDb,
        flags,
        NULL);

      ppdb_ = ppdb_type(tempDb);

      if (ret != SQLITE_OK)
      {
        throw sqlite3_error("Could not create output datafile", ppdb_.get());
      }
    }

    // Actions

    void execute(std::string query)
    {
      sqlite3_stmt* ppstmt;

      if (sqlite3_prepare_v2(
        ppdb_.get(),
        query.c_str(),
        query.length(),
        &ppstmt,
        NULL) != SQLITE_OK)
      {
        throw sqlite3_error("Error writing to database", ppdb_.get());
      }

      int result = sqlite3_step(ppstmt);
      sqlite3_finalize(ppstmt);

      if (result != SQLITE_DONE)
      {
        throw sqlite3_error("Error writing to database", ppdb_.get());
      }
    }

    void insertIntoTable(
      std::string table,
      std::list<column> columns)
    {
      std::list<std::string> fieldNames;
      std::list<std::string> qs;

      for (const column& c : columns)
      {
        fieldNames.push_back(std::get<0>(c));
        qs.push_back("?");
      }

      std::ostringstream query;
      query << "INSERT INTO ";
      query << table;
      query << " (";
      query << implode(std::begin(fieldNames), std::end(fieldNames), ", ");
      query << ") VALUES (";
      query << implode(std::begin(qs), std::end(qs), ", ");
      query << ")";

      std::string query_str = query.str();

      sqlite3_stmt* ppstmt;

      if (sqlite3_prepare_v2(
        ppdb_.get(),
        query_str.c_str(),
        query_str.length(),
        &ppstmt,
        NULL) != SQLITE_OK)
      {
        throw sqlite3_error("Error writing to database", ppdb_.get());
      }

      int i = 1;
      for (const column& c : columns)
      {
        const binding& b = std::get<1>(c);

        if (mpark::holds_alternative<int>(b))
        {
          sqlite3_bind_int(ppstmt, i, mpark::get<int>(b));
        } else if (mpark::holds_alternative<std::string>(b))
        {
          const std::string& arg = mpark::get<std::string>(b);

          sqlite3_bind_text(
            ppstmt,
            i,
            arg.c_str(),
            arg.length(),
            SQLITE_TRANSIENT);
        }

        i++;
      }

      int result = sqlite3_step(ppstmt);
      sqlite3_finalize(ppstmt);

      if (result != SQLITE_DONE)
      {
        throw sqlite3_error("Error writing to database", ppdb_.get());
      }
    }

  private:

    class sqlite3_deleter {
    public:

      void operator()(sqlite3* ptr) const
      {
        sqlite3_close_v2(ptr);
      }
    };

    using ppdb_type = std::unique_ptr<sqlite3, sqlite3_deleter>;

    ppdb_type ppdb_;

  };

};

#endif /* end of include guard: DATABASE_H_0B0A47D2 */