summaryrefslogtreecommitdiffstats
path: root/server/src/sqlite3.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'server/src/sqlite3.cpp')
-rw-r--r--server/src/sqlite3.cpp352
1 files changed, 0 insertions, 352 deletions
diff --git a/server/src/sqlite3.cpp b/server/src/sqlite3.cpp
deleted file mode 100644
index 243cf41..0000000
--- a/server/src/sqlite3.cpp
+++ /dev/null
@@ -1,352 +0,0 @@
1module;
2
3#include <sqlite3.h>
4
5module routemon:sqlite3$impl;
6
7import :sqlite3;
8
9namespace routemon::sqlite3 {
10
11mutex_guard::mutex_guard(::sqlite3* dbc) noexcept : dbc_{dbc}
12{
13 ::sqlite3_mutex_enter(::sqlite3_db_mutex(dbc_));
14}
15
16mutex_guard::~mutex_guard()
17{
18 if (dbc_)
19 ::sqlite3_mutex_leave(::sqlite3_db_mutex(dbc_));
20}
21
22// auto do_guarded(::sqlite3* dbc, std::invocable<mutex_guard const&> auto f,
23// std::optional<mutex_guard const&> malready_locked = std::nullopt)
24// -> decltype(f(std::declval<mutex_guard const&>()))
25// {
26// if (auto const mguard = malready_locked)
27// return f(*mguard);
28// else
29// return f(mutex_guard{dbc});
30// }
31
32error::error(int code, ::sqlite3* dbc)
33 : code_{code}, message_{::sqlite3_errmsg(dbc)}
34{
35}
36
37error::error(int code) : code_{code}, message_{::sqlite3_errstr(code)} {}
38
39[[nodiscard]] auto error::what() const noexcept -> char const*
40{
41 return message_.c_str();
42}
43
44[[nodiscard]] auto error::code() const noexcept -> int { return code_; }
45
46locked_statement::locked_statement(
47 ::sqlite3_stmt* stmt, std::shared_ptr<mutex_guard> dbc_locked)
48 : stmt_{stmt}, guard_{std::move(dbc_locked)}
49{
50 if (!guard_)
51 throw std::invalid_argument{"mutex guard may not be null"};
52 if (!guard_->for_db(::sqlite3_db_handle(stmt_)))
53 throw std::invalid_argument{
54 "provided mutex guard does not apply to statement's database"
55 };
56}
57locked_statement::locked_statement(locked_statement&& rhs) noexcept
58 : stmt_{std::exchange(rhs.stmt_, nullptr)}, guard_{std::move(rhs.guard_)}
59{
60}
61locked_statement::~locked_statement()
62{
63 if (stmt_)
64 ::sqlite3_finalize(stmt_);
65}
66
67row_reader::row_reader(locked_statement&& stmt) : stmt_{std::move(stmt)} {}
68
69auto row_reader::is_null(int col) -> bool
70{
71 return ::sqlite3_column_type(stmt_.stmt_, col) == SQLITE_NULL;
72}
73
74auto row_reader::ncols() -> std::size_t
75{
76 auto const mncols = util::size_from_int(::sqlite3_data_count(stmt_.stmt_));
77 if (!mncols.has_value())
78 throw std::logic_error{"got unexpected negative amount of columns"};
79 return *mncols;
80}
81
82auto row_reader::scan_col(int col, std::string& s) -> void
83{
84 if (::sqlite3_column_type(stmt_.stmt_, col) != SQLITE_TEXT)
85 throw std::invalid_argument{"invalid type for scan"};
86 unsigned char const* chs = ::sqlite3_column_text(stmt_.stmt_, col);
87 auto size = util::size_from_int(::sqlite3_column_bytes(stmt_.stmt_, col));
88 if (!size.has_value())
89 throw std::logic_error{"unexpected negative amount of bytes in column"};
90 s = std::string{reinterpret_cast<char const*>(chs), *size};
91}
92
93auto row_reader::scan_col(int col, double& v) -> void
94{
95 if (::sqlite3_column_type(stmt_.stmt_, col) != SQLITE_FLOAT)
96 throw std::invalid_argument{"invalid type for scan"};
97 v = ::sqlite3_column_double(stmt_.stmt_, col);
98}
99
100auto row_reader::scan_col(int col, std::int64_t& v) -> void
101{
102 if (::sqlite3_column_type(stmt_.stmt_, col) != SQLITE_INTEGER)
103 throw std::invalid_argument{"invalid type for scan"};
104 v = ::sqlite3_column_int64(stmt_.stmt_, col);
105}
106
107auto row_reader::next() -> bool
108{
109 ::sqlite3* dbc = ::sqlite3_db_handle(stmt_.stmt_);
110 auto const s = ::sqlite3_step(stmt_.stmt_);
111 if (s == SQLITE_ROW)
112 return true;
113 if (s == SQLITE_DONE)
114 return false;
115 throw error{s, dbc};
116}
117
118statement::statement(locked_statement&& stmt) : stmt_{std::move(stmt)} {}
119
120auto statement::param_idx(util::zstring_view name) -> int
121{
122 int const i = ::sqlite3_bind_parameter_index(stmt_.stmt_, name.c_str());
123 if (i == 0)
124 throw std::invalid_argument{std::format(
125 "bind: no parameter with name {} found", name)};
126 return i;
127}
128
129auto statement::bind_null(util::zstring_view param_name) -> statement&
130{
131 if (auto s = ::sqlite3_bind_null(stmt_.stmt_, param_idx(param_name));
132 s != SQLITE_OK)
133 throw error{s};
134 return *this;
135}
136
137auto statement::bind(util::zstring_view param_name, std::string_view str)
138 -> statement&
139{
140 auto str_size = util::int_from_size(str.size());
141 if (!str_size.has_value())
142 throw std::invalid_argument{"bind: provided text is too long"};
143 if (auto s = ::sqlite3_bind_text(
144 stmt_.stmt_, param_idx(param_name), str.data(), *str_size,
145 SQLITE_TRANSIENT);
146 s != SQLITE_OK)
147 throw error{s};
148 return *this;
149}
150
151auto statement::bind(util::zstring_view param_name, std::int64_t x)
152 -> statement&
153{
154 if (auto s = ::sqlite3_bind_int64(stmt_.stmt_, param_idx(param_name), x);
155 s != SQLITE_OK)
156 throw error{s};
157 return *this;
158}
159
160auto statement::bind(
161 util::zstring_view param_name, std::optional<std::string_view> mstr)
162 -> statement&
163{
164 if (mstr)
165 return bind(param_name, *mstr);
166 else
167 return bind_null(param_name);
168}
169
170auto statement::bind(
171 util::zstring_view param_name, std::optional<std::int64_t> mx) -> statement&
172{
173 if (mx)
174 return bind(param_name, *mx);
175 else
176 return bind_null(param_name);
177}
178
179auto statement::into_reader() && -> row_reader
180{
181 return row_reader{std::move(stmt_)};
182}
183
184auto noop_binder(statement&) -> void {}
185
186connection::connection(::sqlite3* dbc) : dbc_{dbc} {}
187
188connection::connection(connection&& c) noexcept
189{
190 dbc_ = c.dbc_;
191 c.dbc_ = nullptr;
192}
193
194auto prepare(
195 ::sqlite3* dbc, util::zstring_view& sql,
196 std::shared_ptr<mutex_guard> guard = nullptr) -> std::optional<statement>
197{
198 if (guard && !guard->for_db(dbc))
199 throw std::invalid_argument{
200 "provided mutex guard does not apply to provided database"
201 };
202 if (!guard)
203 guard.reset(new mutex_guard{dbc});
204 ::sqlite3_stmt* pstmt = nullptr;
205 char const* sql_tail = nullptr;
206 auto sql_len = util::int_from_size(sql.length());
207 if (!sql_len.has_value() || *sql_len >= std::numeric_limits<int>::max() - 1)
208 throw std::invalid_argument{"provided input text too large"};
209 if (auto s = ::sqlite3_prepare_v2(
210 dbc, sql.c_str(), *sql_len + 1, &pstmt, &sql_tail);
211 s != SQLITE_OK)
212 {
213 if (pstmt)
214 {
215 // Use contract_assert when having a compiler with
216 // contracts available
217 ::sqlite3_finalize(pstmt);
218 throw std::logic_error{
219 "expected stmt to be null after failed preparation"
220 };
221 }
222 throw error{s, dbc};
223 }
224 if (!pstmt)
225 return std::nullopt;
226 if (sql_tail < sql || sql_tail > sql + sql.length())
227 throw std::runtime_error{"expected SQL tail to be non-null"};
228 sql = util::zstring_view{
229 sql_tail, sql.length() - static_cast<std::size_t>(sql_tail - sql.c_str())
230 };
231 return statement{locked_statement{pstmt, std::move(guard)}};
232}
233
234auto do_query(
235 ::sqlite3* dbc, util::zstring_view sql, bindfn const& bf,
236 std::shared_ptr<mutex_guard> guard = nullptr) -> row_reader
237{
238 auto mstmt = prepare(dbc, sql, std::move(guard));
239 if (!mstmt)
240 throw std::invalid_argument{"provided input text contains no SQL"};
241 if (sql.length() > 0) // what remains after querying
242 throw std::invalid_argument{
243 "provided input text contains more than one SQL statement"
244 };
245 bf(*mstmt);
246 return std::move(*mstmt).into_reader();
247}
248
249auto do_exec(
250 ::sqlite3* dbc, util::zstring_view sql, bindfn const& bf,
251 std::shared_ptr<mutex_guard> guard = nullptr) -> void
252{
253 auto reader = do_query(dbc, sql, bf, std::move(guard));
254 while (reader.next())
255 ;
256}
257
258auto connection::query(util::zstring_view sql, bindfn const& bf) -> row_reader
259{
260 return do_query(dbc_, sql, bf);
261}
262
263auto connection::exec(util::zstring_view sql, bindfn const& bf) -> void
264{
265 return do_exec(dbc_, sql, bf);
266}
267
268connection::~connection()
269{
270 std::ignore = ::sqlite3_close(std::exchange(dbc_, nullptr));
271}
272
273auto open(util::zstring_view filename) -> connection
274{
275 ::sqlite3* dbc = nullptr;
276 auto s = ::sqlite3_open_v2(
277 filename.c_str(), &dbc,
278 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX
279 | SQLITE_OPEN_EXRESCODE,
280 nullptr);
281 if (s != SQLITE_OK)
282 {
283 if (dbc)
284 {
285 throw error{s, dbc};
286 }
287 else
288 {
289 throw error{s};
290 }
291 }
292 auto w = connection{dbc};
293 w.exec("PRAGMA foreign_keys = ON");
294 return w;
295}
296
297tx::tx(connection& dbc)
298 : dbc_{util::not_null{&dbc}},
299 guard_{std::make_shared<mutex_guard>(dbc_->dbc_)}
300{
301 exec("BEGIN");
302}
303
304[[nodiscard]] auto tx::query(util::zstring_view sql, bindfn const& bf)
305 -> row_reader
306{
307 try
308 {
309 return do_query(dbc_->dbc_, sql, bf, guard_);
310 }
311 catch (std::exception const&)
312 {
313 commit_ = false;
314 throw;
315 }
316}
317
318auto tx::exec(util::zstring_view sql, bindfn const& bf) -> void
319{
320 try
321 {
322 do_exec(dbc_->dbc_, sql, bf, guard_);
323 }
324 catch (std::exception const&)
325 {
326 commit_ = false;
327 throw;
328 }
329}
330
331auto tx::exec_first(util::zstring_view& sql) -> void
332{
333 try
334 {
335 auto mstmt = prepare(dbc_->dbc_, sql, guard_);
336 if (!mstmt)
337 {
338 sql = util::zstring_view{sql.c_str() + sql.length(), 0};
339 return;
340 }
341 auto reader = std::move(*mstmt).into_reader();
342 while (reader.next())
343 ;
344 }
345 catch (std::exception const&)
346 {
347 commit_ = false;
348 throw;
349 }
350}
351
352} // namespace routemon::sqlite3