summaryrefslogtreecommitdiffstats
path: root/server/src/database.cppm
blob: 0312ddab99f9a4d73205ddad208a8cda409dbae7 (about) (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
export module routemon:database;

import std;
import :sqlite3;

namespace routemon::database {

  static constexpr std::int64_t expected_database_version = 1;

  export class connection {
    sqlite3::connection dbc_;

    explicit connection(sqlite3::connection dbc) : dbc_{std::move(dbc)} {}

    friend auto open(std::string const& filename) -> std::shared_ptr<connection>;

  public:
    // Nothing here yet
  };

  export auto open(std::string const& filename) -> std::shared_ptr<connection> {
    auto dbc = sqlite3::open(filename);
    try {
      auto version = std::optional<std::int64_t>{};
      dbc.query("SELECT version FROM migration;").scan_single(version);
      if (!version)
        throw std::runtime_error{"failed to fetch database migration version"};
      if (version != expected_database_version) {
        throw std::runtime_error{std::format("database migration version ({}) does not match expected version ({}), consider running migrations", *version, expected_database_version)};
      }
    } catch (std::exception const& e) {
      throw std::runtime_error{std::format("failed to query database version: {}", e.what())};
    }
    return std::shared_ptr<connection>{new connection{std::move(dbc)}};
  }

} // namespace routemon::database