-
Notifications
You must be signed in to change notification settings - Fork 3
/
sqlite3cpp.ipp
executable file
·416 lines (358 loc) · 12.7 KB
/
sqlite3cpp.ipp
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
/*****************************************************************************
* Copyright (c) 2019, Acer Yun-Tse Yang All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
#include <cassert>
#include <type_traits>
#include <utility>
namespace sqlite3cpp {
namespace detail {
template <int>
struct placeholder_tmpl {};
template <int... Ints>
using indexes = std::integer_sequence<int, Ints...>;
template <int Max>
using make_indexes_t = std::make_integer_sequence<int, Max>;
} // namespace detail
} // namespace sqlite3cpp
// custome placeholders
namespace std {
template <int N>
struct is_placeholder<sqlite3cpp::detail::placeholder_tmpl<N>>
: integral_constant<int, N + 1> {};
} // namespace std
namespace sqlite3cpp {
namespace detail {
/**
* tuple enumerate
*/
template <class F, class Tuple, int... I>
constexpr decltype(auto) enumerate_impl(F &&f, Tuple &&t,
std::integer_sequence<int, I...>) {
using result_type = std::invoke_result_t<
F, int, typename std::tuple_element<0, std::decay_t<Tuple>>::type>;
if constexpr (std::is_convertible_v<result_type, bool>)
return (... && std::invoke(std::forward<F>(f), I,
std::get<I>(std::forward<Tuple>(t))));
else
return (
std::invoke(std::forward<F>(f), I, std::get<I>(std::forward<Tuple>(t))),
...);
}
template <class F, class Tuple>
constexpr decltype(auto) enumerate(F &&f, Tuple &&t) {
return detail::enumerate_impl(
std::forward<F>(f), std::forward<Tuple>(t),
std::make_integer_sequence<
int, std::tuple_size_v<std::remove_reference_t<Tuple>>>{});
}
/**
* Helpers for retrieve column values.
*/
inline bool get_col_val_aux(sqlite3_stmt *stmt, sqlite3 *, int index,
int &val) {
val = sqlite3_column_int(stmt, index);
return true;
}
inline bool get_col_val_aux(sqlite3_stmt *stmt, sqlite3 *, int index,
int64_t &val) {
val = sqlite3_column_int64(stmt, index);
return true;
}
inline bool get_col_val_aux(sqlite3_stmt *stmt, sqlite3 *, int index,
double &val) {
val = sqlite3_column_double(stmt, index);
return true;
}
inline bool get_col_val_aux(sqlite3_stmt *stmt, sqlite3 *db, int index,
std::string &val) {
char const *res = (char const *)sqlite3_column_text(stmt, index);
if (!res) {
return false;
}
val.assign(res, sqlite3_column_bytes(stmt, index));
return true;
}
inline bool get_col_val_aux(sqlite3_stmt *stmt, sqlite3 *db, int index,
std::string_view &val) {
char const *res = (char const *)sqlite3_column_text(stmt, index);
if (!res) {
return false;
}
val = std::string_view{
(char const *)sqlite3_column_text(stmt, index),
(std::string_view::size_type)sqlite3_column_bytes(stmt, index)};
return true;
}
inline bool get_col_val_aux(sqlite3_stmt *stmt, sqlite3 *db, int index,
std::optional<std::string> &val) {
char const *res = (char const *)sqlite3_column_text(stmt, index);
if (!res) {
int ec = sqlite3_errcode(db);
if (ec != SQLITE_OK) val.reset();
}
val = std::string{res,
(std::string::size_type)sqlite3_column_bytes(stmt, index)};
return true;
}
inline bool get_col_val_aux(sqlite3_stmt *stmt, sqlite3 *db, int index,
std::optional<std::string_view> &val) {
char const *res = (char const *)sqlite3_column_text(stmt, index);
if (!res) {
int ec = sqlite3_errcode(db);
if (ec != SQLITE_OK) val.reset();
}
val = std::string_view{
res, (std::string_view::size_type)sqlite3_column_bytes(stmt, index)};
return true;
}
/*
* Helpers for binding values to sqlite3_stmt.
*/
inline void bind_to_stmt(sqlite3_stmt *stmt, int i) {}
inline int bind_val(sqlite3_stmt *stmt, int index, int val) {
return sqlite3_bind_int(stmt, index, val);
}
inline int bind_val(sqlite3_stmt *stmt, int index, double val) {
return sqlite3_bind_double(stmt, index, val);
}
inline int bind_val(sqlite3_stmt *stmt, int index, std::string const &val) {
return sqlite3_bind_text(stmt, index, val.c_str(), val.size(), SQLITE_STATIC);
}
inline int bind_val(sqlite3_stmt *stmt, int index, std::string_view val) {
return sqlite3_bind_text(stmt, index, val.data(), val.size(), SQLITE_STATIC);
}
inline int bind_val(sqlite3_stmt *stmt, int index, char const *val) {
return sqlite3_bind_text(stmt, index, val, -1, SQLITE_STATIC);
}
inline int bind_val(sqlite3_stmt *stmt, int index, std::nullptr_t _) {
return sqlite3_bind_null(stmt, index);
}
template <typename T, typename... Args>
void bind_to_stmt(sqlite3_stmt *stmt, int index, T &&val, Args &&...args) {
int ec = 0;
if (0 != (ec = bind_val(stmt, index, std::forward<T>(val)))) throw error(ec);
bind_to_stmt(stmt, index + 1, std::forward<Args>(args)...);
}
/**
* Helpers for converting value from sqlite3_value.
*/
template <typename T>
struct Type {};
inline int get(Type<int>, sqlite3_value **v, int const index) {
return sqlite3_value_int(v[index]);
}
inline int64_t get(Type<int64_t>, sqlite3_value **v, int const index) {
return sqlite3_value_int64(v[index]);
}
inline double get(Type<double>, sqlite3_value **v, int const index) {
return sqlite3_value_double(v[index]);
}
inline std::string get(Type<std::string>, sqlite3_value **v, int const index) {
return std::string((char const *)sqlite3_value_text(v[index]),
(size_t)sqlite3_value_bytes(v[index]));
}
inline std::string_view get(Type<std::string_view>, sqlite3_value **v,
int const index) {
return std::string_view((char const *)sqlite3_value_text(v[index]),
(size_t)sqlite3_value_bytes(v[index]));
}
/**
* Helpers for setting result of scalar functions.
*/
template <typename T>
constexpr bool can_convert_to_string_view_v =
std::is_convertible_v<std::decay_t<T>, std::string_view>;
template <typename T,
std::enable_if_t<can_convert_to_string_view_v<T>, bool> = true>
inline void result(T const &val, sqlite3_context *ctx) {
std::string_view sv(val);
sqlite3_result_text(ctx, sv.data(), sv.size(), SQLITE_TRANSIENT);
}
template <typename T,
std::enable_if_t<!can_convert_to_string_view_v<T>, bool> = true>
inline void result(T val, sqlite3_context *ctx) {
if constexpr (std::is_same_v<T, int>) {
sqlite3_result_int(ctx, val);
} else if (std::is_same_v<T, int64_t>) {
sqlite3_result_int64(ctx, val);
} else if (std::is_same_v<T, double>) {
sqlite3_result_double(ctx, val);
} else {
assert(false);
}
}
/**
* Magic for typesafe invoking lambda/std::function from sqlite3
* (registered via sqlite3_create_function).
*/
template <typename R, typename... Args, int... Is>
R invoke(std::function<R(Args...)> func, int argc, sqlite3_value **argv,
indexes<Is...>) {
// TODO Check argc
// Expand argv per index
return func(get(Type<Args>{}, argv, Is)...);
}
template <typename R, typename... Args>
R invoke(std::function<R(Args...)> func, int argc, sqlite3_value **argv) {
return invoke(func, argc, argv, make_indexes_t<sizeof...(Args)>{});
}
template <typename R, typename... Args>
auto make_invoker(std::function<R(Args...)> &&func) {
if constexpr (std::is_void_v<R>) {
return [func](sqlite3_context *ctx, int argc, sqlite3_value **argv) {
invoke(func, argc, argv);
};
} else {
return [func](sqlite3_context *ctx, int argc, sqlite3_value **argv) {
result(invoke(func, argc, argv), ctx);
};
}
}
/**
* Function traits for supporting lambda.
*/
// For generic types that are functors, delegate to its 'operator()'
template <typename T>
struct function_traits : public function_traits<decltype(&T::operator())> {};
// for pointers to member function
template <typename C, typename R, typename... Args>
struct function_traits<R (C::*)(Args...)> {
typedef std::function<R(Args...)> f_type;
static const size_t arity = sizeof...(Args);
};
// for pointers to const member function
template <typename C, typename R, typename... Args>
struct function_traits<R (C::*)(Args...) const> {
typedef std::function<R(Args...)> f_type;
static const size_t arity = sizeof...(Args);
};
// for function pointers
template <typename R, typename... Args>
struct function_traits<R (*)(Args...)> {
typedef std::function<R(Args...)> f_type;
static const size_t arity = sizeof...(Args);
};
/**
* Member function binder helpers (auto expand by passed function prototype)
*/
template <typename F, typename C, int... Is>
typename function_traits<F>::f_type bind_this(F f, C *this_, indexes<Is...>) {
return std::bind(f, this_, placeholder_tmpl<Is>{}...);
}
template <typename F, typename C>
typename function_traits<F>::f_type bind_this(F f, C *this_) {
using traits = function_traits<F>;
return bind_this(f, this_, make_indexes_t<traits::arity>{});
}
} // namespace detail
} // namespace sqlite3cpp
namespace sqlite3cpp {
/**
* row impl
*/
template <typename... Cols>
std::tuple<Cols...> row::to() const {
std::tuple<Cols...> result;
detail::enumerate(
[this](int index, auto &&tuple_value) {
return detail::get_col_val_aux(m_stmt, m_db, index, tuple_value);
},
result);
return result;
}
/**
* cursor impl
*/
template <typename... Args>
cursor &cursor::execute(std::string const &sql, Args &&...args) {
// TODO: Support rebind params
sqlite3_stmt *stmt = 0;
int ec = 0;
if (0 != (ec = sqlite3_prepare_v2(m_db, sql.c_str(), sql.size(), &stmt, 0)))
throw error(ec);
m_stmt.reset(stmt);
detail::bind_to_stmt(m_stmt.get(), 1, std::forward<Args>(args)...);
step();
return *this;
}
/**
* database impl
*/
template <typename... Args>
cursor database::execute(std::string const &sql, Args &&...args) {
cursor c = make_cursor();
c.execute(sql, std::forward<Args>(args)...);
return c;
}
template <typename FUNC>
void database::create_scalar(std::string const &name, FUNC func, int flags) {
using traits = detail::function_traits<FUNC>;
auto xfunc_ptr = std::make_unique<xfunc_t>(
detail::make_invoker(typename traits::f_type(func)));
int ec = 0;
if (0 !=
(ec = sqlite3_create_function_v2(
m_db.get(), name.c_str(), (int)traits::arity, flags,
(void *)xfunc_ptr.release(), &database::forward, 0, 0, &dispose))) {
throw error(ec);
}
}
template <typename AG>
void database::create_aggregate(std::string const &name, int flags) {
using detail::bind_this;
using detail::make_invoker;
using detail::result;
using traits = detail::function_traits<decltype(&AG::step)>;
aggregate_wrapper_t *wrapper = new aggregate_wrapper_t;
AG *inst = new AG;
wrapper->reset = [inst]() {
inst->~AG();
new (inst) AG();
};
wrapper->release = [inst]() { delete inst; };
wrapper->step = make_invoker(bind_this(&AG::step, inst));
wrapper->fin = [inst](sqlite3_context *ctx) {
result(inst->finalize(), ctx);
};
int ec = 0;
if (0 != (ec = sqlite3_create_function_v2(
m_db.get(), name.c_str(), (int)traits::arity, flags,
(void *)wrapper, 0, &step_ag, &final_ag, &dispose_ag))) {
delete inst;
delete wrapper;
throw error(ec);
}
}
inline void database::dispose(void *user_data) {
auto *cb = (xfunc_t *)user_data;
assert(cb != 0);
delete cb;
}
} // namespace sqlite3cpp