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.

88 lines
2.4 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. m_user_version = version;
  21. } catch (std::exception& e) {
  22. std::cout << "Exception: " << e.what() << std::endl;
  23. }
  24. }
  25. void Schema::set_savepoint() {
  26. try {
  27. m_db->exec("BEGIN;");
  28. m_db->exec("SAVEPOINT " + m_migration_savepoint + ";");
  29. } catch (std::exception& e) {
  30. std::cout << "Exception: " << e.what() << std::endl;
  31. }
  32. }
  33. void Schema::rollback_migrations() {
  34. try {
  35. m_db->exec("ROLLBACK TO " + m_migration_savepoint + ";");
  36. } catch (std::exception& e) {
  37. std::cout << "Exception: " << e.what() << std::endl;
  38. }
  39. }
  40. void Schema::commit_migrations() {
  41. try {
  42. m_db->exec("COMMIT;");
  43. } catch (std::exception& e) {
  44. std::cout << "Exception: " << e.what() << std::endl;
  45. }
  46. }
  47. uint32_t Schema::run_migrations() {
  48. assemble_migrations();
  49. if(migrations.begin() == migrations.end()) {
  50. DEBUG << "No migrations found...";
  51. return ERROR_NO_MIGRATIONS;
  52. }
  53. set_savepoint();
  54. uint32_t user_version = get_user_version();
  55. for(auto const& [epoch, migration] : migrations) {
  56. if(epoch <= user_version) {
  57. DEBUG << "Skipping: " << migration->get_migration_name();
  58. continue;
  59. }
  60. std::cout << "migrating: " << migration->get_migration_name() << std::endl;
  61. try {
  62. m_db->exec(migration->get_statement());
  63. } catch (std::exception& e) {
  64. std::cout << "Exception: " << e.what() << std::endl;
  65. std::cout << "Rolling back migrations..." << std::endl;
  66. rollback_migrations();
  67. return ERROR_FAULTY_MIGRATION;
  68. }
  69. }
  70. commit_migrations();
  71. set_user_version(migrations.rbegin()->first);
  72. return 0;
  73. }
  74. void Schema::assemble_migrations() {
  75. migrations.emplace(1624829187, new db::migrations::m1624829187_create_events());
  76. }
  77. }