-
Notifications
You must be signed in to change notification settings - Fork 10
/
sqlitepp.h
479 lines (420 loc) · 14.6 KB
/
sqlitepp.h
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
///////////////////////////////////////////////////////////////////////////////
/// \author (c) Marco Paland (marco@paland.com)
/// 2014, PALANDesign Hannover, Germany
///
/// \license The MIT License (MIT)
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
///
///
/// \brief sqlitepp classes
/// sqlitepp is a single header C++ wrapper for the SQLite3 db
///
/// \changelog
/// 1.6.1 Changed license to MIT
///
/// 1.6.0 Removed str() function, it's implicit now via conversion operator
///
/// 1.5.0 Added 'invalid' type (-1) for field_type
/// row [""] operator can return invalid ref as invalid field_type now
///
/// 1.4.1 Fixed support for binding empty vectors and strings
///
/// 1.4.0 Added query operator<< for TEXT
///
/// 1.3.0 Added 'vacuum' function for db defragmentation
/// Minor bugfixes
///
/// 1.2.1 Minor cleanups and fixes
///
/// 1.2.0 Added 'str' function on field_type to stringify fields
/// Added 'use_abort' function
///
/// 1.1.0 First inital release
/// Added some enhancements for field_type access
///
/// 1.0.0 All ideas coded, first tests okay
///
///////////////////////////////////////////////////////////////////////////////
#ifndef _SQLITEPP_H_
#define _SQLITEPP_H_
#define SQLITEPP_VERSION "1.6.1" // X.Y.Z
#define SQLITEPP_VERSION_NUMBER 1006001 // X*1000000 + Y*1000 + Z
#include "thirdparty/sqlite3.h"
#include <vector>
#include <string>
#include <sstream>
#include <cstdint>
namespace sqlitepp {
/*
* Representation of a single result field
*/
struct field_type
{
// ctors
field_type()
: type_(-1) { }
field_type(std::string const& name)
: name_(name), type_(SQLITE_NULL) { int_ = 0; }
field_type(int i, std::string const& name)
: name_(name), type_(SQLITE_INTEGER) { int_ = i; }
field_type(::sqlite3_int64 i64, std::string const& name)
: name_(name), type_(SQLITE_INTEGER) { int_ = i64; }
field_type(double d, std::string const& name)
: name_(name), type_(SQLITE_FLOAT) { float_ = d; }
field_type(std::string s, std::string const& name)
: name_(name), type_(SQLITE_TEXT) { str_ = s; }
field_type(std::vector<std::uint8_t> v, std::string const& name)
: name_(name), type_(SQLITE_BLOB) { vec_ = v; }
// access field value
operator int() const { return static_cast<int>(int_); }
operator ::sqlite_int64() const { return int_; }
operator double() const { return float_; }
operator std::string() const {
switch (type_) {
case SQLITE_TEXT : return str_;
case SQLITE_INTEGER : { std::stringstream s; s << int_; return s.str(); }
case SQLITE_FLOAT : { std::stringstream s; s << float_; return s.str(); }
case SQLITE_BLOB : return "BLOB";
case SQLITE_NULL : return "NULL";
case -1 : return "invalid";
default : return "";
}
}
operator std::vector<std::uint8_t>() const { return vec_; }
// get field (column) name
inline std::string name() const { return name_; }
// get field (column) type
inline int type() const { return type_; }
// returns true if field is NULL
inline bool is_null() const { return type_ == SQLITE_NULL; }
private:
std::int64_t int_; // int data
double float_; // float data
std::vector<std::uint8_t> vec_; // vector (blob) data
std::string str_; // string (text) data
std::string name_; // field (col) name
int type_; // sqlte type
};
/*
* Representation of a result row
*/
class row : public std::vector<field_type>
{
public:
// access field by index
const_reference operator[](size_type idx) const {
return at(idx);
}
// access field by name
const_reference operator[](const char* colname) const {
const static field_type invalid_ref;
for (row::const_iterator it = begin(); it != end(); ++it) {
if (it->name() == colname) {
return *it;
}
}
return invalid_ref; // no match - invalid answer
}
// return the number of fields in this row
size_type num_fields() const { return size(); }
};
/*
* Representation of a complete result set (all columns and rows)
*/
class result : public std::vector<row>
{
public:
// default ctor
result() { };
// destroy result set
~result() { }
// return the number of rows in this result set
size_type num_rows() const { return size(); }
};
/*
* Database class
*/
class db
{
public:
db(std::string name, bool initial_open = true, int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE)
: name_(name)
, open_(false)
, db_(nullptr)
{
if (initial_open) {
// inital connect
(void)open(flags);
}
}
~db()
{
// close the db
(void)close();
}
// open (connect) the database
int open(int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE)
{
int err = ::sqlite3_open_v2(name_.c_str(), &db_, flags, nullptr);
open_ = !err;
return err;
}
// close the database
int close()
{
int err = ::sqlite3_close_v2(db_);
open_ = false;
db_ = nullptr;
return err;
}
// returns true if the database is open
inline bool is_open() const { return open_; }
// SQLite3 access
inline ::sqlite3* get() const { return db_; }
inline ::sqlite3* operator()() const { return db_; }
// SQLite version
inline std::string version() { return std::string(SQLITE_VERSION); }
// database defragmentation
int vacuum()
{
return ::sqlite3_exec(db_, "VACUUM;", nullptr, nullptr, nullptr);
}
private:
db& operator=(const db&) { } // no assignment
private:
::sqlite3* db_; // associated db
const std::string name_; // db filename
bool open_; // db open status
};
/*
* Representation of a query
*/
class query
{
public:
query(const db& db, const std::string& query = "")
: db_(db)
, query_(query) { }
~query() { }
// << operator for query assembly
// CAUTION: Be aware of SQL injection when directly passing user input in the query. Better use explicit binding.
template <class T>
inline query& operator<< (const T& value)
{
query_ << value;
return *this;
}
// specialized << operator to bind blobs
inline query& operator<< (std::vector<std::uint8_t> const& blob)
{
bind_type b(bind_.size() + 1U, &blob);
bind_.push_back(b);
return *this;
}
// specialized << operator to bind TEXT
inline query& operator<< (std::string const& text)
{
bind_type b(bind_.size() + 1U, &text);
bind_.push_back(b);
return *this;
}
// use "exec()" if you don't expect a result set, like a DELETE or UPDATE statement
int exec(const char* query = "") {
int err = ::sqlite3_prepare_v2(db_(), *query ? query : query_.str().c_str(), -1, &stmt_, nullptr);
query_.str("");
if (err != SQLITE_OK) { (void)::sqlite3_finalize(stmt_); return err; }
err = do_bind();
if (err != SQLITE_OK) { (void)::sqlite3_finalize(stmt_); return err; }
err = ::sqlite3_step(stmt_);
if (err != SQLITE_DONE) { (void)::sqlite3_finalize(stmt_); return err; }
return ::sqlite3_finalize(stmt_);
}
// use "use()" to get a single row. You MUST call use_next() or use_abort() after!
row use(const char* query = "") {
int err = ::sqlite3_prepare_v2(db_(), *query ? query : query_.str().c_str(), -1, &stmt_, nullptr);
query_.str("");
if (err != SQLITE_OK) { (void)::sqlite3_finalize(stmt_); return row(); }
err = do_bind();
if (err != SQLITE_OK) { (void)::sqlite3_finalize(stmt_); return row(); }
return use_next();
}
// use "use_next()" to get the next row after use()/use_next()
// call use_next() until it returns an empty row or call use_abort() to finish prematurely
row use_next() {
row _row;
if (::sqlite3_step(stmt_) == SQLITE_ROW) {
for (int i = 0; i < sqlite3_column_count(stmt_); ++i) {
switch (::sqlite3_column_type(stmt_, i))
{
case SQLITE_INTEGER:
_row.push_back(field_type(sqlite3_column_int(stmt_, i), ::sqlite3_column_name(stmt_, i)));
break;
case SQLITE_FLOAT:
_row.push_back(field_type(sqlite3_column_double(stmt_, i), ::sqlite3_column_name(stmt_, i)));
break;
case SQLITE_BLOB:
{
const std::uint8_t* blob = reinterpret_cast<const std::uint8_t*>(::sqlite3_column_blob(stmt_, i));
std::vector<std::uint8_t> v(&blob[0], &blob[::sqlite3_column_bytes(stmt_, i)]);
_row.push_back(field_type(v, ::sqlite3_column_name(stmt_, i)));
}
break;
case SQLITE_TEXT:
{
std::string text(reinterpret_cast<const char*>(::sqlite3_column_text(stmt_, i)));
_row.push_back(field_type(text, ::sqlite3_column_name(stmt_, i)));
}
break;
case SQLITE_NULL:
_row.push_back(field_type(::sqlite3_column_name(stmt_, i)));
break;
default:
_row.push_back(field_type(0, ::sqlite3_column_name(stmt_, i)));
break;
}
}
}
else {
// finalize statement
(void)::sqlite3_finalize(stmt_);
}
return _row;
}
// call this if use()/use_next() should be aborted before use_next() finished (returned an empty row)
// this is a mandatory call!
int use_abort() {
return ::sqlite3_finalize(stmt_);
}
// use "store()" if you want to get the complete result in memory
result store(const char* query = "") {
result _res;
row _row = use(query);
while (!_row.empty()) {
_res.push_back(_row);
_row = use_next();
}
return _res;
}
// return the last inserted rowid
inline std::int64_t insert_id() const { return ::sqlite3_last_insert_rowid(db_()); }
// return count of affected rows of the last statement (like in DELETE/UPDATE)
inline std::int64_t affected_rows() const { return ::sqlite3_changes(db_()); }
// bind a BLOB or TEXT to query
// CAUTION: vector and string MUST BE constant until end of query execution of exec()/use()/store()
void bind(int param, std::vector<std::uint8_t> const& blob) {
bind_type b(param, &blob);
bind_.push_back(b);
}
void bind(int param, std::string const& text) {
bind_type t(param, &text);
bind_.push_back(t);
}
void bind(const char* param, std::vector<std::uint8_t> const& blob) {
bind_type b(param, &blob);
bind_.push_back(b);
}
void bind(const char* param, std::string const& text) {
bind_type t(param, &text);
bind_.push_back(t);
}
private:
int do_bind() {
int err = SQLITE_OK;
for (std::vector<bind_type>::const_iterator it = bind_.begin(); it != bind_.end(); ++it) {
if (it->type_== SQLITE_BLOB) {
const std::vector<std::uint8_t>* v = static_cast<const std::vector<std::uint8_t>*>(it->ptr_);
err = ::sqlite3_bind_blob(stmt_, !it->param_str_ ? it->param_num_ : ::sqlite3_bind_parameter_index(stmt_, it->param_str_), v->size() ? (const void*)&(*v)[0] : nullptr, (int)v->size(), SQLITE_STATIC);
if (err != SQLITE_OK) break;
}
if (it->type_ == SQLITE_TEXT) {
const std::string* s = static_cast<const std::string*>(it->ptr_);
err = ::sqlite3_bind_text(stmt_, !it->param_str_ ? it->param_num_ : ::sqlite3_bind_parameter_index(stmt_, it->param_str_), s->size() ? s->c_str() : nullptr, (int)s->size(), SQLITE_STATIC);
if (err != SQLITE_OK) break;
}
if (it->type_ == SQLITE_NULL) {
err = ::sqlite3_bind_null(stmt_, !it->param_str_ ? it->param_num_ : ::sqlite3_bind_parameter_index(stmt_, it->param_str_));
if (err != SQLITE_OK) break;
}
}
bind_.clear(); // clear bindings
return err;
}
private:
const db& db_; // associated db
::sqlite3_stmt* stmt_; // statement
std::stringstream query_; // query
typedef struct struct_bind_type {
const void* ptr_;
const char* param_str_;
int param_num_;
int type_;
struct_bind_type(int param, const std::vector<std::uint8_t>* blob) : param_num_(param), param_str_(nullptr), ptr_(blob), type_(SQLITE_BLOB) { };
struct_bind_type(int param, const std::string* text) : param_num_(param), param_str_(nullptr), ptr_(text), type_(SQLITE_TEXT) { };
struct_bind_type(const char* param, const std::vector<std::uint8_t>* blob) : param_num_(0), param_str_(param), ptr_(blob), type_(SQLITE_BLOB) { };
struct_bind_type(const char* param, const std::string* text) : param_num_(0), param_str_(param), ptr_(text), type_(SQLITE_TEXT) { };
} bind_type;
std::vector<bind_type> bind_;
};
/*
* Representation of a transaction
*/
class transaction
{
public:
// isolation levels - see SQLite3 documentation
enum level_type {
deferred,
immediate,
exclusve
};
transaction(const db& db, level_type level = deferred)
: db_(db)
, finished_(true) // don't bother rolling it back if ctor fails
{
(void)begin(level);
}
~transaction() {
if (!finished_) { rollback(); }
}
// start transaction
int begin(level_type level = deferred) {
int err = ::sqlite3_exec(db_(), level == deferred ? "BEGIN TRANSACTION;" : (level == immediate ? "BEGIN IMMEDIATE TRANSACTION;" : "BEGIN EXCLUSIVE TRANSACTION;"), nullptr, nullptr, nullptr);
finished_ = (err != SQLITE_OK);
return err;
}
// commit transaction
int commit() {
int err = ::sqlite3_exec(db_(), "COMMIT;", nullptr, nullptr, nullptr);
finished_ = true;
return err;
}
// rollback transaction
int rollback() {
int err = ::sqlite3_exec(db_(), "ROLLBACK;", nullptr, nullptr, nullptr);
finished_ = true;
return err;
}
private:
transaction& operator=(const transaction&) { } // no assignment
private:
const db& db_;
bool finished_;
};
} // namespace sqlitepp
#endif // _SQLITEPP_H_