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/connection.cpp | 78 ++++++++ server/src/database/connection.cppm | 30 +++ server/src/database/migrator.cpp | 122 ++++++++++++ server/src/database/migrator.cppm | 26 +++ server/src/database/schema.cpp | 59 ++++++ server/src/database/schema.cppm | 67 +++++++ server/src/database/sqlite3.cpp | 367 ++++++++++++++++++++++++++++++++++++ server/src/database/sqlite3.cppm | 222 ++++++++++++++++++++++ 8 files changed, 971 insertions(+) create mode 100644 server/src/database/connection.cpp create mode 100644 server/src/database/connection.cppm create mode 100644 server/src/database/migrator.cpp create mode 100644 server/src/database/migrator.cppm create mode 100644 server/src/database/schema.cpp create mode 100644 server/src/database/schema.cppm create mode 100644 server/src/database/sqlite3.cpp create mode 100644 server/src/database/sqlite3.cppm (limited to 'server/src/database') diff --git a/server/src/database/connection.cpp b/server/src/database/connection.cpp new file mode 100644 index 0000000..fcdf15f --- /dev/null +++ b/server/src/database/connection.cpp @@ -0,0 +1,78 @@ +module routemon:database.connection$impl; + +import :database.connection; + +namespace routemon::database { + +auto connection::insert_rwgps_notifications( + std::vector + >>& notifs) -> void +{ + auto tx = sqlite3::tx{dbc_}; + for (auto& [notif, mtarget_collection] : notifs) + { + tx.query( + "INSERT INTO rwgps_notification " + " (rwgps_timestamp, user_id, item_type, item_id, " + " item_user_id, item_url, action_) " + "VALUES (:rwgps_timestamp, :user_id, :item_type, :item_id, " + " :item_user_id, :item_url, :action) " + "RETURNING id", + [¬if](auto& s) + { + auto const ts = time::iso8601_secs(notif.rwgps_timestamp); + s.bind(":rwgps_timestamp", std::string_view{ts}); + s.bind(":user_id", notif.user_id); + s.bind(":item_type", try_to_string(notif.item_type)); + s.bind(":item_id", notif.item_id); + s.bind(":item_user_id", notif.item_user_id); + s.bind(":item_url", notif.item_url); + s.bind(":action", try_to_string(notif.action)); + }) + .scan_row_max1(notif.id); + + if (mtarget_collection) + { + tx.exec( + "INSERT INTO rwgps_notification_target_collection " + " (notification_id, id, type_, url) " + "VALUES (:notification_id, :id, :type, :url)", + [¬if, &mtarget_collection](auto& s) + { + s.bind(":notification_id", notif.id); + s.bind(":id", mtarget_collection->id); + s.bind(":type", try_to_string(mtarget_collection->type)); + s.bind(":url", mtarget_collection->url); + }); + } + } +} + +auto open(std::filesystem::path const& filename) -> std::shared_ptr +{ + auto dbc = sqlite3::open(filename); + try + { + auto mversion = std::optional{}; + dbc.query("SELECT version FROM migration;").scan_row_max1(mversion); + if (!mversion) + throw std::runtime_error{"failed to fetch database migration version"}; + if (mversion != schema::expected_version) + { + throw std::runtime_error{std::format( + "database migration version ({}) does not match expected " + "version ({}), consider running migrations", + *mversion, schema::expected_version)}; + } + } + catch (std::exception const& e) + { + throw std::runtime_error{std::format( + "failed to query database version: {}", e.what())}; + } + return std::shared_ptr{new connection{std::move(dbc)}}; +} + +} // namespace routemon::database diff --git a/server/src/database/connection.cppm b/server/src/database/connection.cppm new file mode 100644 index 0000000..22e6495 --- /dev/null +++ b/server/src/database/connection.cppm @@ -0,0 +1,30 @@ +export module routemon:database.connection; + +import std; +import :database.schema; +import :database.sqlite3; +import :time; + +namespace routemon::database { + +export class connection +{ + sqlite3::connection dbc_; + + explicit connection(sqlite3::connection dbc) : dbc_{std::move(dbc)} {} + + friend auto open(std::filesystem::path const& filename) + -> std::shared_ptr; + +public: + auto insert_rwgps_notifications( + std::vector + >>& notifs) -> void; +}; + +export auto open(std::filesystem::path const& filename) + -> std::shared_ptr; + +} // namespace routemon::database diff --git a/server/src/database/migrator.cpp b/server/src/database/migrator.cpp new file mode 100644 index 0000000..d6c7926 --- /dev/null +++ b/server/src/database/migrator.cpp @@ -0,0 +1,122 @@ +module; + +#include + +export module routemon:database.migrator$impl; + +import :database.migrator; + +namespace routemon::database { + +auto load_migrations( + std::filesystem::path const& dir, std::int64_t current_version, + std::int64_t target_version) -> std::vector +{ + if (current_version < 0 || target_version < 0) + throw std::invalid_argument{"database versions must be nonnegative"}; + if (target_version < current_version) + throw std::runtime_error{"migrating down is not supported yet"}; + if (current_version == target_version) + return {}; + assert(current_version < target_version); + + // TODO: narrow_cast or something like that + auto migration_sqls = + std::vector>>{ + static_cast(target_version - current_version) + }; + for (auto const& entry : std::filesystem::directory_iterator{dir}) + { + if (!std::filesystem::is_regular_file(entry.status())) + continue; + auto const filename = std::string{entry.path().filename()}; + if (!filename.ends_with("_up.sql")) + continue; + auto const [no_str, mrest] = util::split_on(filename, '_'); + if (!mrest) + continue; + auto const mno = util::parse_int(no_str); + if (!mno || *mno < 1) + continue; + if (*mno <= current_version || target_version < *mno) + continue; + auto const i = static_cast(*mno - current_version - 1); + + if (migration_sqls[i]) + throw std::runtime_error{std::format( + "found more than one (up) migration file for version {}", *mno)}; + + auto f = std::ifstream{entry.path(), std::ios::binary}; + auto contents = std::string{ + std::istreambuf_iterator{f}, + std::istreambuf_iterator{}, + }; + + migration_sqls[i] = {entry.path(), contents}; + } + + return migration_sqls | std::views::enumerate + | std::views::transform( + [current_version](auto&& pair) -> std::string + { + auto&& [i, mentry] = pair; + if (!mentry) + throw std::runtime_error{std::format( + "no migration found to version {}", + current_version + i + 1)}; + return std::move(mentry->second); + }) + | std::ranges::to>(); +} + +auto migrator::current_version() -> std::int64_t +{ + if (auto const [has_migrations_table] = + dbc_.query( + "SELECT COUNT(*) FROM sqlite_schema WHERE " + "type IS 'table' AND " + "name IS 'migration'") + .scan_row_max1(); + has_migrations_table) + return std::get<0>(dbc_.query("SELECT version FROM migration") + .scan_row_max1()); + return 0; +} + +migrator::migrator( + log::logger const& l, std::filesystem::path const& db_filename, + std::filesystem::path migrations_dir) + : l_{l.sub("migrator")}, dbc_{sqlite3::open(db_filename)}, + migrations_dir_{std::move(migrations_dir)} +{ +} + +auto migrator::migrate_to(std::int64_t target_version) -> void +{ + // Part of function contract. Consider throwing instead? + if (target_version < 0) + throw std::invalid_argument{"target database version must be nonnegative"}; + + auto current = current_version(); + auto const migration_sqls = + load_migrations(migrations_dir_, current, target_version); + + for (auto const& sql : migration_sqls) + { + l_.info("Migrating from schema version {} to {}", current, current + 1); + migrate_step(++current, sql); + } +} + +auto migrator::migrate_step(std::int64_t target_version, util::zstring_view sql) + -> void +{ + auto tx = sqlite3::tx{dbc_}; + while (!sql.empty()) + tx.exec_first(sql); + tx.exec( + "UPDATE migration SET version = :version", + [target_version](auto& s) { s.bind(":version", target_version); }); +} + +} // namespace routemon::database diff --git a/server/src/database/migrator.cppm b/server/src/database/migrator.cppm new file mode 100644 index 0000000..d7fbfc3 --- /dev/null +++ b/server/src/database/migrator.cppm @@ -0,0 +1,26 @@ +export module routemon:database.migrator; + +import :database.sqlite3; +import :log; + +namespace routemon::database { + +export class migrator +{ + log::logger l_; + sqlite3::connection dbc_; + std::filesystem::path migrations_dir_; + + auto current_version() -> std::int64_t; + +public: + explicit migrator( + log::logger const& l, std::filesystem::path const& db_filename, + std::filesystem::path migrations_dir); + + auto migrate_to(std::int64_t target_version) -> void; + auto migrate_step(std::int64_t target_version, util::zstring_view sql) + -> void; +}; + +} // namespace routemon::database diff --git a/server/src/database/schema.cpp b/server/src/database/schema.cpp new file mode 100644 index 0000000..addc1f8 --- /dev/null +++ b/server/src/database/schema.cpp @@ -0,0 +1,59 @@ +module routemon:database.schema$impl; + +import :database.schema; + +namespace routemon::database::schema { + +auto try_to_string(rwgps_notification_cause c) -> std::optional +{ + switch (c) + { + case rwgps_notification_cause::unknown: + return std::nullopt; + case rwgps_notification_cause::created: + return "created"; + case rwgps_notification_cause::updated: + return "updated"; + case rwgps_notification_cause::deleted: + return "deleted"; + case rwgps_notification_cause::added: + return "added"; + case rwgps_notification_cause::removed: + return "removed"; + } +} + +auto try_to_string(rwgps_notification_item_type t) -> std::optional +{ + switch (t) + { + case rwgps_notification_item_type::unknown: + return std::nullopt; + case rwgps_notification_item_type::trip: + return "trip"; + case rwgps_notification_item_type::route: + return "route"; + case rwgps_notification_item_type::event: + return "event"; + case rwgps_notification_item_type::event_participant: + return "event_participant"; + case rwgps_notification_item_type::club_member: + return "club_member"; + case rwgps_notification_item_type::authorization: + return "authorization"; + } +} + +auto try_to_string(rwgps_notification_target_collection_type t) + -> std::optional +{ + switch (t) + { + case rwgps_notification_target_collection_type::unknown: + return std::nullopt; + case rwgps_notification_target_collection_type::pinned: + return "pinned"; + } +}; + +} // namespace routemon::database::schema diff --git a/server/src/database/schema.cppm b/server/src/database/schema.cppm new file mode 100644 index 0000000..a34edef --- /dev/null +++ b/server/src/database/schema.cppm @@ -0,0 +1,67 @@ +export module routemon:database.schema; + +import std; +import :time; + +namespace routemon::database::schema { + +constexpr std::int64_t expected_version = 2; + +enum class rwgps_notification_cause +{ + unknown, + created, + updated, + deleted, + added, + removed, +}; + +auto try_to_string(rwgps_notification_cause c) -> std::optional; + +enum class rwgps_notification_item_type +{ + unknown, + trip, + route, + event, + event_participant, + club_member, + authorization, +}; + +auto try_to_string(rwgps_notification_item_type t) + -> std::optional; + +enum rwgps_notification_target_collection_type +{ + unknown, + pinned, +}; + +auto try_to_string(rwgps_notification_target_collection_type t) + -> std::optional; + +struct rwgps_notification_target_collection +{ + std::int64_t notification_id = 0; + std::int64_t id; + rwgps_notification_target_collection_type type; + std::optional url; +}; + +struct rwgps_notification +{ + std::int64_t id = 0; + time::timestamp rwgps_timestamp; + // User that took the action + std::int64_t user_id; + rwgps_notification_item_type item_type; + std::optional item_id; + // User that owns the item + std::optional item_user_id; + std::optional item_url; + rwgps_notification_cause action; +}; + +} // namespace routemon::database::schema 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 diff --git a/server/src/database/sqlite3.cppm b/server/src/database/sqlite3.cppm new file mode 100644 index 0000000..2216109 --- /dev/null +++ b/server/src/database/sqlite3.cppm @@ -0,0 +1,222 @@ +export module routemon:database.sqlite3; + +import std; +import :util; + +extern "C" +{ + using sqlite3 = struct sqlite3; + using sqlite3_mutex = struct sqlite3_mutex; + using sqlite3_stmt = struct sqlite3_stmt; +} + +namespace routemon::database::sqlite3 { + +template concept C> +concept optional_of = requires { + typename T::value_type; + requires std::same_as>; + requires C; +}; + +template +concept scannable_prim = std::same_as || std::same_as + || std::same_as; + +template +concept scannable = scannable_prim || optional_of; + +class mutex_guard +{ + ::sqlite3* dbc_; + +public: + explicit mutex_guard(::sqlite3* dbc) noexcept; + mutex_guard(mutex_guard const&) = delete; + mutex_guard(mutex_guard&& rhs) = delete; + auto operator=(mutex_guard const&) -> mutex_guard& = delete; + auto operator=(mutex_guard&& rhs) -> mutex_guard& = delete; + ~mutex_guard(); + + auto for_db(::sqlite3 const* dbc) const -> bool { return dbc_ == dbc; } +}; + +class error : public std::exception +{ + int code_; + std::string message_; + +public: + explicit error(int code, ::sqlite3* dbc); + explicit error(int code); + + [[nodiscard]] auto what() const noexcept -> char const* override; + [[nodiscard]] auto code() const noexcept -> int; +}; + +class statement; +class row_reader; + +// TODO: make consumable and mark release_guard only callable when unconsumed? +// Same might have to for release_guard in row_reader. +class locked_statement +{ + ::sqlite3_stmt* stmt_; + std::shared_ptr guard_; + + friend class statement; + friend class row_reader; + +public: + explicit locked_statement( + ::sqlite3_stmt* stmt, std::shared_ptr dbc_locked); + locked_statement(locked_statement const&) = delete; + locked_statement(locked_statement&& s) noexcept; + ~locked_statement(); +}; + +class statement +{ + locked_statement stmt_; + + auto param_idx(util::zstring_view name) -> int; + auto bind_null(util::zstring_view param_name) -> statement&; + +public: + explicit statement(locked_statement&& stmt); + + auto bind(util::zstring_view param_name, std::string_view str) -> statement&; + auto bind(util::zstring_view param_name, std::int64_t x) -> statement&; + auto bind(util::zstring_view param_name, std::optional str) + -> statement&; + auto bind(util::zstring_view param_name, std::optional x) + -> statement&; + auto into_reader() && -> row_reader; +}; + +class row_reader +{ + locked_statement stmt_; + + friend class statement; + + explicit row_reader(locked_statement&& stmt); + + auto is_null(int col) -> bool; + auto ncols() -> std::size_t; + + auto scan_col(int col, std::string& s) -> void; + auto scan_col(int col, double& v) -> void; + auto scan_col(int col, std::int64_t& v) -> void; + auto scan_col(int col, optional_of auto& v) -> void + { + if (is_null(col)) + { + v.reset(); + } + else + { + typename std::remove_cvref_t::value_type tmp; + scan_col(col, tmp); + v = std::move(tmp); + } + } + +public: + auto next() -> bool; + + auto scan(scannable auto&... args) -> void + { + if (sizeof...(args) > ncols()) + throw std::invalid_argument{ + "more scanning arguments provided than columns in result set" + }; + auto col = 0; + (..., scan_col(col++, args)); + } + + template + auto scan() -> std::tuple + { + std::tuple res; + auto& [... elems] = res; + scan(elems...); + return res; + } + + auto scan_row_max1(scannable auto&... args) -> void + { + if (!next()) + throw std::logic_error{"no row in result set"}; + scan(args...); + if (next()) + { + throw std::logic_error{"more than one row in result set"}; + } + } + + template + auto scan_row_max1() -> std::tuple + { + std::tuple res; + auto& [... elems] = res; + scan_row_max1(elems...); + return res; + } +}; + +// TODO: consider making this a concept instead. +using bindfn = std::functionvoid>; + +auto noop_binder(statement&) -> void; + +export class connection +{ + ::sqlite3* dbc_; + + explicit connection(::sqlite3* dbc); + + friend auto open(std::filesystem::path const& filename) -> connection; + friend class tx; + +public: + connection(connection const&) = delete; + connection(connection&& c) noexcept; + + [[nodiscard]] auto + query(util::zstring_view sql, bindfn const& bf = noop_binder) -> row_reader; + + auto exec(util::zstring_view sql, bindfn const& bf = noop_binder) -> void; + + ~connection(); +}; + +// TODO: define behavior when user issues queries that affect the +// transaction itself. +export class tx +{ + bool commit_ = true; + util::not_null dbc_; + std::shared_ptr guard_; + +public: + explicit tx(connection& dbc); + + ~tx() + { + if (commit_) + exec("COMMIT"); + else + exec("ROLLBACK"); + } + + [[nodiscard]] auto + query(util::zstring_view sql, bindfn const& bf = noop_binder) -> row_reader; + + auto exec(util::zstring_view sql, bindfn const& bf = noop_binder) -> void; + auto exec_first(util::zstring_view& sql) -> void; +}; + +export auto open(std::filesystem::path const& filename) -> connection; + +} // namespace routemon::database::sqlite3 -- cgit v1.3.1