-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVEXSQL.hpp
More file actions
85 lines (71 loc) · 2.44 KB
/
VEXSQL.hpp
File metadata and controls
85 lines (71 loc) · 2.44 KB
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
#include <sqlite3.h>
#include <string>
#include <stdexcept>
#include <iostream>
#include <memory>
#ifndef UNTITLED_VEXSQL_HPP
#define UNTITLED_VEXSQL_HPP
inline void sqlite3_cpp_error(char* &err) {
if(err) {
std::string errStr(err);
sqlite3_free(err);
err = nullptr;
throw std::runtime_error(errStr);
}
}
struct ScopedSQLite3 {
sqlite3* ptr;
std::string location;
std::string seqTableName;
explicit ScopedSQLite3(const std::string& location): ptr(nullptr), location(location), seqTableName("event_sequence") {
sqlite3_open(location.c_str(), &ptr);
}
~ScopedSQLite3() {
if(ptr) {
sqlite3_close(ptr);
std::cerr << "Database named " << location << " successfully closed." << std::endl;
}
}
ScopedSQLite3(const ScopedSQLite3&) = delete;
ScopedSQLite3& operator=(const ScopedSQLite3&) = delete;
ScopedSQLite3(ScopedSQLite3&& other) noexcept {
ptr = other.ptr;
seqTableName = other.seqTableName;
other.ptr = nullptr;
}
ScopedSQLite3& operator=(ScopedSQLite3&& other) noexcept {
ptr = other.ptr;
other.ptr = nullptr;
return *this;
}
void executeScript(const std::string& data);
template<typename T>
void exec_lambda(const char* query, const T& copyableRunnable) {
const T* lamb = ©ableRunnable;
char* err = nullptr;
sqlite3_exec(ptr, query, [](void* param, int colCount, char** colValues, char** colNames) -> int {
(*((T*)param))(colCount, colValues, colNames);
}, (void*)lamb, &err);
sqlite3_cpp_error(err);
}
void exec(const char* query);
int getQueryWithIntResult(const char* query);
bool dbHasVexData() {
return getQueryWithIntResult("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='events';");
}
int getLastModified() {
return dbHasVexData() ? getQueryWithIntResult(("SELECT max(modified) FROM " + seqTableName).c_str()) : 0;
}
int getSchema() {
return getQueryWithIntResult("PRAGMA user_version");
}
bool applyEndpoint(const std::string& endpoint, int timeout = 0);
};
bool updateEventList(int timeout = 0);
ScopedSQLite3& dbForEventList(bool update = true);
inline ScopedSQLite3 dbForEndpoint(const std::string& endpoint) {
ScopedSQLite3 db(":memory:");
db.applyEndpoint(endpoint);
return std::move(db);
}
#endif //UNTITLED_VEXSQL_HPP