From 7bba7176194c4d1d9c7066f8eda7a94491d924e6 Mon Sep 17 00:00:00 2001 From: Rutger Broekhoff Date: Mon, 30 Nov 2026 21:27:55 +0100 Subject: Cleanups and updates --- server/src/database/sqlite3.cpp | 367 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 367 insertions(+) create mode 100644 server/src/database/sqlite3.cpp (limited to 'server/src/database/sqlite3.cpp') diff --git a/server/src/database/sqlite3.cpp b/server/src/database/sqlite3.cpp new file mode 100644 index 0000000..35d4fec --- /dev/null +++ b/server/src/database/sqlite3.cpp @@ -0,0 +1,367 @@ +module; + +#include + +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_)); +} + +// auto do_guarded(::sqlite3* dbc, std::invocable auto f, +// std::optional malready_locked = std::nullopt) +// -> decltype(f(std::declval())) +// { +// if (auto const mguard = malready_locked) +// return f(*mguard); +// else +// return f(mutex_guard{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 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(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 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 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 guard = nullptr) -> std::optional +{ + 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::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(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 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 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(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 -- cgit v1.3.1