|
| 1 | +#include <vix/db/mig/diff/Diff.hpp> |
| 2 | + |
| 3 | +#include <stdexcept> |
| 4 | +#include <unordered_map> |
| 5 | + |
| 6 | +namespace vix::db::mig::diff |
| 7 | +{ |
| 8 | + using vix::db::schema::Schema; |
| 9 | + using vix::db::schema::Table; |
| 10 | + |
| 11 | + static std::unordered_map<std::string, const Table *> map_tables(const Schema &s) |
| 12 | + { |
| 13 | + std::unordered_map<std::string, const Table *> m; |
| 14 | + m.reserve(s.tables.size()); |
| 15 | + for (const auto &t : s.tables) |
| 16 | + m.emplace(t.name, &t); |
| 17 | + return m; |
| 18 | + } |
| 19 | + |
| 20 | + std::vector<Op> diff_or_throw(const Schema &from, const Schema &to) |
| 21 | + { |
| 22 | + std::vector<Op> ops; |
| 23 | + |
| 24 | + auto A = map_tables(from); |
| 25 | + auto B = map_tables(to); |
| 26 | + |
| 27 | + // 1) Drop tables missing in 'to' |
| 28 | + for (const auto &[name, ta] : A) |
| 29 | + { |
| 30 | + if (!B.count(name)) |
| 31 | + ops.push_back(DropTable{*ta}); |
| 32 | + } |
| 33 | + |
| 34 | + // 2) Create tables new in 'to' |
| 35 | + for (const auto &[name, tb] : B) |
| 36 | + { |
| 37 | + if (!A.count(name)) |
| 38 | + { |
| 39 | + ops.push_back(CreateTable{*tb}); |
| 40 | + continue; |
| 41 | + } |
| 42 | + |
| 43 | + // 3) Same table: diff columns + indexes |
| 44 | + const auto *oldT = A.at(name); |
| 45 | + const auto *newT = tb; |
| 46 | + |
| 47 | + // Columns: drops |
| 48 | + for (const auto &c_old : oldT->columns) |
| 49 | + { |
| 50 | + if (!newT->findColumn(c_old.name)) |
| 51 | + ops.push_back(DropColumn{name, c_old}); |
| 52 | + } |
| 53 | + |
| 54 | + // Columns: adds |
| 55 | + for (const auto &c_new : newT->columns) |
| 56 | + { |
| 57 | + if (!oldT->findColumn(c_new.name)) |
| 58 | + ops.push_back(AddColumn{name, c_new}); |
| 59 | + } |
| 60 | + |
| 61 | + // Indexes: drops |
| 62 | + for (const auto &i_old : oldT->indexes) |
| 63 | + { |
| 64 | + if (!newT->findIndex(i_old.name)) |
| 65 | + ops.push_back(DropIndex{name, i_old}); |
| 66 | + } |
| 67 | + |
| 68 | + // Indexes: adds |
| 69 | + for (const auto &i_new : newT->indexes) |
| 70 | + { |
| 71 | + if (!oldT->findIndex(i_new.name)) |
| 72 | + ops.push_back(CreateIndex{name, i_new}); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + return ops; |
| 77 | + } |
| 78 | + |
| 79 | +} // namespace vix::db::mig::diff |
0 commit comments