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.cpp318
1 files changed, 226 insertions, 92 deletions
diff --git a/server/src/sqlite3.cpp b/server/src/sqlite3.cpp
index 3e0d64a..243cf41 100644
--- a/server/src/sqlite3.cpp
+++ b/server/src/sqlite3.cpp
@@ -8,23 +8,28 @@ import :sqlite3;
8 8
9namespace routemon::sqlite3 { 9namespace routemon::sqlite3 {
10 10
11mutex_guard::mutex_guard(::sqlite3_mutex* mut) noexcept : mut_{mut} {} 11mutex_guard::mutex_guard(::sqlite3* dbc) noexcept : dbc_{dbc}
12
13mutex_guard::~mutex_guard() { ::sqlite3_mutex_leave(mut_); }
14
15auto do_guarded(::sqlite3_mutex* mut, std::invocable<mutex_guard const&> auto f)
16 -> decltype(f(std::declval<mutex_guard const&>()))
17{ 12{
18 return f(mutex_guard{mut}); 13 ::sqlite3_mutex_enter(::sqlite3_db_mutex(dbc_));
19} 14}
20 15
21auto do_guarded(::sqlite3* dbc, std::invocable<mutex_guard const&> auto f) 16mutex_guard::~mutex_guard()
22 -> decltype(f(std::declval<mutex_guard const&>()))
23{ 17{
24 return do_guarded(::sqlite3_db_mutex(dbc), f); 18 if (dbc_)
19 ::sqlite3_mutex_leave(::sqlite3_db_mutex(dbc_));
25} 20}
26 21
27error::error(mutex_guard const&, int code, ::sqlite3* dbc) 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)
28 : code_{code}, message_{::sqlite3_errmsg(dbc)} 33 : code_{code}, message_{::sqlite3_errmsg(dbc)}
29{ 34{
30} 35}
@@ -38,161 +43,234 @@ error::error(int code) : code_{code}, message_{::sqlite3_errstr(code)} {}
38 43
39[[nodiscard]] auto error::code() const noexcept -> int { return code_; } 44[[nodiscard]] auto error::code() const noexcept -> int { return code_; }
40 45
41statement::statement(::sqlite3_stmt* stmt) : stmt_{stmt} {} 46locked_statement::locked_statement(
42statement::statement(statement&& s) noexcept 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_)}
43{ 59{
44 stmt_ = s.stmt_;
45 s.stmt_ = nullptr;
46} 60}
47statement::~statement() { ::sqlite3_finalize(stmt_); } 61locked_statement::~locked_statement()
48auto statement::get() -> ::sqlite3_stmt* { return stmt_; } 62{
63 if (stmt_)
64 ::sqlite3_finalize(stmt_);
65}
49 66
50row_reader::row_reader(statement stmt) : stmt_{std::move(stmt)} {} 67row_reader::row_reader(locked_statement&& stmt) : stmt_{std::move(stmt)} {}
51 68
52auto row_reader::is_null(int col) -> bool 69auto row_reader::is_null(int col) -> bool
53{ 70{
54 return ::sqlite3_column_type(stmt_.get(), col) == SQLITE_NULL; 71 return ::sqlite3_column_type(stmt_.stmt_, col) == SQLITE_NULL;
55} 72}
56 73
57auto row_reader::ncols() -> std::size_t 74auto row_reader::ncols() -> std::size_t
58{ 75{
59 auto const mncols = util::size_from_int(::sqlite3_data_count(stmt_.get())); 76 auto const mncols = util::size_from_int(::sqlite3_data_count(stmt_.stmt_));
60 if (!mncols.has_value()) 77 if (!mncols.has_value())
61 throw std::logic_error{"got unexpected negative amount of columns"}; 78 throw std::logic_error{"got unexpected negative amount of columns"};
62 return *mncols; 79 return *mncols;
63} 80}
64 81
65auto row_reader::scan(int col, std::string& s) -> void 82auto row_reader::scan_col(int col, std::string& s) -> void
66{ 83{
67 if (::sqlite3_column_type(stmt_.get(), col) != SQLITE_TEXT) 84 if (::sqlite3_column_type(stmt_.stmt_, col) != SQLITE_TEXT)
68 throw std::invalid_argument{"invalid type for scan"}; 85 throw std::invalid_argument{"invalid type for scan"};
69 unsigned char const* chs = ::sqlite3_column_text(stmt_.get(), col); 86 unsigned char const* chs = ::sqlite3_column_text(stmt_.stmt_, col);
70 auto size = util::size_from_int(::sqlite3_column_bytes(stmt_.get(), col)); 87 auto size = util::size_from_int(::sqlite3_column_bytes(stmt_.stmt_, col));
71 if (!size.has_value()) 88 if (!size.has_value())
72 throw std::logic_error{"unexpected negative amount of bytes in column"}; 89 throw std::logic_error{"unexpected negative amount of bytes in column"};
73 s = std::string{reinterpret_cast<char const*>(chs), *size}; 90 s = std::string{reinterpret_cast<char const*>(chs), *size};
74} 91}
75 92
76auto row_reader::scan(int col, double& v) -> void 93auto row_reader::scan_col(int col, double& v) -> void
77{ 94{
78 if (::sqlite3_column_type(stmt_.get(), col) != SQLITE_FLOAT) 95 if (::sqlite3_column_type(stmt_.stmt_, col) != SQLITE_FLOAT)
79 throw std::invalid_argument{"invalid type for scan"}; 96 throw std::invalid_argument{"invalid type for scan"};
80 v = ::sqlite3_column_double(stmt_.get(), col); 97 v = ::sqlite3_column_double(stmt_.stmt_, col);
81} 98}
82 99
83auto row_reader::scan(int col, std::int64_t& v) -> void 100auto row_reader::scan_col(int col, std::int64_t& v) -> void
84{ 101{
85 if (::sqlite3_column_type(stmt_.get(), col) != SQLITE_INTEGER) 102 if (::sqlite3_column_type(stmt_.stmt_, col) != SQLITE_INTEGER)
86 throw std::invalid_argument{"invalid type for scan"}; 103 throw std::invalid_argument{"invalid type for scan"};
87 v = ::sqlite3_column_int64(stmt_.get(), col); 104 v = ::sqlite3_column_int64(stmt_.stmt_, col);
88} 105}
89 106
90auto row_reader::next() -> bool 107auto row_reader::next() -> bool
91{ 108{
92 ::sqlite3* dbc = ::sqlite3_db_handle(stmt_.get()); 109 ::sqlite3* dbc = ::sqlite3_db_handle(stmt_.stmt_);
93 return do_guarded( 110 auto const s = ::sqlite3_step(stmt_.stmt_);
94 dbc, 111 if (s == SQLITE_ROW)
95 [&](auto const& guard) -> bool 112 return true;
96 { 113 if (s == SQLITE_DONE)
97 auto const s = ::sqlite3_step(stmt_.get()); 114 return false;
98 if (s == SQLITE_ROW) 115 throw error{s, dbc};
99 return true;
100 if (s == SQLITE_DONE)
101 return false;
102 throw error{guard, s, dbc};
103 });
104} 116}
105 117
106binder::binder(statement& stmt) : stmt_{stmt} {} 118statement::statement(locked_statement&& stmt) : stmt_{std::move(stmt)} {}
107 119
108auto binder::text(std::string const& param_name, std::string_view str) -> void 120auto statement::param_idx(util::zstring_view name) -> int
109{ 121{
110 int const i = ::sqlite3_bind_parameter_index(stmt_.get(), param_name.c_str()); 122 int const i = ::sqlite3_bind_parameter_index(stmt_.stmt_, name.c_str());
111 if (i == 0) 123 if (i == 0)
112 throw std::invalid_argument{std::format( 124 throw std::invalid_argument{std::format(
113 "bind: no parameter with name {} found", param_name)}; 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{
114 auto str_size = util::int_from_size(str.size()); 140 auto str_size = util::int_from_size(str.size());
115 if (!str_size.has_value()) 141 if (!str_size.has_value())
116 throw std::invalid_argument{"bind: provided text is too long"}; 142 throw std::invalid_argument{"bind: provided text is too long"};
117 if (auto s = ::sqlite3_bind_text( 143 if (auto s = ::sqlite3_bind_text(
118 stmt_.get(), i, str.data(), *str_size, SQLITE_TRANSIENT); 144 stmt_.stmt_, param_idx(param_name), str.data(), *str_size,
145 SQLITE_TRANSIENT);
119 s != SQLITE_OK) 146 s != SQLITE_OK)
120 {
121 throw error{s}; 147 throw error{s};
122 } 148 return *this;
123} 149}
124 150
125auto binder::noop(binder&) -> void {} 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}
126 178
127connection::connection(::sqlite3* dbc) 179auto statement::into_reader() && -> row_reader
128 : dbc_{dbc}, mut_{::sqlite3_db_mutex(dbc)}
129{ 180{
181 return row_reader{std::move(stmt_)};
130} 182}
131 183
132connection::connection(connection const&) = delete; 184auto noop_binder(statement&) -> void {}
185
186connection::connection(::sqlite3* dbc) : dbc_{dbc} {}
187
133connection::connection(connection&& c) noexcept 188connection::connection(connection&& c) noexcept
134{ 189{
135 dbc_ = c.dbc_; 190 dbc_ = c.dbc_;
136 mut_ = c.mut_;
137 c.dbc_ = nullptr; 191 c.dbc_ = nullptr;
138 c.mut_ = nullptr;
139} 192}
140 193
141auto connection::query( 194auto prepare(
142 std::string const& sql, std::function<void(binder&)> const& bf) 195 ::sqlite3* dbc, util::zstring_view& sql,
143 -> row_reader 196 std::shared_ptr<mutex_guard> guard = nullptr) -> std::optional<statement>
144{ 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});
145 ::sqlite3_stmt* pstmt = nullptr; 204 ::sqlite3_stmt* pstmt = nullptr;
146 char const* sql_tail = nullptr; 205 char const* sql_tail = nullptr;
147 auto sql_size = util::int_from_size(sql.size()); 206 auto sql_len = util::int_from_size(sql.length());
148 if (!sql_size.has_value() || *sql_size >= std::numeric_limits<int>::max() - 1) 207 if (!sql_len.has_value() || *sql_len >= std::numeric_limits<int>::max() - 1)
149 throw std::invalid_argument{"provided input text too large"}; 208 throw std::invalid_argument{"provided input text too large"};
150 do_guarded( 209 if (auto s = ::sqlite3_prepare_v2(
151 mut_, 210 dbc, sql.c_str(), *sql_len + 1, &pstmt, &sql_tail);
152 [&](auto const& guard) -> void 211 s != SQLITE_OK)
153 { 212 {
154 if (auto s = ::sqlite3_prepare_v2( 213 if (pstmt)
155 dbc_, sql.data(), *sql_size + 1, &pstmt, &sql_tail); 214 {
156 s != SQLITE_OK) 215 // Use contract_assert when having a compiler with
157 { 216 // contracts available
158 if (pstmt != nullptr) 217 ::sqlite3_finalize(pstmt);
159 { 218 throw std::logic_error{
160 // Use contract_assert when having a compiler with 219 "expected stmt to be null after failed preparation"
161 // contracts available 220 };
162 ::sqlite3_finalize(pstmt); 221 }
163 throw std::logic_error{ 222 throw error{s, dbc};
164 "expected stmt to be null after failed preparation" 223 }
165 };
166 }
167 throw error{guard, s, dbc_};
168 }
169 });
170 if (!pstmt) 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)
171 throw std::invalid_argument{"provided input text contains no SQL"}; 240 throw std::invalid_argument{"provided input text contains no SQL"};
172 auto stmt = statement{pstmt}; 241 if (sql.length() > 0) // what remains after querying
173 if (sql_tail && std::strlen(sql_tail) > 0)
174 throw std::invalid_argument{ 242 throw std::invalid_argument{
175 "provided input text contains more than one SQL statement" 243 "provided input text contains more than one SQL statement"
176 }; 244 };
177 auto b = binder{stmt}; 245 bf(*mstmt);
178 bf(b); 246 return std::move(*mstmt).into_reader();
179 return row_reader{std::move(stmt)};
180} 247}
181 248
182auto connection::exec( 249auto do_exec(
183 std::string const& sql, std::function<void(binder&)> const& bf) -> void 250 ::sqlite3* dbc, util::zstring_view sql, bindfn const& bf,
251 std::shared_ptr<mutex_guard> guard = nullptr) -> void
184{ 252{
185 auto reader = query(sql, bf); 253 auto reader = do_query(dbc, sql, bf, std::move(guard));
186 while (reader.next()) 254 while (reader.next())
187 ; 255 ;
188} 256}
189 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
190connection::~connection() 268connection::~connection()
191{ 269{
192 std::ignore = ::sqlite3_close(std::exchange(dbc_, nullptr)); 270 std::ignore = ::sqlite3_close(std::exchange(dbc_, nullptr));
193} 271}
194 272
195auto open(std::string const& filename) -> connection 273auto open(util::zstring_view filename) -> connection
196{ 274{
197 ::sqlite3* dbc = nullptr; 275 ::sqlite3* dbc = nullptr;
198 auto s = ::sqlite3_open_v2( 276 auto s = ::sqlite3_open_v2(
@@ -204,15 +282,71 @@ auto open(std::string const& filename) -> connection
204 { 282 {
205 if (dbc) 283 if (dbc)
206 { 284 {
207 do_guarded( 285 throw error{s, dbc};
208 dbc, [&](auto const& guard) -> void { throw error{guard, s, dbc}; });
209 } 286 }
210 else 287 else
211 { 288 {
212 throw error{s}; 289 throw error{s};
213 } 290 }
214 } 291 }
215 return connection{dbc}; 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 }
216} 350}
217 351
218} // namespace routemon::sqlite3 352} // namespace routemon::sqlite3