forked from membase/ep-engine
/
sqlite-strategies.cc
115 lines (99 loc) · 2.96 KB
/
sqlite-strategies.cc
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
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include <cassert>
#include <iostream>
#include <stdexcept>
#include "sqlite-strategies.hh"
#include "sqlite-eval.hh"
#include "ep.hh"
sqlite3 *SqliteStrategy::open(void) {
if(!db) {
if(sqlite3_open(filename, &db) != SQLITE_OK) {
throw std::runtime_error("Error initializing sqlite3");
}
if(sqlite3_extended_result_codes(db, 1) != SQLITE_OK) {
throw std::runtime_error("Error enabling extended RCs");
}
initPragmas();
initTables();
initStatements();
}
return db;
}
void SqliteStrategy::close(void) {
if(db) {
destroyStatements();
sqlite3_close(db);
db = NULL;
}
}
void SqliteStrategy::destroyStatements() {
while (!statements.empty()) {
Statements *st = statements.back();
delete st;
statements.pop_back();
}
}
void SqliteStrategy::initTables(void) {
assert(db);
execute("create table if not exists kv"
" (k varchar(250) primary key on conflict replace,"
" v text,"
" flags integer,"
" exptime integer,"
" cas integer)");
}
void SqliteStrategy::initStatements(void) {
assert(db);
Statements *st = new Statements(db, "kv");
statements.push_back(st);
}
void SqliteStrategy::destroyTables(void) {
execute("drop table if exists kv");
}
void SqliteStrategy::initPragmas(void) {
if (initFile) {
SqliteEvaluator eval(db);
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"Initializing DB session from %s\n", initFile);
eval.eval(initFile);
}
}
void SqliteStrategy::execute(const char * const query) {
PreparedStatement st(db, query);
st.execute();
}
//
// ----------------------------------------------------------------------
// Multi DB strategy
// ----------------------------------------------------------------------
//
void MultiDBSqliteStrategy::initTables() {
char buf[1024];
for (int i = 0; i < numTables; i++) {
snprintf(buf, sizeof(buf), "attach database \"%s-%d.sqlite\" as kv_%d",
filename, i, i);
execute(buf);
snprintf(buf, sizeof(buf),
"create table if not exists kv_%d.kv"
" (k varchar(250) primary key on conflict replace,"
" v text,"
" flags integer,"
" exptime integer,"
" cas integer)", i);
execute(buf);
}
}
void MultiDBSqliteStrategy::initStatements() {
char buf[64];
for (int i = 0; i < numTables; i++) {
snprintf(buf, sizeof(buf), "kv_%d.kv", i);
statements.push_back(new Statements(db, std::string(buf)));
}
}
void MultiDBSqliteStrategy::destroyTables() {
char buf[1024];
for (int i = 0; i < numTables; i++) {
snprintf(buf, sizeof(buf), "drop table if exists kv_%d.kv", i);
execute(buf);
}
}