summaryrefslogtreecommitdiffstats
path: root/server/src/database.cppm
diff options
context:
space:
mode:
Diffstat (limited to 'server/src/database.cppm')
-rw-r--r--server/src/database.cppm52
1 files changed, 31 insertions, 21 deletions
diff --git a/server/src/database.cppm b/server/src/database.cppm
index 0312dda..86ed0d7 100644
--- a/server/src/database.cppm
+++ b/server/src/database.cppm
@@ -5,33 +5,43 @@ import :sqlite3;
5 5
6namespace routemon::database { 6namespace routemon::database {
7 7
8 static constexpr std::int64_t expected_database_version = 1; 8static constexpr std::int64_t expected_database_version = 1;
9 9
10 export class connection { 10export class connection
11 sqlite3::connection dbc_; 11{
12 sqlite3::connection dbc_;
12 13
13 explicit connection(sqlite3::connection dbc) : dbc_{std::move(dbc)} {} 14 explicit connection(sqlite3::connection dbc) : dbc_{std::move(dbc)} {}
14 15
15 friend auto open(std::string const& filename) -> std::shared_ptr<connection>; 16 friend auto open(std::string const& filename) -> std::shared_ptr<connection>;
16 17
17 public: 18public:
18 // Nothing here yet 19 // Nothing here yet
19 }; 20};
20 21
21 export auto open(std::string const& filename) -> std::shared_ptr<connection> { 22export auto open(std::string const& filename) -> std::shared_ptr<connection>
22 auto dbc = sqlite3::open(filename); 23{
23 try { 24 auto dbc = sqlite3::open(filename);
24 auto version = std::optional<std::int64_t>{}; 25 try
25 dbc.query("SELECT version FROM migration;").scan_single(version); 26 {
26 if (!version) 27 auto version = std::optional<std::int64_t>{};
27 throw std::runtime_error{"failed to fetch database migration version"}; 28 dbc.query("SELECT version FROM migration;").scan_single(version);
28 if (version != expected_database_version) { 29 if (!version)
29 throw std::runtime_error{std::format("database migration version ({}) does not match expected version ({}), consider running migrations", *version, expected_database_version)}; 30 throw std::runtime_error{"failed to fetch database migration version"};
30 } 31 if (version != expected_database_version)
31 } catch (std::exception const& e) { 32 {
32 throw std::runtime_error{std::format("failed to query database version: {}", e.what())}; 33 throw std::runtime_error{std::format(
34 "database migration version ({}) does not match expected "
35 "version ({}), consider running migrations",
36 *version, expected_database_version)};
33 } 37 }
34 return std::shared_ptr<connection>{new connection{std::move(dbc)}};
35 } 38 }
39 catch (std::exception const& e)
40 {
41 throw std::runtime_error{std::format(
42 "failed to query database version: {}", e.what())};
43 }
44 return std::shared_ptr<connection>{new connection{std::move(dbc)}};
45}
36 46
37} // namespace routemon::database 47} // namespace routemon::database