aboutsummaryrefslogtreecommitdiff
path: root/frontend/DB.h
blob: 0164e340ff4805a6d9039dbebd61489517a5ce90 (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#pragma once

#include <memory>
#include <functional>
#include <sqlite3.h>

class DB;
class DBStatement;

class DBQueryRow {
public:
	DBQueryRow(DBStatement &);

public:
	template <typename T>
	T col(int index, const T & default_value);
	template <typename T>
	T col(int index);

private:
	DBStatement & parent;
};

class DBQueryRowRange {
public:
	DBQueryRowRange(DBStatement & stmt);

private:
	class DBQueryRowIterator {
	public:
		DBQueryRowIterator(DBQueryRowRange & parent);

	public:
		DBQueryRow & operator * () const;
		DBQueryRowIterator & operator ++ ();
		bool operator != (const DBQueryRowIterator &) const;

	private:
		bool end = false;
		DBQueryRowRange & parent;
	};

public:
	DBQueryRowIterator begin();
	DBQueryRowIterator end();

private:
	DBStatement & parent;
	DBQueryRow row;
};

class DBStatement {
	friend class DBQueryRow;
	friend class DBQueryRowRange;

public:
	DBStatement(DB &, const std::string & query);

public:
	DBStatement & reset();
	DBStatement & bind(const std::string & text);
	DBStatement & bind(const int & number);
public:
	void execute();
	DBQueryRow row();
	DBQueryRowRange rows();

private:
	std::unique_ptr<sqlite3_stmt, std::function<void(sqlite3_stmt*)>> stmt;
	int param_index = 1;
	DB & parent;
};

class DB {
	friend class DBStatement;

public:
	DB(const std::string & path);
	DBStatement prepare(const std::string & query);

private:
	std::unique_ptr<sqlite3, std::function<void(sqlite3*)>> db = NULL;
};