about summary refs log tree commit diff stats
path: root/hkutil/database.h
blob: a2217e62049fdc49e4c0c5b621fb2b07f1481234 (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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
#ifndef DATABASE_H_0B0A47D2
#define DATABASE_H_0B0A47D2

#include <sqlite3.h>
#include <fstream>
#include <sstream>
#include <string>
#include <stdexcept>
#include <vector>
#include <cstring>
#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 blob_type = std::vector<unsigned char>;

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

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

  using row =
    std::vector<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* tempStmt;

      int ret = sqlite3_prepare_v2(
        ppdb_.get(),
        query.c_str(),
        query.length(),
        &tempStmt,
        NULL);

      ppstmt_type ppstmt(tempStmt);

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

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

    uint64_t 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* tempStmt;

      int ret = sqlite3_prepare_v2(
        ppdb_.get(),
        query_str.c_str(),
        query_str.length(),
        &tempStmt,
        NULL);

      ppstmt_type ppstmt(tempStmt);

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

      int i = 1;
      for (const column& c : columns)
      {
        bindToStmt(ppstmt, i, std::get<1>(c));

        i++;
      }

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

      return sqlite3_last_insert_rowid(ppdb_.get());
    }

    std::vector<row> queryAll(
      std::string queryString,
      std::list<binding> bindings = {})
    {
      sqlite3_stmt* tempStmt;

      int ret = sqlite3_prepare_v2(
        ppdb_.get(),
        queryString.c_str(),
        queryString.length(),
        &tempStmt,
        NULL);

      ppstmt_type ppstmt(tempStmt);

      if (ret != SQLITE_OK)
      {
        throw sqlite3_error("Error preparing query", ppdb_.get());
      }

      int i = 1;
      for (const binding& value : bindings)
      {
        bindToStmt(ppstmt, i, value);

        i++;
      }

      std::vector<row> result;

      while (sqlite3_step(ppstmt.get()) == SQLITE_ROW)
      {
        row curRow;

        int cols = sqlite3_column_count(ppstmt.get());

        for (int i = 0; i < cols; i++)
        {
          switch (sqlite3_column_type(ppstmt.get(), i))
          {
            case SQLITE_INTEGER:
            {
              curRow.emplace_back(sqlite3_column_int(ppstmt.get(), i));

              break;
            }

            case SQLITE_TEXT:
            {
              curRow.emplace_back(
                std::string(
                  reinterpret_cast<const char*>(
                    sqlite3_column_text(ppstmt.get(), i))));

              break;
            }

            case SQLITE_FLOAT:
            {
              curRow.emplace_back(sqlite3_column_double(ppstmt.get(), i));

              break;
            }

            case SQLITE_NULL:
            {
              curRow.emplace_back(nullptr);

              break;
            }

            case SQLITE_BLOB:
            {
              int len = sqlite3_column_bytes(ppstmt.get(), i);

              blob_type value(len);

              memcpy(
                value.data(),
                sqlite3_column_blob(ppstmt.get(), i),
                len);

                curRow.emplace_back(std::move(value));

              break;
            }

            default:
            {
              // Impossible

              break;
            }
          }
        }

        result.emplace_back(std::move(curRow));
      }

      return result;
    }

    row queryFirst(
      std::string queryString,
      std::list<binding> bindings = {})
    {
      std::vector<row> dataset = queryAll(
        std::move(queryString),
        std::move(bindings));

      if (dataset.empty())
      {
        throw std::logic_error("Query returned empty dataset");
      }

      row result = std::move(dataset.front());

      return result;
    }

  private:

    class sqlite3_deleter {
    public:

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

    class stmt_deleter {
    public:

      void operator()(sqlite3_stmt* ptr) const
      {
        sqlite3_finalize(ptr);
      }
    };

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

    void bindToStmt(
      const ppstmt_type& ppstmt,
      int i,
      const binding& value)
    {
      if (mpark::holds_alternative<int>(value))
      {
        if (sqlite3_bind_int(
          ppstmt.get(),
          i,
          mpark::get<int>(value)) != SQLITE_OK)
        {
          throw sqlite3_error("Error preparing statement", ppdb_.get());
        }
      } else if (mpark::holds_alternative<std::string>(value))
      {
        const std::string& arg = mpark::get<std::string>(value);

        if (sqlite3_bind_text(
          ppstmt.get(),
          i,
          arg.c_str(),
          arg.length(),
          SQLITE_TRANSIENT) != SQLITE_OK)
        {
          throw sqlite3_error("Error preparing statement", ppdb_.get());
        }
      } else if (mpark::holds_alternative<double>(value))
      {
        if (sqlite3_bind_double(
          ppstmt.get(),
          i,
          mpark::get<double>(value)) != SQLITE_OK)
        {
          throw sqlite3_error("Error preparing statement", ppdb_.get());
        }
      } else if (mpark::holds_alternative<std::nullptr_t>(value))
      {
        if (sqlite3_bind_null(ppstmt.get(), i) != SQLITE_OK)
        {
          throw sqlite3_error("Error preparing statement", ppdb_.get());
        }
      } else if (mpark::holds_alternative<blob_type>(value))
      {
        const blob_type& arg = mpark::get<blob_type>(value);

        if (sqlite3_bind_blob(
          ppstmt.get(),
          i,
          arg.data(),
          arg.size(),
          SQLITE_TRANSIENT) != SQLITE_OK)
        {
          throw sqlite3_error("Error preparing statement", ppdb_.get());
        }
      }
    }

    ppdb_type ppdb_;

  };

};

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