diff --git a/lib/sequent/migrations/versions.rb b/lib/sequent/migrations/versions.rb index b2664319..f5d2bc78 100644 --- a/lib/sequent/migrations/versions.rb +++ b/lib/sequent/migrations/versions.rb @@ -11,8 +11,10 @@ class Versions < Sequent::ApplicationRecord 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} drop constraint if exists only_one_running; ALTER TABLE #{table_name} ADD COLUMN IF NOT EXISTS status INTEGER DEFAULT NULL CONSTRAINT only_one_running CHECK (status in (1,2,3)); - CREATE UNIQUE INDEX IF NOT EXISTS single_migration_running ON #{table_name} (status); + DROP INDEX IF EXISTS single_migration_running; + CREATE UNIQUE INDEX single_migration_running ON #{table_name} ((status * 0)) where status is not null; SQL end diff --git a/spec/lib/sequent/migrations/view_schema_spec.rb b/spec/lib/sequent/migrations/view_schema_spec.rb index c8c90b2c..9200c816 100644 --- a/spec/lib/sequent/migrations/view_schema_spec.rb +++ b/spec/lib/sequent/migrations/view_schema_spec.rb @@ -59,6 +59,17 @@ expect(Sequent::ApplicationRecord.connection).to have_schema(view_schema) end + + it 'can not insert two versions with a status' do + migrator.create_view_schema_if_not_exists + migrator.create_view_schema_if_not_exists + + Sequent::Migrations::Versions.create!(version: 1, status: nil) + Sequent::Migrations::Versions.create!(version: 2, status: 1) + expect do + Sequent::Migrations::Versions.create!(version: 3, status: 2) + end.to raise_error(ActiveRecord::RecordNotUnique) + end end context '#create_view_tables' do