-rw-r--r-- | test/sqlite.h | 71 |
1 files changed, 71 insertions, 0 deletions
diff --git a/test/sqlite.h b/test/sqlite.h new file mode 100644 index 0000000..883a2c0 --- a/dev/null +++ b/test/sqlite.h | |||
@@ -0,0 +1,71 @@ | |||
1 | #include <sqlite3.h> | ||
2 | |||
3 | class sqlite3_t { | ||
4 | public: | ||
5 | sqlite3 *_D; | ||
6 | |||
7 | sqlite3_t(const char *f) | ||
8 | : _D(0) { | ||
9 | int r = sqlite3_open(f,&_D); | ||
10 | if(r!=SQLITE_OK) { | ||
11 | string msg = sqlite3_errmsg(_D); sqlite3_close(_D); | ||
12 | throw opkele::exception(OPKELE_CP_ "Failed to open SQLite database: "+msg); | ||
13 | } | ||
14 | } | ||
15 | ~sqlite3_t() { | ||
16 | if(_D) sqlite3_close(_D); | ||
17 | } | ||
18 | |||
19 | operator const sqlite3*(void) const { return _D; } | ||
20 | operator sqlite3*(void) { return _D; } | ||
21 | |||
22 | void exec(const char *sql) { | ||
23 | assert(_D); | ||
24 | char *errm; | ||
25 | if(sqlite3_exec(_D,sql,NULL,NULL,&errm)!=SQLITE_OK) | ||
26 | throw opkele::exception(OPKELE_CP_ string("Failed to sqlite3_exec():")+errm); | ||
27 | } | ||
28 | void get_table(const char *sql,char ***resp,int *nr,int *nc) { | ||
29 | assert(_D); | ||
30 | char *errm; | ||
31 | if(sqlite3_get_table(_D,sql,resp,nr,nc,&errm)!=SQLITE_OK) | ||
32 | throw opkele::exception(OPKELE_CP_ string("Failed to sqlite3_get_table():")+errm); | ||
33 | } | ||
34 | }; | ||
35 | |||
36 | template<typename T> | ||
37 | class sqlite3_mem_t { | ||
38 | public: | ||
39 | T _M; | ||
40 | |||
41 | sqlite3_mem_t(T M) :_M(M) { } | ||
42 | ~sqlite3_mem_t() { if(_M) sqlite3_free(_M); } | ||
43 | |||
44 | operator const T&(void) const { return _M; } | ||
45 | operator T&(void) { return _M; } | ||
46 | |||
47 | sqlite3_mem_t operator=(T M) { | ||
48 | if(_M) sqlite3_free(_M); | ||
49 | _M = M; | ||
50 | } | ||
51 | }; | ||
52 | |||
53 | class sqlite3_table_t { | ||
54 | public: | ||
55 | char **_T; | ||
56 | |||
57 | sqlite3_table_t() : _T(0) { } | ||
58 | sqlite3_table_t(char **T) : _T(T) { } | ||
59 | ~sqlite3_table_t() { if(_T) sqlite3_free_table(_T); } | ||
60 | |||
61 | operator char**&(void) { return _T; } | ||
62 | |||
63 | operator char ***(void) { | ||
64 | if(_T) sqlite3_free_table(_T); | ||
65 | return &_T; } | ||
66 | |||
67 | const char *get(int r,int c,int nc) { | ||
68 | assert(_T); | ||
69 | return _T[r*nc+c]; | ||
70 | } | ||
71 | }; | ||