You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.7 KiB

  1. #include "Schema.h"
  2. #include <io/debug.h>
  3. #include "migrations/1624829187_create_events.h"
  4. namespace db {
  5. namespace db_builder = db::migrations::builder;
  6. Schema::Schema(sql::Database* db) : m_db(db) {
  7. }
  8. uint32_t Schema::get_user_version() const {
  9. try {
  10. int user_version = m_db->execAndGet("PRAGMA user_version;");
  11. return user_version;
  12. } catch (std::exception& e) {
  13. std::cout << "Exception: " << e.what() << std::endl;
  14. return -1;
  15. }
  16. }
  17. void Schema::set_user_version(uint32_t version) {
  18. try {
  19. m_db->exec("PRAGMA user_version = " + std::to_string(version) + ";");
  20. } catch (std::exception& e) {
  21. std::cout << "Exception: " << e.what() << std::endl;
  22. }
  23. }
  24. void Schema::run_migrations() {
  25. assemble_migrations();
  26. if(migrations.begin() == migrations.end()) {
  27. DEBUG << "No migrations found...";
  28. return;
  29. }
  30. // TODO try and catch block
  31. // migration should stop on error and restore old schema
  32. uint32_t user_version = get_user_version();
  33. for(auto const& [epoch, migration] : migrations) {
  34. if(epoch <= user_version) {
  35. DEBUG << "Skipping: " << migration->get_migration_name();
  36. continue;
  37. }
  38. DEBUG << "migrating: " << migration->get_migration_name();
  39. try {
  40. m_db->exec(migration->get_statement());
  41. } catch (std::exception& e) {
  42. std::cout << "Exception: " << e.what() << std::endl;
  43. }
  44. }
  45. DEBUG << migrations.rbegin()->first;
  46. set_user_version(migrations.rbegin()->first);
  47. user_version = get_user_version();
  48. DEBUG << user_version;
  49. }
  50. void Schema::assemble_migrations() {
  51. migrations.emplace(1624829187, new db::migrations::m1624829187_create_events());
  52. }
  53. }