diff options
| author | Rutger Broekhoff | 2026-11-30 21:27:55 +0100 |
|---|---|---|
| committer | Rutger Broekhoff | 2026-11-30 21:27:55 +0100 |
| commit | 7bba7176194c4d1d9c7066f8eda7a94491d924e6 (patch) | |
| tree | a9a171e8608786e09d6342729ee13b8471c0c9c2 /server/src/database | |
| parent | 02475e05ccd1aa15c6a6163834f28bfebbef796f (diff) | |
| download | routemon-7bba7176194c4d1d9c7066f8eda7a94491d924e6.tar.gz routemon-7bba7176194c4d1d9c7066f8eda7a94491d924e6.zip | |
Cleanups and updates
Diffstat (limited to 'server/src/database')
| -rw-r--r-- | server/src/database/connection.cpp | 78 | ||||
| -rw-r--r-- | server/src/database/connection.cppm | 30 | ||||
| -rw-r--r-- | server/src/database/migrator.cpp | 122 | ||||
| -rw-r--r-- | server/src/database/migrator.cppm | 26 | ||||
| -rw-r--r-- | server/src/database/schema.cpp | 59 | ||||
| -rw-r--r-- | server/src/database/schema.cppm | 67 | ||||
| -rw-r--r-- | server/src/database/sqlite3.cpp | 367 | ||||
| -rw-r--r-- | server/src/database/sqlite3.cppm | 222 |
8 files changed, 971 insertions, 0 deletions
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 @@ | |||
| 1 | module routemon:database.connection$impl; | ||
| 2 | |||
| 3 | import :database.connection; | ||
| 4 | |||
| 5 | namespace routemon::database { | ||
| 6 | |||
| 7 | auto connection::insert_rwgps_notifications( | ||
| 8 | std::vector<std::pair< | ||
| 9 | schema::rwgps_notification, | ||
| 10 | std::optional<schema::rwgps_notification_target_collection> | ||
| 11 | >>& notifs) -> void | ||
| 12 | { | ||
| 13 | auto tx = sqlite3::tx{dbc_}; | ||
| 14 | for (auto& [notif, mtarget_collection] : notifs) | ||
| 15 | { | ||
| 16 | tx.query( | ||
| 17 | "INSERT INTO rwgps_notification " | ||
| 18 | " (rwgps_timestamp, user_id, item_type, item_id, " | ||
| 19 | " item_user_id, item_url, action_) " | ||
| 20 | "VALUES (:rwgps_timestamp, :user_id, :item_type, :item_id, " | ||
| 21 | " :item_user_id, :item_url, :action) " | ||
| 22 | "RETURNING id", | ||
| 23 | [¬if](auto& s) | ||
| 24 | { | ||
| 25 | auto const ts = time::iso8601_secs(notif.rwgps_timestamp); | ||
| 26 | s.bind(":rwgps_timestamp", std::string_view{ts}); | ||
| 27 | s.bind(":user_id", notif.user_id); | ||
| 28 | s.bind(":item_type", try_to_string(notif.item_type)); | ||
| 29 | s.bind(":item_id", notif.item_id); | ||
| 30 | s.bind(":item_user_id", notif.item_user_id); | ||
| 31 | s.bind(":item_url", notif.item_url); | ||
| 32 | s.bind(":action", try_to_string(notif.action)); | ||
| 33 | }) | ||
| 34 | .scan_row_max1(notif.id); | ||
| 35 | |||
| 36 | if (mtarget_collection) | ||
| 37 | { | ||
| 38 | tx.exec( | ||
| 39 | "INSERT INTO rwgps_notification_target_collection " | ||
| 40 | " (notification_id, id, type_, url) " | ||
| 41 | "VALUES (:notification_id, :id, :type, :url)", | ||
| 42 | [¬if, &mtarget_collection](auto& s) | ||
| 43 | { | ||
| 44 | s.bind(":notification_id", notif.id); | ||
| 45 | s.bind(":id", mtarget_collection->id); | ||
| 46 | s.bind(":type", try_to_string(mtarget_collection->type)); | ||
| 47 | s.bind(":url", mtarget_collection->url); | ||
| 48 | }); | ||
| 49 | } | ||
| 50 | } | ||
| 51 | } | ||
| 52 | |||
| 53 | auto open(std::filesystem::path const& filename) -> std::shared_ptr<connection> | ||
| 54 | { | ||
| 55 | auto dbc = sqlite3::open(filename); | ||
| 56 | try | ||
| 57 | { | ||
| 58 | auto mversion = std::optional<std::int64_t>{}; | ||
| 59 | dbc.query("SELECT version FROM migration;").scan_row_max1(mversion); | ||
| 60 | if (!mversion) | ||
| 61 | throw std::runtime_error{"failed to fetch database migration version"}; | ||
| 62 | if (mversion != schema::expected_version) | ||
| 63 | { | ||
| 64 | throw std::runtime_error{std::format( | ||
| 65 | "database migration version ({}) does not match expected " | ||
| 66 | "version ({}), consider running migrations", | ||
| 67 | *mversion, schema::expected_version)}; | ||
| 68 | } | ||
| 69 | } | ||
| 70 | catch (std::exception const& e) | ||
| 71 | { | ||
| 72 | throw std::runtime_error{std::format( | ||
| 73 | "failed to query database version: {}", e.what())}; | ||
| 74 | } | ||
| 75 | return std::shared_ptr<connection>{new connection{std::move(dbc)}}; | ||
| 76 | } | ||
| 77 | |||
| 78 | } // 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 @@ | |||
| 1 | export module routemon:database.connection; | ||
| 2 | |||
| 3 | import std; | ||
| 4 | import :database.schema; | ||
| 5 | import :database.sqlite3; | ||
| 6 | import :time; | ||
| 7 | |||
| 8 | namespace routemon::database { | ||
| 9 | |||
| 10 | export class connection | ||
| 11 | { | ||
| 12 | sqlite3::connection dbc_; | ||
| 13 | |||
| 14 | explicit connection(sqlite3::connection dbc) : dbc_{std::move(dbc)} {} | ||
| 15 | |||
| 16 | friend auto open(std::filesystem::path const& filename) | ||
| 17 | -> std::shared_ptr<connection>; | ||
| 18 | |||
| 19 | public: | ||
| 20 | auto insert_rwgps_notifications( | ||
| 21 | std::vector<std::pair< | ||
| 22 | schema::rwgps_notification, | ||
| 23 | std::optional<schema::rwgps_notification_target_collection> | ||
| 24 | >>& notifs) -> void; | ||
| 25 | }; | ||
| 26 | |||
| 27 | export auto open(std::filesystem::path const& filename) | ||
| 28 | -> std::shared_ptr<connection>; | ||
| 29 | |||
| 30 | } // 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 @@ | |||
| 1 | module; | ||
| 2 | |||
| 3 | #include <cassert> | ||
| 4 | |||
| 5 | export module routemon:database.migrator$impl; | ||
| 6 | |||
| 7 | import :database.migrator; | ||
| 8 | |||
| 9 | namespace routemon::database { | ||
| 10 | |||
| 11 | auto load_migrations( | ||
| 12 | std::filesystem::path const& dir, std::int64_t current_version, | ||
| 13 | std::int64_t target_version) -> std::vector<std::string> | ||
| 14 | { | ||
| 15 | if (current_version < 0 || target_version < 0) | ||
| 16 | throw std::invalid_argument{"database versions must be nonnegative"}; | ||
| 17 | if (target_version < current_version) | ||
| 18 | throw std::runtime_error{"migrating down is not supported yet"}; | ||
| 19 | if (current_version == target_version) | ||
| 20 | return {}; | ||
| 21 | assert(current_version < target_version); | ||
| 22 | |||
| 23 | // TODO: narrow_cast or something like that | ||
| 24 | auto migration_sqls = | ||
| 25 | std::vector<std::optional<std::pair<std::filesystem::path, std::string>>>{ | ||
| 26 | static_cast<std::size_t>(target_version - current_version) | ||
| 27 | }; | ||
| 28 | for (auto const& entry : std::filesystem::directory_iterator{dir}) | ||
| 29 | { | ||
| 30 | if (!std::filesystem::is_regular_file(entry.status())) | ||
| 31 | continue; | ||
| 32 | auto const filename = std::string{entry.path().filename()}; | ||
| 33 | if (!filename.ends_with("_up.sql")) | ||
| 34 | continue; | ||
| 35 | auto const [no_str, mrest] = util::split_on(filename, '_'); | ||
| 36 | if (!mrest) | ||
| 37 | continue; | ||
| 38 | auto const mno = util::parse_int<std::int64_t>(no_str); | ||
| 39 | if (!mno || *mno < 1) | ||
| 40 | continue; | ||
| 41 | if (*mno <= current_version || target_version < *mno) | ||
| 42 | continue; | ||
| 43 | auto const i = static_cast<std::size_t>(*mno - current_version - 1); | ||
| 44 | |||
| 45 | if (migration_sqls[i]) | ||
| 46 | throw std::runtime_error{std::format( | ||
| 47 | "found more than one (up) migration file for version {}", *mno)}; | ||
| 48 | |||
| 49 | auto f = std::ifstream{entry.path(), std::ios::binary}; | ||
| 50 | auto contents = std::string{ | ||
| 51 | std::istreambuf_iterator<char>{f}, | ||
| 52 | std::istreambuf_iterator<char>{}, | ||
| 53 | }; | ||
| 54 | |||
| 55 | migration_sqls[i] = {entry.path(), contents}; | ||
| 56 | } | ||
| 57 | |||
| 58 | return migration_sqls | std::views::enumerate | ||
| 59 | | std::views::transform( | ||
| 60 | [current_version](auto&& pair) -> std::string | ||
| 61 | { | ||
| 62 | auto&& [i, mentry] = pair; | ||
| 63 | if (!mentry) | ||
| 64 | throw std::runtime_error{std::format( | ||
| 65 | "no migration found to version {}", | ||
| 66 | current_version + i + 1)}; | ||
| 67 | return std::move(mentry->second); | ||
| 68 | }) | ||
| 69 | | std::ranges::to<std::vector<std::string>>(); | ||
| 70 | } | ||
| 71 | |||
| 72 | auto migrator::current_version() -> std::int64_t | ||
| 73 | { | ||
| 74 | if (auto const [has_migrations_table] = | ||
| 75 | dbc_.query( | ||
| 76 | "SELECT COUNT(*) FROM sqlite_schema WHERE " | ||
| 77 | "type IS 'table' AND " | ||
| 78 | "name IS 'migration'") | ||
| 79 | .scan_row_max1<std::int64_t>(); | ||
| 80 | has_migrations_table) | ||
| 81 | return std::get<0>(dbc_.query("SELECT version FROM migration") | ||
| 82 | .scan_row_max1<std::int64_t>()); | ||
| 83 | return 0; | ||
| 84 | } | ||
| 85 | |||
| 86 | migrator::migrator( | ||
| 87 | log::logger const& l, std::filesystem::path const& db_filename, | ||
| 88 | std::filesystem::path migrations_dir) | ||
| 89 | : l_{l.sub("migrator")}, dbc_{sqlite3::open(db_filename)}, | ||
| 90 | migrations_dir_{std::move(migrations_dir)} | ||
| 91 | { | ||
| 92 | } | ||
| 93 | |||
| 94 | auto migrator::migrate_to(std::int64_t target_version) -> void | ||
| 95 | { | ||
| 96 | // Part of function contract. Consider throwing instead? | ||
| 97 | if (target_version < 0) | ||
| 98 | throw std::invalid_argument{"target database version must be nonnegative"}; | ||
| 99 | |||
| 100 | auto current = current_version(); | ||
| 101 | auto const migration_sqls = | ||
| 102 | load_migrations(migrations_dir_, current, target_version); | ||
| 103 | |||
| 104 | for (auto const& sql : migration_sqls) | ||
| 105 | { | ||
| 106 | l_.info("Migrating from schema version {} to {}", current, current + 1); | ||
| 107 | migrate_step(++current, sql); | ||
| 108 | } | ||
| 109 | } | ||
| 110 | |||
| 111 | auto migrator::migrate_step(std::int64_t target_version, util::zstring_view sql) | ||
| 112 | -> void | ||
| 113 | { | ||
| 114 | auto tx = sqlite3::tx{dbc_}; | ||
| 115 | while (!sql.empty()) | ||
| 116 | tx.exec_first(sql); | ||
| 117 | tx.exec( | ||
| 118 | "UPDATE migration SET version = :version", | ||
| 119 | [target_version](auto& s) { s.bind(":version", target_version); }); | ||
| 120 | } | ||
| 121 | |||
| 122 | } // 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 @@ | |||
| 1 | export module routemon:database.migrator; | ||
| 2 | |||
| 3 | import :database.sqlite3; | ||
| 4 | import :log; | ||
| 5 | |||
| 6 | namespace routemon::database { | ||
| 7 | |||
| 8 | export class migrator | ||
| 9 | { | ||
| 10 | log::logger l_; | ||
| 11 | sqlite3::connection dbc_; | ||
| 12 | std::filesystem::path migrations_dir_; | ||
| 13 | |||
| 14 | auto current_version() -> std::int64_t; | ||
| 15 | |||
| 16 | public: | ||
| 17 | explicit migrator( | ||
| 18 | log::logger const& l, std::filesystem::path const& db_filename, | ||
| 19 | std::filesystem::path migrations_dir); | ||
| 20 | |||
| 21 | auto migrate_to(std::int64_t target_version) -> void; | ||
| 22 | auto migrate_step(std::int64_t target_version, util::zstring_view sql) | ||
| 23 | -> void; | ||
| 24 | }; | ||
| 25 | |||
| 26 | } // 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 @@ | |||
| 1 | module routemon:database.schema$impl; | ||
| 2 | |||
| 3 | import :database.schema; | ||
| 4 | |||
| 5 | namespace routemon::database::schema { | ||
| 6 | |||
| 7 | auto try_to_string(rwgps_notification_cause c) -> std::optional<std::string> | ||
| 8 | { | ||
| 9 | switch (c) | ||
| 10 | { | ||
| 11 | case rwgps_notification_cause::unknown: | ||
| 12 | return std::nullopt; | ||
| 13 | case rwgps_notification_cause::created: | ||
| 14 | return "created"; | ||
| 15 | case rwgps_notification_cause::updated: | ||
| 16 | return "updated"; | ||
| 17 | case rwgps_notification_cause::deleted: | ||
| 18 | return "deleted"; | ||
| 19 | case rwgps_notification_cause::added: | ||
| 20 | return "added"; | ||
| 21 | case rwgps_notification_cause::removed: | ||
| 22 | return "removed"; | ||
| 23 | } | ||
| 24 | } | ||
| 25 | |||
| 26 | auto try_to_string(rwgps_notification_item_type t) -> std::optional<std::string> | ||
| 27 | { | ||
| 28 | switch (t) | ||
| 29 | { | ||
| 30 | case rwgps_notification_item_type::unknown: | ||
| 31 | return std::nullopt; | ||
| 32 | case rwgps_notification_item_type::trip: | ||
| 33 | return "trip"; | ||
| 34 | case rwgps_notification_item_type::route: | ||
| 35 | return "route"; | ||
| 36 | case rwgps_notification_item_type::event: | ||
| 37 | return "event"; | ||
| 38 | case rwgps_notification_item_type::event_participant: | ||
| 39 | return "event_participant"; | ||
| 40 | case rwgps_notification_item_type::club_member: | ||
| 41 | return "club_member"; | ||
| 42 | case rwgps_notification_item_type::authorization: | ||
| 43 | return "authorization"; | ||
| 44 | } | ||
| 45 | } | ||
| 46 | |||
| 47 | auto try_to_string(rwgps_notification_target_collection_type t) | ||
| 48 | -> std::optional<std::string> | ||
| 49 | { | ||
| 50 | switch (t) | ||
| 51 | { | ||
| 52 | case rwgps_notification_target_collection_type::unknown: | ||
| 53 | return std::nullopt; | ||
| 54 | case rwgps_notification_target_collection_type::pinned: | ||
| 55 | return "pinned"; | ||
| 56 | } | ||
| 57 | }; | ||
| 58 | |||
| 59 | } // 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 @@ | |||
| 1 | export module routemon:database.schema; | ||
| 2 | |||
| 3 | import std; | ||
| 4 | import :time; | ||
| 5 | |||
| 6 | namespace routemon::database::schema { | ||
| 7 | |||
| 8 | constexpr std::int64_t expected_version = 2; | ||
| 9 | |||
| 10 | enum class rwgps_notification_cause | ||
| 11 | { | ||
| 12 | unknown, | ||
| 13 | created, | ||
| 14 | updated, | ||
| 15 | deleted, | ||
| 16 | added, | ||
| 17 | removed, | ||
| 18 | }; | ||
| 19 | |||
| 20 | auto try_to_string(rwgps_notification_cause c) -> std::optional<std::string>; | ||
| 21 | |||
| 22 | enum class rwgps_notification_item_type | ||
| 23 | { | ||
| 24 | unknown, | ||
| 25 | trip, | ||
| 26 | route, | ||
| 27 | event, | ||
| 28 | event_participant, | ||
| 29 | club_member, | ||
| 30 | authorization, | ||
| 31 | }; | ||
| 32 | |||
| 33 | auto try_to_string(rwgps_notification_item_type t) | ||
| 34 | -> std::optional<std::string>; | ||
| 35 | |||
| 36 | enum rwgps_notification_target_collection_type | ||
| 37 | { | ||
| 38 | unknown, | ||
| 39 | pinned, | ||
| 40 | }; | ||
| 41 | |||
| 42 | auto try_to_string(rwgps_notification_target_collection_type t) | ||
| 43 | -> std::optional<std::string>; | ||
| 44 | |||
| 45 | struct rwgps_notification_target_collection | ||
| 46 | { | ||
| 47 | std::int64_t notification_id = 0; | ||
| 48 | std::int64_t id; | ||
| 49 | rwgps_notification_target_collection_type type; | ||
| 50 | std::optional<std::string> url; | ||
| 51 | }; | ||
| 52 | |||
| 53 | struct rwgps_notification | ||
| 54 | { | ||
| 55 | std::int64_t id = 0; | ||
| 56 | time::timestamp<std::chrono::seconds> rwgps_timestamp; | ||
| 57 | // User that took the action | ||
| 58 | std::int64_t user_id; | ||
| 59 | rwgps_notification_item_type item_type; | ||
| 60 | std::optional<std::int64_t> item_id; | ||
| 61 | // User that owns the item | ||
| 62 | std::optional<std::int64_t> item_user_id; | ||
| 63 | std::optional<std::string> item_url; | ||
| 64 | rwgps_notification_cause action; | ||
| 65 | }; | ||
| 66 | |||
| 67 | } // 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 @@ | |||
| 1 | module; | ||
| 2 | |||
| 3 | #include <sqlite3.h> | ||
| 4 | |||
| 5 | module routemon:database.sqlite3$impl; | ||
| 6 | |||
| 7 | import :database.sqlite3; | ||
| 8 | |||
| 9 | namespace routemon::database::sqlite3 { | ||
| 10 | |||
| 11 | mutex_guard::mutex_guard(::sqlite3* dbc) noexcept : dbc_{dbc} | ||
| 12 | { | ||
| 13 | ::sqlite3_mutex_enter(::sqlite3_db_mutex(dbc_)); | ||
| 14 | } | ||
| 15 | |||
| 16 | mutex_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 | |||
| 32 | error::error(int code, ::sqlite3* dbc) | ||
| 33 | : code_{code}, message_{::sqlite3_errmsg(dbc)} | ||
| 34 | { | ||
| 35 | } | ||
| 36 | |||
| 37 | error::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 | |||
| 46 | locked_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 | } | ||
| 57 | locked_statement::locked_statement(locked_statement&& rhs) noexcept | ||
| 58 | : stmt_{std::exchange(rhs.stmt_, nullptr)}, guard_{std::move(rhs.guard_)} | ||
| 59 | { | ||
| 60 | } | ||
| 61 | locked_statement::~locked_statement() | ||
| 62 | { | ||
| 63 | if (stmt_) | ||
| 64 | ::sqlite3_finalize(stmt_); | ||
| 65 | } | ||
| 66 | |||
| 67 | row_reader::row_reader(locked_statement&& stmt) : stmt_{std::move(stmt)} {} | ||
| 68 | |||
| 69 | auto row_reader::is_null(int col) -> bool | ||
| 70 | { | ||
| 71 | return ::sqlite3_column_type(stmt_.stmt_, col) == SQLITE_NULL; | ||
| 72 | } | ||
| 73 | |||
| 74 | auto 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 | |||
| 82 | auto 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 | |||
| 93 | auto 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 | |||
| 100 | auto 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 | |||
| 107 | auto 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 | |||
| 118 | statement::statement(locked_statement&& stmt) : stmt_{std::move(stmt)} {} | ||
| 119 | |||
| 120 | auto 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 | |||
| 129 | auto 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 | |||
| 137 | auto 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 | |||
| 151 | auto 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 | |||
| 160 | auto 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 | |||
| 170 | auto 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 | |||
| 179 | auto statement::into_reader() && -> row_reader | ||
| 180 | { | ||
| 181 | return row_reader{std::move(stmt_)}; | ||
| 182 | } | ||
| 183 | |||
| 184 | auto noop_binder(statement&) -> void {} | ||
| 185 | |||
| 186 | connection::connection(::sqlite3* dbc) : dbc_{dbc} {} | ||
| 187 | |||
| 188 | connection::connection(connection&& c) noexcept | ||
| 189 | { | ||
| 190 | dbc_ = c.dbc_; | ||
| 191 | c.dbc_ = nullptr; | ||
| 192 | } | ||
| 193 | |||
| 194 | auto 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 | |||
| 234 | auto 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 | |||
| 249 | auto 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 | |||
| 258 | auto connection::query(util::zstring_view sql, bindfn const& bf) -> row_reader | ||
| 259 | { | ||
| 260 | return do_query(dbc_, sql, bf); | ||
| 261 | } | ||
| 262 | |||
| 263 | auto connection::exec(util::zstring_view sql, bindfn const& bf) -> void | ||
| 264 | { | ||
| 265 | return do_exec(dbc_, sql, bf); | ||
| 266 | } | ||
| 267 | |||
| 268 | connection::~connection() | ||
| 269 | { | ||
| 270 | std::ignore = ::sqlite3_close(std::exchange(dbc_, nullptr)); | ||
| 271 | } | ||
| 272 | |||
| 273 | auto open(std::filesystem::path const& 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 | |||
| 294 | w.exec("PRAGMA foreign_keys = ON"); | ||
| 295 | auto foreign_keys_on = std::int64_t{}; | ||
| 296 | try | ||
| 297 | { | ||
| 298 | w.query("PRAGMA foreign_keys").scan_row_max1(foreign_keys_on); | ||
| 299 | } | ||
| 300 | catch (std::exception& e) | ||
| 301 | { | ||
| 302 | throw std::runtime_error{ | ||
| 303 | "used SQLite version does not seem to support foreign key enforcement" | ||
| 304 | }; | ||
| 305 | } | ||
| 306 | if (foreign_keys_on != 1) | ||
| 307 | throw std::runtime_error{"failed to enable foreign key enforcement"}; | ||
| 308 | |||
| 309 | return w; | ||
| 310 | } | ||
| 311 | |||
| 312 | tx::tx(connection& dbc) | ||
| 313 | : dbc_{util::not_null{&dbc}}, | ||
| 314 | guard_{std::make_shared<mutex_guard>(dbc_->dbc_)} | ||
| 315 | { | ||
| 316 | exec("BEGIN"); | ||
| 317 | } | ||
| 318 | |||
| 319 | [[nodiscard]] auto tx::query(util::zstring_view sql, bindfn const& bf) | ||
| 320 | -> row_reader | ||
| 321 | { | ||
| 322 | try | ||
| 323 | { | ||
| 324 | return do_query(dbc_->dbc_, sql, bf, guard_); | ||
| 325 | } | ||
| 326 | catch (std::exception const&) | ||
| 327 | { | ||
| 328 | commit_ = false; | ||
| 329 | throw; | ||
| 330 | } | ||
| 331 | } | ||
| 332 | |||
| 333 | auto tx::exec(util::zstring_view sql, bindfn const& bf) -> void | ||
| 334 | { | ||
| 335 | try | ||
| 336 | { | ||
| 337 | do_exec(dbc_->dbc_, sql, bf, guard_); | ||
| 338 | } | ||
| 339 | catch (std::exception const&) | ||
| 340 | { | ||
| 341 | commit_ = false; | ||
| 342 | throw; | ||
| 343 | } | ||
| 344 | } | ||
| 345 | |||
| 346 | auto tx::exec_first(util::zstring_view& sql) -> void | ||
| 347 | { | ||
| 348 | try | ||
| 349 | { | ||
| 350 | auto mstmt = prepare(dbc_->dbc_, sql, guard_); | ||
| 351 | if (!mstmt) | ||
| 352 | { | ||
| 353 | sql = util::zstring_view{sql.c_str() + sql.length(), 0}; | ||
| 354 | return; | ||
| 355 | } | ||
| 356 | auto reader = std::move(*mstmt).into_reader(); | ||
| 357 | while (reader.next()) | ||
| 358 | ; | ||
| 359 | } | ||
| 360 | catch (std::exception const&) | ||
| 361 | { | ||
| 362 | commit_ = false; | ||
| 363 | throw; | ||
| 364 | } | ||
| 365 | } | ||
| 366 | |||
| 367 | } // 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 @@ | |||
| 1 | export module routemon:database.sqlite3; | ||
| 2 | |||
| 3 | import std; | ||
| 4 | import :util; | ||
| 5 | |||
| 6 | extern "C" | ||
| 7 | { | ||
| 8 | using sqlite3 = struct sqlite3; | ||
| 9 | using sqlite3_mutex = struct sqlite3_mutex; | ||
| 10 | using sqlite3_stmt = struct sqlite3_stmt; | ||
| 11 | } | ||
| 12 | |||
| 13 | namespace routemon::database::sqlite3 { | ||
| 14 | |||
| 15 | template <class T, template <class U> concept C> | ||
| 16 | concept optional_of = requires { | ||
| 17 | typename T::value_type; | ||
| 18 | requires std::same_as<T, std::optional<typename T::value_type>>; | ||
| 19 | requires C<typename T::value_type>; | ||
| 20 | }; | ||
| 21 | |||
| 22 | template <class T> | ||
| 23 | concept scannable_prim = std::same_as<T, std::string> || std::same_as<T, double> | ||
| 24 | || std::same_as<T, std::int64_t>; | ||
| 25 | |||
| 26 | template <class T> | ||
| 27 | concept scannable = scannable_prim<T> || optional_of<T, scannable_prim>; | ||
| 28 | |||
| 29 | class mutex_guard | ||
| 30 | { | ||
| 31 | ::sqlite3* dbc_; | ||
| 32 | |||
| 33 | public: | ||
| 34 | explicit mutex_guard(::sqlite3* dbc) noexcept; | ||
| 35 | mutex_guard(mutex_guard const&) = delete; | ||
| 36 | mutex_guard(mutex_guard&& rhs) = delete; | ||
| 37 | auto operator=(mutex_guard const&) -> mutex_guard& = delete; | ||
| 38 | auto operator=(mutex_guard&& rhs) -> mutex_guard& = delete; | ||
| 39 | ~mutex_guard(); | ||
| 40 | |||
| 41 | auto for_db(::sqlite3 const* dbc) const -> bool { return dbc_ == dbc; } | ||
| 42 | }; | ||
| 43 | |||
| 44 | class error : public std::exception | ||
| 45 | { | ||
| 46 | int code_; | ||
| 47 | std::string message_; | ||
| 48 | |||
| 49 | public: | ||
| 50 | explicit error(int code, ::sqlite3* dbc); | ||
| 51 | explicit error(int code); | ||
| 52 | |||
| 53 | [[nodiscard]] auto what() const noexcept -> char const* override; | ||
| 54 | [[nodiscard]] auto code() const noexcept -> int; | ||
| 55 | }; | ||
| 56 | |||
| 57 | class statement; | ||
| 58 | class row_reader; | ||
| 59 | |||
| 60 | // TODO: make consumable and mark release_guard only callable when unconsumed? | ||
| 61 | // Same might have to for release_guard in row_reader. | ||
| 62 | class locked_statement | ||
| 63 | { | ||
| 64 | ::sqlite3_stmt* stmt_; | ||
| 65 | std::shared_ptr<mutex_guard> guard_; | ||
| 66 | |||
| 67 | friend class statement; | ||
| 68 | friend class row_reader; | ||
| 69 | |||
| 70 | public: | ||
| 71 | explicit locked_statement( | ||
| 72 | ::sqlite3_stmt* stmt, std::shared_ptr<mutex_guard> dbc_locked); | ||
| 73 | locked_statement(locked_statement const&) = delete; | ||
| 74 | locked_statement(locked_statement&& s) noexcept; | ||
| 75 | ~locked_statement(); | ||
| 76 | }; | ||
| 77 | |||
| 78 | class statement | ||
| 79 | { | ||
| 80 | locked_statement stmt_; | ||
| 81 | |||
| 82 | auto param_idx(util::zstring_view name) -> int; | ||
| 83 | auto bind_null(util::zstring_view param_name) -> statement&; | ||
| 84 | |||
| 85 | public: | ||
| 86 | explicit statement(locked_statement&& stmt); | ||
| 87 | |||
| 88 | auto bind(util::zstring_view param_name, std::string_view str) -> statement&; | ||
| 89 | auto bind(util::zstring_view param_name, std::int64_t x) -> statement&; | ||
| 90 | auto bind(util::zstring_view param_name, std::optional<std::string_view> str) | ||
| 91 | -> statement&; | ||
| 92 | auto bind(util::zstring_view param_name, std::optional<std::int64_t> x) | ||
| 93 | -> statement&; | ||
| 94 | auto into_reader() && -> row_reader; | ||
| 95 | }; | ||
| 96 | |||
| 97 | class row_reader | ||
| 98 | { | ||
| 99 | locked_statement stmt_; | ||
| 100 | |||
| 101 | friend class statement; | ||
| 102 | |||
| 103 | explicit row_reader(locked_statement&& stmt); | ||
| 104 | |||
| 105 | auto is_null(int col) -> bool; | ||
| 106 | auto ncols() -> std::size_t; | ||
| 107 | |||
| 108 | auto scan_col(int col, std::string& s) -> void; | ||
| 109 | auto scan_col(int col, double& v) -> void; | ||
| 110 | auto scan_col(int col, std::int64_t& v) -> void; | ||
| 111 | auto scan_col(int col, optional_of<scannable_prim> auto& v) -> void | ||
| 112 | { | ||
| 113 | if (is_null(col)) | ||
| 114 | { | ||
| 115 | v.reset(); | ||
| 116 | } | ||
| 117 | else | ||
| 118 | { | ||
| 119 | typename std::remove_cvref_t<decltype(v)>::value_type tmp; | ||
| 120 | scan_col(col, tmp); | ||
| 121 | v = std::move(tmp); | ||
| 122 | } | ||
| 123 | } | ||
| 124 | |||
| 125 | public: | ||
| 126 | auto next() -> bool; | ||
| 127 | |||
| 128 | auto scan(scannable auto&... args) -> void | ||
| 129 | { | ||
| 130 | if (sizeof...(args) > ncols()) | ||
| 131 | throw std::invalid_argument{ | ||
| 132 | "more scanning arguments provided than columns in result set" | ||
| 133 | }; | ||
| 134 | auto col = 0; | ||
| 135 | (..., scan_col(col++, args)); | ||
| 136 | } | ||
| 137 | |||
| 138 | template <scannable... args> | ||
| 139 | auto scan() -> std::tuple<args...> | ||
| 140 | { | ||
| 141 | std::tuple<args...> res; | ||
| 142 | auto& [... elems] = res; | ||
| 143 | scan(elems...); | ||
| 144 | return res; | ||
| 145 | } | ||
| 146 | |||
| 147 | auto scan_row_max1(scannable auto&... args) -> void | ||
| 148 | { | ||
| 149 | if (!next()) | ||
| 150 | throw std::logic_error{"no row in result set"}; | ||
| 151 | scan(args...); | ||
| 152 | if (next()) | ||
| 153 | { | ||
| 154 | throw std::logic_error{"more than one row in result set"}; | ||
| 155 | } | ||
| 156 | } | ||
| 157 | |||
| 158 | template <scannable... args> | ||
| 159 | auto scan_row_max1() -> std::tuple<args...> | ||
| 160 | { | ||
| 161 | std::tuple<args...> res; | ||
| 162 | auto& [... elems] = res; | ||
| 163 | scan_row_max1(elems...); | ||
| 164 | return res; | ||
| 165 | } | ||
| 166 | }; | ||
| 167 | |||
| 168 | // TODO: consider making this a concept instead. | ||
| 169 | using bindfn = std::function<auto(statement&)->void>; | ||
| 170 | |||
| 171 | auto noop_binder(statement&) -> void; | ||
| 172 | |||
| 173 | export class connection | ||
| 174 | { | ||
| 175 | ::sqlite3* dbc_; | ||
| 176 | |||
| 177 | explicit connection(::sqlite3* dbc); | ||
| 178 | |||
| 179 | friend auto open(std::filesystem::path const& filename) -> connection; | ||
| 180 | friend class tx; | ||
| 181 | |||
| 182 | public: | ||
| 183 | connection(connection const&) = delete; | ||
| 184 | connection(connection&& c) noexcept; | ||
| 185 | |||
| 186 | [[nodiscard]] auto | ||
| 187 | query(util::zstring_view sql, bindfn const& bf = noop_binder) -> row_reader; | ||
| 188 | |||
| 189 | auto exec(util::zstring_view sql, bindfn const& bf = noop_binder) -> void; | ||
| 190 | |||
| 191 | ~connection(); | ||
| 192 | }; | ||
| 193 | |||
| 194 | // TODO: define behavior when user issues queries that affect the | ||
| 195 | // transaction itself. | ||
| 196 | export class tx | ||
| 197 | { | ||
| 198 | bool commit_ = true; | ||
| 199 | util::not_null<connection*> dbc_; | ||
| 200 | std::shared_ptr<mutex_guard> guard_; | ||
| 201 | |||
| 202 | public: | ||
| 203 | explicit tx(connection& dbc); | ||
| 204 | |||
| 205 | ~tx() | ||
| 206 | { | ||
| 207 | if (commit_) | ||
| 208 | exec("COMMIT"); | ||
| 209 | else | ||
| 210 | exec("ROLLBACK"); | ||
| 211 | } | ||
| 212 | |||
| 213 | [[nodiscard]] auto | ||
| 214 | query(util::zstring_view sql, bindfn const& bf = noop_binder) -> row_reader; | ||
| 215 | |||
| 216 | auto exec(util::zstring_view sql, bindfn const& bf = noop_binder) -> void; | ||
| 217 | auto exec_first(util::zstring_view& sql) -> void; | ||
| 218 | }; | ||
| 219 | |||
| 220 | export auto open(std::filesystem::path const& filename) -> connection; | ||
| 221 | |||
| 222 | } // namespace routemon::database::sqlite3 | ||