summaryrefslogtreecommitdiffabout
path: root/src/sqlite.h
Unidiff
Diffstat (limited to 'src/sqlite.h') (more/less context) (ignore whitespace changes)
-rw-r--r--src/sqlite.h103
1 files changed, 103 insertions, 0 deletions
diff --git a/src/sqlite.h b/src/sqlite.h
new file mode 100644
index 0000000..ad276ee
--- a/dev/null
+++ b/src/sqlite.h
@@ -0,0 +1,103 @@
1#ifndef __SQLITE_H
2#define __SQLITE_H
3
4#include <cassert>
5#include <stdexcept>
6#include <string>
7#include <sqlite3.h>
8
9namespace sqlite {
10 using std::string;
11
12 class exception : public std::runtime_error {
13 public:
14 int rcode;
15 explicit exception(const string& w,int rc=-1)
16 : std::runtime_error(w), rcode(rc) { }
17 ~exception() throw() { }
18 };
19
20 class db_t {
21 public:
22 sqlite3 *_D;
23
24 db_t()
25 : _D(0) { }
26 db_t(const char *f)
27 : _D(0) { open(f); }
28 ~db_t() { close(); }
29
30 operator const sqlite3*(void) const { return _D; }
31 operator sqlite3*(void) { return _D; }
32
33 void close() {
34 if(_D) {
35 sqlite3_close(_D);
36 _D = 0;
37 }
38 }
39 void open(const char *f) {
40 close();
41 int r = sqlite3_open(f,&_D);
42 if(r!=SQLITE_OK) {
43 string msg = sqlite3_errmsg(_D); sqlite3_close(_D);
44 throw exception("Failed to open SQLite database: "+msg,r);
45 }
46 }
47
48 void exec(const char *sql) {
49 assert(_D);
50 char *errm;
51 int r = sqlite3_exec(_D,sql,NULL,NULL,&errm);
52 if(r!=SQLITE_OK)
53 throw exception(string("Failed to sqlite3_exec():")+errm,r);
54 }
55 void get_table(const char *sql,char ***resp,int *nr,int *nc) {
56 assert(_D);
57 char *errm;
58 int r = sqlite3_get_table(_D,sql,resp,nr,nc,&errm);
59 if(r!=SQLITE_OK)
60 throw exception(string("Failed to sqlite3_get_table():")+errm,r);
61 }
62 };
63
64 template<typename T>
65 class mem_t {
66 public:
67 T _M;
68
69 mem_t(T M) :_M(M) { }
70 ~mem_t() { if(_M) sqlite3_free(_M); }
71
72 operator const T&(void) const { return _M; }
73 operator T&(void) { return _M; }
74
75 mem_t operator=(T M) {
76 if(_M) sqlite3_free(_M);
77 _M = M;
78 }
79 };
80
81 class table_t {
82 public:
83 char **_T;
84
85 table_t() : _T(0) { }
86 table_t(char **T) : _T(T) { }
87 ~table_t() { if(_T) sqlite3_free_table(_T); }
88
89 operator char**&(void) { return _T; }
90
91 operator char ***(void) {
92 if(_T) sqlite3_free_table(_T);
93 return &_T; }
94
95 const char *get(int r,int c,int nc) {
96 assert(_T);
97 return _T[r*nc+c];
98 }
99 };
100
101}
102
103#endif /* __SQLITE_H */