From faaf9dd00eb3fdedfdeff8df9b905a58b38b610c Mon Sep 17 00:00:00 2001 From: Lars Vonk Date: Mon, 13 Nov 2023 14:49:39 +0100 Subject: [PATCH] Add migrating metadata tables before running migration --- lib/sequent/migrations/replayed_ids.rb | 2 +- lib/sequent/migrations/versions.rb | 2 +- lib/sequent/migrations/view_schema.rb | 16 +++++++++++----- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/lib/sequent/migrations/replayed_ids.rb b/lib/sequent/migrations/replayed_ids.rb index a1416ad8..470f53d2 100644 --- a/lib/sequent/migrations/replayed_ids.rb +++ b/lib/sequent/migrations/replayed_ids.rb @@ -3,7 +3,7 @@ module Sequent module Migrations class ReplayedIds < Sequent::ApplicationRecord - def self.sql + def self.migration_sql <<~SQL.chomp CREATE TABLE IF NOT EXISTS #{table_name} (event_id bigint NOT NULL, CONSTRAINT event_id_pk PRIMARY KEY(event_id)); SQL diff --git a/lib/sequent/migrations/versions.rb b/lib/sequent/migrations/versions.rb index 8fa7f82a..b2664319 100644 --- a/lib/sequent/migrations/versions.rb +++ b/lib/sequent/migrations/versions.rb @@ -8,7 +8,7 @@ class Versions < Sequent::ApplicationRecord MIGRATE_OFFLINE_RUNNING = 3 DONE = nil - def self.sql + def self.migration_sql <<~SQL.chomp CREATE TABLE IF NOT EXISTS #{table_name} (version integer NOT NULL, CONSTRAINT version_pk PRIMARY KEY(version)); ALTER TABLE #{table_name} ADD COLUMN IF NOT EXISTS status INTEGER DEFAULT NULL CONSTRAINT only_one_running CHECK (status in (1,2,3)); diff --git a/lib/sequent/migrations/view_schema.rb b/lib/sequent/migrations/view_schema.rb index 701cfc06..e1258dc9 100644 --- a/lib/sequent/migrations/view_schema.rb +++ b/lib/sequent/migrations/view_schema.rb @@ -162,11 +162,7 @@ def replay_all!(group_exponent: 1) # This method is mainly useful during an initial setup of the view schema def create_view_schema_if_not_exists exec_sql(%(CREATE SCHEMA IF NOT EXISTS #{view_schema})) - Sequent::ApplicationRecord.transaction do - in_view_schema do - exec_sql([ReplayedIds.sql, Versions.sql].join("\n")) - end - end + migrate_metadata_tables end def plan @@ -195,6 +191,8 @@ def executor # # @raise ConcurrentMigrationError if migration is already running def migrate_online + migrate_metadata_tables + return if Sequent.new_version == current_version ensure_version_correct! @@ -287,6 +285,14 @@ def migrate_offline private + def migrate_metadata_tables + Sequent::ApplicationRecord.transaction do + in_view_schema do + exec_sql([ReplayedIds.migration_sql, Versions.migration_sql].join("\n")) + end + end + end + def ensure_version_correct! create_view_schema_if_not_exists new_version = Sequent.new_version