summaryrefslogtreecommitdiffstats
path: root/server/src/migrate.cppm
diff options
context:
space:
mode:
Diffstat (limited to 'server/src/migrate.cppm')
-rw-r--r--server/src/migrate.cppm126
1 files changed, 126 insertions, 0 deletions
diff --git a/server/src/migrate.cppm b/server/src/migrate.cppm
new file mode 100644
index 0000000..e5cd52a
--- /dev/null
+++ b/server/src/migrate.cppm
@@ -0,0 +1,126 @@
1module;
2
3#include <cassert>
4
5export module routemon:migrate;
6
7import :log;
8import :sqlite3;
9
10namespace routemon::migrate {
11
12auto load_migrations(std::int64_t current_version, std::int64_t target_version)
13 -> 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{"migrations"})
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
72export class migrator
73{
74 log::logger l_;
75 sqlite3::connection dbc_;
76
77 auto current_version() -> std::int64_t
78 {
79 if (auto const [has_migrations_table] =
80 dbc_.query(
81 "SELECT COUNT(*) FROM sqlite_schema WHERE "
82 "type IS 'table' AND "
83 "name IS 'migration'")
84 .scan_row_max1<std::int64_t>();
85 has_migrations_table)
86 return std::get<0>(dbc_.query("SELECT version FROM migration")
87 .scan_row_max1<std::int64_t>());
88 return 0;
89 }
90
91public:
92 explicit migrator(log::logger const& l, std::string const& filename)
93 : l_{l.sub("migrator")}, dbc_{sqlite3::open(filename)}
94 {
95 }
96
97 auto migrate_to(std::int64_t target_version) -> void
98 {
99 // Part of function contract. Consider throwing instead?
100 if (target_version < 0)
101 throw std::invalid_argument{
102 "target database version must be nonnegative"
103 };
104
105 auto current = current_version();
106 auto const migration_sqls = load_migrations(current, target_version);
107
108 for (auto const& sql : migration_sqls)
109 {
110 l_.info("Migrating from schema version {} to {}", current, current + 1);
111 migrate_step(++current, sql);
112 }
113 }
114
115 auto migrate_step(std::int64_t target_version, util::zstring_view sql) -> void
116 {
117 auto tx = sqlite3::tx{dbc_};
118 while (!sql.empty())
119 tx.exec_first(sql);
120 tx.exec(
121 "UPDATE migration SET version = :version",
122 [target_version](auto& s) { s.bind(":version", target_version); });
123 }
124};
125
126} // namespace routemon::migrate