| 1 | #pragma once
|
| 2 |
|
| 3 | #include <functional>
|
| 4 | #include <string>
|
| 5 | #include <cstdint>
|
| 6 | #include <string_view>
|
| 7 |
|
| 8 | #include "types.hh"
|
| 9 |
|
| 10 | class sqlite3;
|
| 11 | class sqlite3_stmt;
|
| 12 |
|
| 13 | namespace nix {
|
| 14 |
|
| 15 |
|
| 16 | struct SQLite
|
| 17 | {
|
| 18 | sqlite3 * db;
|
| 19 | SQLite() { db = 0; }
|
| 20 | ~SQLite();
|
| 21 | operator sqlite3 * () { return db; }
|
| 22 | };
|
| 23 |
|
| 24 |
|
| 25 | struct SQLiteStmt
|
| 26 | {
|
| 27 | sqlite3 * db = 0;
|
| 28 | sqlite3_stmt * stmt = 0;
|
| 29 | SQLiteStmt() { }
|
| 30 | void create(sqlite3 * db, const std::string & s);
|
| 31 | ~SQLiteStmt();
|
| 32 | operator sqlite3_stmt * () { return stmt; }
|
| 33 |
|
| 34 |
|
| 35 | class Use
|
| 36 | {
|
| 37 | friend struct SQLiteStmt;
|
| 38 | private:
|
| 39 | SQLiteStmt & stmt;
|
| 40 | unsigned int curArg = 1;
|
| 41 | Use(SQLiteStmt & stmt);
|
| 42 |
|
| 43 | public:
|
| 44 |
|
| 45 | ~Use();
|
| 46 |
|
| 47 |
|
| 48 | Use & operator () (const std::string & value, bool notNull = true);
|
| 49 | Use & operator () (int64_t value, bool notNull = true);
|
| 50 | Use & bind(); |
| 51 |
|
| 52 | int step();
|
| 53 |
|
| 54 |
|
| 55 | void exec();
|
| 56 |
|
| 57 | |
| 58 | a row is available.
|
| 59 | bool next();
|
| 60 |
|
| 61 | std::string getStr(int col);
|
| 62 | int64_t getInt(int col);
|
| 63 | };
|
| 64 |
|
| 65 | Use use()
|
| 66 | {
|
| 67 | return Use(*this);
|
| 68 | }
|
| 69 | };
|
| 70 |
|
| 71 | |
| 72 | committed.
|
| 73 | struct SQLiteTxn
|
| 74 | {
|
| 75 | bool active = false;
|
| 76 | sqlite3 * db;
|
| 77 |
|
| 78 | SQLiteTxn(sqlite3 * db);
|
| 79 |
|
| 80 | void commit();
|
| 81 |
|
| 82 | ~SQLiteTxn();
|
| 83 | };
|
| 84 |
|
| 85 |
|
| 86 | MakeError(SQLiteError, Error);
|
| 87 | MakeError(SQLiteBusy, SQLiteError);
|
| 88 |
|
| 89 | [[noreturn]] void throwSQLiteError(sqlite3 * db, std::string_view f);
|
| 90 |
|
| 91 | |
| 92 | database is busy.
|
| 93 | template<typename T>
|
| 94 | T retrySQLite(std::function<T()> fun)
|
| 95 | {
|
| 96 | while (true) {
|
| 97 | try {
|
| 98 | return fun();
|
| 99 | } catch (SQLiteBusy & e) {
|
| 100 | }
|
| 101 | }
|
| 102 | }
|
| 103 |
|
| 104 | }
|