aboutsummaryrefslogtreecommitdiff
path: root/frontend/DB.cpp
blob: d51601ee60c2906e936e31b8ab9cc16313b94e2d (plain)
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
#include "DB.h"
#include "Exception.h"

using namespace std;

DB::DB(const string & path) {
	sqlite3 * db = NULL;
	int ret = sqlite3_open_v2(path.c_str(), &db, SQLITE_OPEN_READWRITE, NULL);
	this->db = {
		db,
		[] (sqlite3 * db) {
			sqlite3_close_v2(db);
		},
	};
	if (ret != SQLITE_OK)
		throw Exception("sqlite3_open_v2: %d", ret);
}

DBStatement DB::prepare(const string & query) {
	return DBStatement(*this, query);
}

DBStatement::DBStatement(DB & db, const string & query) : db(db) {
	sqlite3_stmt * stmt = NULL;
	int ret = sqlite3_prepare_v2(this->db.db.get(), query.c_str(), query.size(), &stmt, NULL);
	this->stmt = {
		stmt,
		[] (sqlite3_stmt * stmt) {
			sqlite3_finalize(stmt);
		},
	};
	if (ret != SQLITE_OK)
		throw Exception("sqlite3_prepare_v2: %d", ret);
}

DBStatement & DBStatement::bind(const string & text) {
	int ret = sqlite3_bind_text(this->stmt.get(), this->param_index, text.data(), text.size(), NULL);
	if (ret != SQLITE_OK)
		throw Exception("sqlite3_bind_text: %d", ret);

	this->param_index++;
	return *this;
}

DBStatement & DBStatement::bind(const int & number) {
	int ret = sqlite3_bind_int(this->stmt.get(), this->param_index, number);
	if (ret != SQLITE_OK)
		throw Exception("sqlite3_bind_int: %d", ret);

	this->param_index++;
	return *this;
}

DBStatement & DBStatement::unbind() {
	this->param_index = 1;
	return *this;
}

void DBStatement::execute() {
	int ret = sqlite3_step(this->stmt.get());
	if (ret != SQLITE_DONE)
		throw Exception("sqlite3_step: %d", ret);
}