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
|
module;
#include <sqlite3.h>
module routemon:database.sqlite3$impl;
import :database.sqlite3;
namespace routemon::database::sqlite3 {
mutex_guard::mutex_guard(::sqlite3* dbc) noexcept : dbc_{dbc}
{
::sqlite3_mutex_enter(::sqlite3_db_mutex(dbc_));
}
mutex_guard::~mutex_guard()
{
if (dbc_)
::sqlite3_mutex_leave(::sqlite3_db_mutex(dbc_));
}
error::error(int code, ::sqlite3* dbc)
: code_{code}, message_{::sqlite3_errmsg(dbc)}
{
}
error::error(int code) : code_{code}, message_{::sqlite3_errstr(code)} {}
[[nodiscard]] auto error::what() const noexcept -> char const*
{
return message_.c_str();
}
[[nodiscard]] auto error::code() const noexcept -> int { return code_; }
locked_statement::locked_statement(
::sqlite3_stmt* stmt, std::shared_ptr<mutex_guard> dbc_locked)
: stmt_{stmt}, guard_{std::move(dbc_locked)}
{
if (!guard_)
throw std::invalid_argument{"mutex guard may not be null"};
if (!guard_->for_db(::sqlite3_db_handle(stmt_)))
throw std::invalid_argument{
"provided mutex guard does not apply to statement's database"
};
}
locked_statement::locked_statement(locked_statement&& rhs) noexcept
: stmt_{std::exchange(rhs.stmt_, nullptr)}, guard_{std::move(rhs.guard_)}
{
}
locked_statement::~locked_statement()
{
if (stmt_)
::sqlite3_finalize(stmt_);
}
row_reader::row_reader(locked_statement&& stmt) : stmt_{std::move(stmt)} {}
auto row_reader::is_null(int col) -> bool
{
return ::sqlite3_column_type(stmt_.stmt_, col) == SQLITE_NULL;
}
auto row_reader::ncols() -> std::size_t
{
auto const mncols = util::size_from_int(::sqlite3_data_count(stmt_.stmt_));
if (!mncols.has_value())
throw std::logic_error{"got unexpected negative amount of columns"};
return *mncols;
}
auto row_reader::scan_col(int col, std::string& s) -> void
{
if (::sqlite3_column_type(stmt_.stmt_, col) != SQLITE_TEXT)
throw std::invalid_argument{"invalid type for scan"};
unsigned char const* chs = ::sqlite3_column_text(stmt_.stmt_, col);
auto size = util::size_from_int(::sqlite3_column_bytes(stmt_.stmt_, col));
if (!size.has_value())
throw std::logic_error{"unexpected negative amount of bytes in column"};
s = std::string{reinterpret_cast<char const*>(chs), *size};
}
auto row_reader::scan_col(int col, double& v) -> void
{
if (::sqlite3_column_type(stmt_.stmt_, col) != SQLITE_FLOAT)
throw std::invalid_argument{"invalid type for scan"};
v = ::sqlite3_column_double(stmt_.stmt_, col);
}
auto row_reader::scan_col(int col, std::int64_t& v) -> void
{
if (::sqlite3_column_type(stmt_.stmt_, col) != SQLITE_INTEGER)
throw std::invalid_argument{"invalid type for scan"};
v = ::sqlite3_column_int64(stmt_.stmt_, col);
}
auto row_reader::next() -> bool
{
::sqlite3* dbc = ::sqlite3_db_handle(stmt_.stmt_);
auto const s = ::sqlite3_step(stmt_.stmt_);
if (s == SQLITE_ROW)
return true;
if (s == SQLITE_DONE)
return false;
throw error{s, dbc};
}
statement::statement(locked_statement&& stmt) : stmt_{std::move(stmt)} {}
auto statement::param_idx(util::zstring_view name) -> int
{
int const i = ::sqlite3_bind_parameter_index(stmt_.stmt_, name.c_str());
if (i == 0)
throw std::invalid_argument{std::format(
"bind: no parameter with name {} found", name)};
return i;
}
auto statement::bind_null(util::zstring_view param_name) -> statement&
{
if (auto s = ::sqlite3_bind_null(stmt_.stmt_, param_idx(param_name));
s != SQLITE_OK)
throw error{s};
return *this;
}
auto statement::bind(util::zstring_view param_name, std::string_view str)
-> statement&
{
auto str_size = util::int_from_size(str.size());
if (!str_size.has_value())
throw std::invalid_argument{"bind: provided text is too long"};
if (auto s = ::sqlite3_bind_text(
stmt_.stmt_, param_idx(param_name), str.data(), *str_size,
SQLITE_TRANSIENT);
s != SQLITE_OK)
throw error{s};
return *this;
}
auto statement::bind(util::zstring_view param_name, std::int64_t x)
-> statement&
{
if (auto s = ::sqlite3_bind_int64(stmt_.stmt_, param_idx(param_name), x);
s != SQLITE_OK)
throw error{s};
return *this;
}
auto statement::bind(
util::zstring_view param_name, std::optional<std::string_view> mstr)
-> statement&
{
if (mstr)
return bind(param_name, *mstr);
else
return bind_null(param_name);
}
auto statement::bind(
util::zstring_view param_name, std::optional<std::int64_t> mx) -> statement&
{
if (mx)
return bind(param_name, *mx);
else
return bind_null(param_name);
}
auto statement::into_reader() && -> row_reader
{
return row_reader{std::move(stmt_)};
}
auto noop_binder(statement&) -> void {}
connection::connection(::sqlite3* dbc) : dbc_{dbc} {}
connection::connection(connection&& c) noexcept
{
dbc_ = c.dbc_;
c.dbc_ = nullptr;
}
auto prepare(
::sqlite3* dbc, util::zstring_view& sql,
std::shared_ptr<mutex_guard> guard = nullptr) -> std::optional<statement>
{
if (guard && !guard->for_db(dbc))
throw std::invalid_argument{
"provided mutex guard does not apply to provided database"
};
if (!guard)
guard.reset(new mutex_guard{dbc});
::sqlite3_stmt* pstmt = nullptr;
char const* sql_tail = nullptr;
auto sql_len = util::int_from_size(sql.length());
if (!sql_len.has_value() || *sql_len >= std::numeric_limits<int>::max() - 1)
throw std::invalid_argument{"provided input text too large"};
if (auto s = ::sqlite3_prepare_v2(
dbc, sql.c_str(), *sql_len + 1, &pstmt, &sql_tail);
s != SQLITE_OK)
{
if (pstmt)
{
// Use contract_assert when having a compiler with
// contracts available
::sqlite3_finalize(pstmt);
throw std::logic_error{
"expected stmt to be null after failed preparation"
};
}
throw error{s, dbc};
}
if (!pstmt)
return std::nullopt;
if (sql_tail < sql || sql_tail > sql + sql.length())
throw std::runtime_error{"expected SQL tail to be non-null"};
sql = util::zstring_view{
sql_tail, sql.length() - static_cast<std::size_t>(sql_tail - sql.c_str())
};
return statement{locked_statement{pstmt, std::move(guard)}};
}
auto do_query(
::sqlite3* dbc, util::zstring_view sql, bindfn const& bf,
std::shared_ptr<mutex_guard> guard = nullptr) -> row_reader
{
auto mstmt = prepare(dbc, sql, std::move(guard));
if (!mstmt)
throw std::invalid_argument{"provided input text contains no SQL"};
if (sql.length() > 0) // what remains after querying
throw std::invalid_argument{
"provided input text contains more than one SQL statement"
};
bf(*mstmt);
return std::move(*mstmt).into_reader();
}
auto do_exec(
::sqlite3* dbc, util::zstring_view sql, bindfn const& bf,
std::shared_ptr<mutex_guard> guard = nullptr) -> void
{
auto reader = do_query(dbc, sql, bf, std::move(guard));
while (reader.next())
;
}
auto connection::query(util::zstring_view sql, bindfn const& bf) -> row_reader
{
return do_query(dbc_, sql, bf);
}
auto connection::exec(util::zstring_view sql, bindfn const& bf) -> void
{
return do_exec(dbc_, sql, bf);
}
connection::~connection()
{
std::ignore = ::sqlite3_close(std::exchange(dbc_, nullptr));
}
auto open(std::filesystem::path const& filename) -> connection
{
::sqlite3* dbc = nullptr;
auto s = ::sqlite3_open_v2(
filename.c_str(), &dbc,
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX
| SQLITE_OPEN_EXRESCODE,
nullptr);
if (s != SQLITE_OK)
{
if (dbc)
{
throw error{s, dbc};
}
else
{
throw error{s};
}
}
auto w = connection{dbc};
w.exec("PRAGMA foreign_keys = ON");
auto foreign_keys_on = std::int64_t{};
try
{
w.query("PRAGMA foreign_keys").scan_row_max1(foreign_keys_on);
}
catch (std::exception& e)
{
throw std::runtime_error{
"used SQLite version does not seem to support foreign key enforcement"
};
}
if (foreign_keys_on != 1)
throw std::runtime_error{"failed to enable foreign key enforcement"};
return w;
}
tx::tx(connection& dbc)
: dbc_{util::not_null{&dbc}},
guard_{std::make_shared<mutex_guard>(dbc_->dbc_)}
{
exec("BEGIN");
}
[[nodiscard]] auto tx::query(util::zstring_view sql, bindfn const& bf)
-> row_reader
{
try
{
return do_query(dbc_->dbc_, sql, bf, guard_);
}
catch (std::exception const&)
{
commit_ = false;
throw;
}
}
auto tx::exec(util::zstring_view sql, bindfn const& bf) -> void
{
try
{
do_exec(dbc_->dbc_, sql, bf, guard_);
}
catch (std::exception const&)
{
commit_ = false;
throw;
}
}
auto tx::exec_first(util::zstring_view& sql) -> void
{
try
{
auto mstmt = prepare(dbc_->dbc_, sql, guard_);
if (!mstmt)
{
sql = util::zstring_view{sql.c_str() + sql.length(), 0};
return;
}
auto reader = std::move(*mstmt).into_reader();
while (reader.next())
;
}
catch (std::exception const&)
{
commit_ = false;
throw;
}
}
} // namespace routemon::database::sqlite3
|