From a65a23c4f35b290e8caee79aca2b1de088c4ab02 Mon Sep 17 00:00:00 2001 From: Philipp Thun Date: Wed, 7 Oct 2026 12:40:50 +0200 Subject: [PATCH 1/2] Use shared-context helpers in migration specs Replace raw Sequel::Migrator.run calls in migration specs with the run_migration and revert_migration helpers, and use the test_up_migration_idempotency / test_down_migration_idempotency helpers for idempotency checks. The idempotency helpers assert the expected schema_migrations state, then delete or insert the row before re-running, so the migration body is genuinely re-executed. Re-running the migrator to the same target only is a no-op and does not test idempotency. Apply each helper only where the migration body supports it: options like add_column(if_not_exists:) are honoured on PostgreSQL but ignored on MySQL, so such migrations assert idempotency in a database-gated context. Single-database migrations are exercised only there, and migrations with unguarded DDL or no reversible down assert only the steps that apply. Each added step asserts state in the same style as the rest of its spec. Update spec/migrations/Readme.md to document the four helpers and their preconditions. Add two custom cops: UseMigrationHelpers flags raw Sequel::Migrator.run calls in specs that include the shared context, and RequireMigrationSharedContext flags per-migration specs that omit it. Legacy and bigint-step specs are excluded via .rubocop_cc.yml. Teach TooManyMigrationRuns to count the four helpers only when the migration shared context is included, while retaining detection of direct migrator calls and local wrappers. Share context detection across all three cops and add regression coverage for unrelated helper names and invalid idempotency-check setup. --- .rubocop_cc.yml | 17 ++ spec/linters/migration/migration_context.rb | 20 ++ .../require_migration_shared_context.rb | 23 +++ .../require_migration_shared_context_spec.rb | 60 ++++++ .../migration/too_many_migration_runs.rb | 40 ++-- .../migration/too_many_migration_runs_spec.rb | 159 ++++++++++++---- .../migration/use_migration_helpers.rb | 43 +++++ .../migration/use_migration_helpers_spec.rb | 141 ++++++++++++++ ...0_streamline_annotation_key_prefix_spec.rb | 8 +- ...rosecond_timestamp_msql_asg_update_spec.rb | 21 ++- ...13105256_add_service_plan_id_index_spec.rb | 13 +- ...remove_deployments_with_degenerate_spec.rb | 13 +- ...3000_rename_annotations_key_column_spec.rb | 23 ++- ...00_add_annotation_label_uniqueness_spec.rb | 178 +++++++++--------- ...add_delete_cascade_to_foreign_keys_spec.rb | 21 ++- ...19113000_add_routes_space_id_index_spec.rb | 19 +- ..._change_delayed_jobs_reserve_index_spec.rb | 23 ++- ...131908_add_user_guid_to_jobs_table_spec.rb | 8 +- ...ask_guid_index_to_app_usage_events_spec.rb | 8 +- ...742_add_jobs_user_guid_state_index_spec.rb | 8 +- ..._add_foreign_key_apps_droplet_guid_spec.rb | 14 +- ...straint_quota_definitions_name_key_spec.rb | 64 ++----- ...ed_service_bindings_enabled_column_spec.rb | 6 +- ...ove_unnecessary_fk_in_job_warnings_spec.rb | 6 +- ...ed_service_binding_feature_columns_spec.rb | 8 +- ..._add_user_id_index_to_roles_tables_spec.rb | 8 +- ...250610212414_add_user_to_processes_spec.rb | 8 +- .../20250630170610_add_user_to_tasks_spec.rb | 8 +- ...27_allow_multiple_service_bindings_spec.rb | 8 +- ...ecurity_groups_spaces_unique_index_spec.rb | 10 +- ...135214_route_bindings_unique_index_spec.rb | 8 +- ...onstraint_to_sidecar_process_types_spec.rb | 15 +- ...20251117123719_add_state_to_stacks_spec.rb | 14 +- ...ided_metadata_to_service_instances_spec.rb | 6 +- ...dd_unique_constraint_to_buildpacks_spec.rb | 10 +- ...ue_constraint_to_revision_sidecars_spec.rb | 12 +- ..._add_unique_constraint_to_sidecars_spec.rb | 12 +- ...ique_constraint_to_security_groups_spec.rb | 16 +- ...raint_to_revision_process_commands_spec.rb | 12 +- ...00_add_composite_indexes_to_events_spec.rb | 8 +- ...8120000_add_lifecycle_type_to_apps_spec.rb | 13 +- ...100_add_lifecycle_type_to_droplets_spec.rb | 13 +- ...20200_add_lifecycle_type_to_builds_spec.rb | 13 +- ...445_add_jobs_operation_state_index_spec.rb | 10 +- ...0260630120000_add_status_to_spaces_spec.rb | 16 +- ...11120000_add_root_job_guid_to_jobs_spec.rb | 8 +- ...0825120000_backfill_lifecycle_type_spec.rb | 18 +- ...0_make_lifecycle_type_non_nullable_spec.rb | 14 +- ...dd_buildpack_lifecycle_credentials_spec.rb | 25 +-- spec/migrations/Readme.md | 49 ++++- .../helpers/migration_shared_context.rb | 26 ++- .../helpers/migration_shared_context_spec.rb | 28 +++ 52 files changed, 1005 insertions(+), 327 deletions(-) create mode 100644 spec/linters/migration/migration_context.rb create mode 100644 spec/linters/migration/require_migration_shared_context.rb create mode 100644 spec/linters/migration/require_migration_shared_context_spec.rb create mode 100644 spec/linters/migration/use_migration_helpers.rb create mode 100644 spec/linters/migration/use_migration_helpers_spec.rb create mode 100644 spec/migrations/helpers/migration_shared_context_spec.rb diff --git a/.rubocop_cc.yml b/.rubocop_cc.yml index 1e3cfb9b941..b41c68fe039 100644 --- a/.rubocop_cc.yml +++ b/.rubocop_cc.yml @@ -12,8 +12,10 @@ require: - ./spec/linters/migration/add_constraint_name.rb - ./spec/linters/migration/include_string_size.rb - ./spec/linters/migration/no_model_in_specs.rb + - ./spec/linters/migration/require_migration_shared_context.rb - ./spec/linters/migration/require_primary_key.rb - ./spec/linters/migration/too_many_migration_runs.rb + - ./spec/linters/migration/use_migration_helpers.rb - ./spec/linters/match_requires_with_includes.rb - ./spec/linters/prefer_oj_over_other_json_libraries.rb @@ -126,6 +128,21 @@ Style/RaiseArgs: Migration/TooManyMigrationRuns: Exclude: - spec/linters/migration/too_many_migration_runs.rb +Migration/UseMigrationHelpers: + Exclude: + - spec/migrations/helpers/**/* +Migration/RequireMigrationSharedContext: + Include: + - spec/migrations/**/* + Exclude: + - spec/migrations/helpers/**/* + # old migration specs + - !ruby/regexp /spec/migrations/201([0-9]).+_spec\.rb$/ + - !ruby/regexp /spec/migrations/202([0-2]).+_spec\.rb$/ + # specs not testing a specific migration (no timestamp prefix) + - !ruby/regexp /spec/migrations/[a-z]+.+_spec\.rb$/ + # bigint migration step specs use their own 'bigint migration *' contexts by design + - !ruby/regexp /spec/migrations/.+_bigint_migration_.+_spec\.rb$/ #### ENABLED SECTION Capybara/FindAllFirst: diff --git a/spec/linters/migration/migration_context.rb b/spec/linters/migration/migration_context.rb new file mode 100644 index 00000000000..6e13e44bcf2 --- /dev/null +++ b/spec/linters/migration/migration_context.rb @@ -0,0 +1,20 @@ +module RuboCop + module Cop + module Migration + module MigrationContext + private + + def includes_migration_context? + processed_source.ast.each_descendant(:send).any? { |node| migration_shared_context?(node) } + end + + def migration_shared_context?(node) + node.method_name == :include_context && + node.receiver.nil? && + node.first_argument&.str_type? && + node.first_argument.value == 'migration' + end + end + end + end +end diff --git a/spec/linters/migration/require_migration_shared_context.rb b/spec/linters/migration/require_migration_shared_context.rb new file mode 100644 index 00000000000..d69a7de2f5c --- /dev/null +++ b/spec/linters/migration/require_migration_shared_context.rb @@ -0,0 +1,23 @@ +require_relative 'migration_context' + +module RuboCop + module Cop + module Migration + class RequireMigrationSharedContext < Base + include MigrationContext + + MSG = "Per-migration specs must include the 'migration' shared context " \ + "(include_context 'migration') so they use the shared setup and helpers " \ + '(run_migration, revert_migration, test_up_migration_idempotency, ' \ + 'test_down_migration_idempotency). See spec/migrations/Readme.md for details.'.freeze + + def on_new_investigation + return unless processed_source.ast + return if includes_migration_context? + + add_offense(processed_source.ast) + end + end + end + end +end diff --git a/spec/linters/migration/require_migration_shared_context_spec.rb b/spec/linters/migration/require_migration_shared_context_spec.rb new file mode 100644 index 00000000000..25db6d47008 --- /dev/null +++ b/spec/linters/migration/require_migration_shared_context_spec.rb @@ -0,0 +1,60 @@ +require 'spec_helper' +require 'rubocop' +require 'rubocop/rspec/cop_helper' +require 'rubocop/config' +require 'linters/migration/require_migration_shared_context' + +RSpec.describe RuboCop::Cop::Migration::RequireMigrationSharedContext do + include CopHelper + + subject(:cop) { described_class.new(RuboCop::Config.new({})) } + + let(:message) { described_class::MSG } + + it 'registers an offense when the migration shared context is missing' do + result = inspect_source(<<~RUBY) + RSpec.describe 'adds a column' do + it 'works' do + expect(true).to be(true) + end + end + RUBY + + expect(result.size).to eq(1) + expect(result.map(&:message)).to eq([message]) + end + + it 'does not register an offense when the context is included via a block' do + result = inspect_source(<<~RUBY) + RSpec.describe 'adds a column' do + include_context 'migration' do + let(:migration_filename) { 'x.rb' } + end + end + RUBY + + expect(result.size).to eq(0) + end + + it 'does not register an offense for the bare include_context form' do + result = inspect_source(<<~RUBY) + RSpec.describe 'adds a column' do + include_context 'migration' + end + RUBY + + expect(result.size).to eq(0) + end + + it 'registers an offense when only a different shared context is included' do + result = inspect_source(<<~RUBY) + RSpec.describe 'adds a column' do + include_context 'bigint migration step1' do + let(:migration_filename) { 'x.rb' } + end + end + RUBY + + expect(result.size).to eq(1) + end +end diff --git a/spec/linters/migration/too_many_migration_runs.rb b/spec/linters/migration/too_many_migration_runs.rb index 3b4c393aeb6..6ae04d81958 100644 --- a/spec/linters/migration/too_many_migration_runs.rb +++ b/spec/linters/migration/too_many_migration_runs.rb @@ -1,10 +1,17 @@ +require_relative 'migration_context' + module RuboCop module Cop module Migration class TooManyMigrationRuns < Base + include MigrationContext + + MIGRATION_HELPERS = %i[run_migration revert_migration test_up_migration_idempotency test_down_migration_idempotency].freeze + def on_new_investigation return unless processed_source.ast + @includes_migration_context = includes_migration_context? definitions = extract_migrator_definitions call_count = count_migrator_calls(definitions) @@ -38,7 +45,7 @@ def extract_migrator_definitions end def extract_migrator_method(node, method_names) - return unless contains_migrator_run?(node) + return unless contains_migration_run?(node) method_names << node.method_name end @@ -54,12 +61,12 @@ def extract_block_definitions(node, definitions) when :let, :let! extract_named_migrator(node, definitions[:let_names]) when :before, :after, :around - definitions[:before_after_blocks].add(node.object_id) if contains_migrator_run?(node) + definitions[:before_after_blocks].add(node.object_id) if contains_migration_run?(node) end end def extract_named_migrator(node, names) - return unless contains_migrator_run?(node) + return unless contains_migration_run?(node) first_arg = node.send_node.first_argument names << first_arg.value if first_arg&.sym_type? @@ -84,20 +91,25 @@ def migration_call?(node, definitions) end if in_before_after_block - # Count direct Migrator.run calls inside before/after/around blocks - migrator_run_call?(node) + # Count migration runs inside before/after/around blocks + migration_run_call?(node) else - # Count direct calls (not in definitions) or helper invocations - direct_migrator_call?(node) || helper_migration_call?(node, definitions) + # Count direct calls (not in definitions) or local wrapper invocations + direct_migration_call?(node) || local_migration_wrapper_call?(node, definitions) end end - def direct_migrator_call?(node) - return false unless migrator_run_call?(node) + def direct_migration_call?(node) + return false unless migration_run_call?(node) !inside_definition?(node) end + def migration_run_call?(node) + migrator_run_call?(node) || + (@includes_migration_context && MIGRATION_HELPERS.include?(node.method_name) && (node.receiver.nil? || node.receiver.self_type?)) + end + def migrator_run_call?(node) return false unless node.method_name == :run @@ -113,28 +125,28 @@ def migrator_run_call?(node) false end - def helper_migration_call?(node, definitions) + def local_migration_wrapper_call?(node, definitions) method = node.method_name definitions[:subject_names].include?(method) || definitions[:let_names].include?(method) || definitions[:method_names].include?(method) end - def contains_migrator_run?(node) - node.each_descendant(:send).any? { |send_node| migrator_run_call?(send_node) } + def contains_migration_run?(node) + node.each_descendant(:send).any? { |send_node| migration_run_call?(send_node) } end def inside_definition?(node) node.each_ancestor(:def, :block).any? do |ancestor| case ancestor.type when :def - contains_migrator_run?(ancestor) + contains_migration_run?(ancestor) when :block next false unless ancestor.send_node method = ancestor.send_node.method_name if %i[subject let let!].include?(method) - contains_migrator_run?(ancestor) + contains_migration_run?(ancestor) else %i[before after around].include?(method) end diff --git a/spec/linters/migration/too_many_migration_runs_spec.rb b/spec/linters/migration/too_many_migration_runs_spec.rb index 662383ae41d..a5d4cb81fd5 100644 --- a/spec/linters/migration/too_many_migration_runs_spec.rb +++ b/spec/linters/migration/too_many_migration_runs_spec.rb @@ -27,60 +27,91 @@ def it_blocks(count) expect(result.first.message).to include('(5)') end - it 'counts multiple migrations in a single it block' do + it 'does not register an offense for 4 or fewer shared-context helper calls' do + %w[run_migration revert_migration test_up_migration_idempotency test_down_migration_idempotency].each do |helper| + source = <<~RUBY + RSpec.describe('m') do + include_context 'migration' + #{(1..4).map { |n| "it('t#{n}') { #{helper} }" }.join("\n")} + end + RUBY + + expect(inspect_source(source)).to be_empty, "Expected no offense for #{helper}" + end + end + + it 'registers an offense for more than 4 shared-context helper calls' do + %w[run_migration revert_migration test_up_migration_idempotency test_down_migration_idempotency].each do |helper| + source = <<~RUBY + RSpec.describe('m') do + include_context 'migration' + #{(1..5).map { |n| "it('t#{n}') { #{helper} }" }.join("\n")} + end + RUBY + + result = inspect_source(source) + expect(result.size).to eq(1), "Expected offense for #{helper}" + expect(result.first.message).to include('(5)') + end + end + + it 'counts a mix of direct calls and all four shared-context helpers' do source = <<~RUBY RSpec.describe('m') do + include_context 'migration' it('test') do - #{(1..5).map { |n| migration_call(n) }.join("\n")} + #{migration_call(1)} + run_migration + revert_migration + test_up_migration_idempotency + test_down_migration_idempotency end end RUBY + result = inspect_source(source) expect(result.size).to eq(1) expect(result.first.message).to include('(5)') end - it 'counts migrations via subject, let, let!, and helper methods' do + it 'counts explicit self helper calls only in files including the migration shared context' do source = <<~RUBY RSpec.describe('m') do - subject(:migrate_subj) { #{migration_call(1)} } - let(:migrate_let) { #{migration_call(2)} } - let!(:migrate_let_bang) { #{migration_call(3)} } - def migrate_method; #{migration_call(4)}; end - - it('t1') { migrate_subj } - it('t2') { migrate_let } - it('t3') { migrate_let_bang } - it('t4') { migrate_method } - it('t5') { migrate_subj } + include_context 'migration' + #{(1..5).map { |n| "it('t#{n}') { self.run_migration }" }.join("\n")} end RUBY + result = inspect_source(source) expect(result.size).to eq(1) expect(result.first.message).to include('(5)') + + expect(inspect_source(source.sub("include_context 'migration'", "include_context 'other'"))).to be_empty + expect(inspect_source(source).size).to eq(1) end - it 'does not double-count definitions - only invocations' do + it 'does not count calls to similarly named methods on other objects' do source = <<~RUBY RSpec.describe('m') do - subject(:migrate) { #{migration_call(1)} } - it('t1') { migrate } - it('t2') { migrate } - it('t3') { migrate } - it('t4') { migrate } + it('test') do + runner.run_migration + runner.revert_migration + runner.test_up_migration_idempotency + runner.test_down_migration_idempotency + runner.run_migration + end end RUBY - result = inspect_source(source) - expect(result).to be_empty + + expect(inspect_source(source)).to be_empty end - it 'counts migrations in before/after blocks' do + it 'counts multiple migrations in a single it block' do source = <<~RUBY RSpec.describe('m') do - before { #{migration_call(1)}; #{migration_call(2)} } - after { #{migration_call(3)} } - it('t1') { #{migration_call(4)} } - it('t2') { #{migration_call(5)} } + it('test') do + #{(1..5).map { |n| migration_call(n) }.join("\n")} + end end RUBY result = inspect_source(source) @@ -88,15 +119,75 @@ def migrate_method; #{migration_call(4)}; end expect(result.first.message).to include('(5)') end + it 'counts migrations via subject, let, let!, and local wrapper methods' do + [migration_call(1), 'run_migration'].each do |call| + migration_context = "include_context 'migration'" if call == 'run_migration' + source = <<~RUBY + RSpec.describe('m') do + #{migration_context} + subject(:migrate_subj) { #{call} } + let(:migrate_let) { #{call} } + let!(:migrate_let_bang) { #{call} } + def migrate_method; #{call}; end + + it('t1') { migrate_subj } + it('t2') { migrate_let } + it('t3') { migrate_let_bang } + it('t4') { migrate_method } + it('t5') { migrate_subj } + end + RUBY + result = inspect_source(source) + expect(result.size).to eq(1), "Expected offense for wrappers containing #{call}" + expect(result.first.message).to include('(5)') + end + end + + it 'does not double-count definitions - only invocations' do + [migration_call(1), 'run_migration'].each do |call| + source = <<~RUBY + RSpec.describe('m') do + include_context 'migration' + subject(:migrate) { #{call} } + it('t1') { migrate } + it('t2') { migrate } + it('t3') { migrate } + it('t4') { migrate } + end + RUBY + result = inspect_source(source) + expect(result).to be_empty, "Expected no offense for a subject containing #{call}" + end + end + + it 'counts migrations in before/after/around blocks' do + [migration_call(2), 'run_migration'].each do |call| + source = <<~RUBY + RSpec.describe('m') do + include_context 'migration' + before { #{migration_call(1)}; #{call} } + after { #{call} } + around { |example| #{call}; example.run } + it('test') { #{call} } + end + RUBY + result = inspect_source(source) + expect(result.size).to eq(1), "Expected offense for hooks containing #{call}" + expect(result.first.message).to include('(5)') + end + end + it 'does not count non-migration let invocations' do - source = <<~RUBY - RSpec.describe('m') do - let(:value) { 'not a migration' } - #{(1..4).map { |n| "it('t#{n}') { value; #{migration_call(n)} }" }.join("\n")} - end - RUBY - result = inspect_source(source) - expect(result).to be_empty + %w[value run_migration revert_migration test_up_migration_idempotency test_down_migration_idempotency].each do |name| + source = <<~RUBY + RSpec.describe('m') do + let(:#{name}) { 'not a migration' } + #{(1..4).map { |n| "it('t#{n}') { #{name}; #{migration_call(n)} }" }.join("\n")} + end + RUBY + + expect(inspect_source(source)).to be_empty, "Expected no offense for unrelated #{name}" + end end it 'handles empty files and files without migrations' do diff --git a/spec/linters/migration/use_migration_helpers.rb b/spec/linters/migration/use_migration_helpers.rb new file mode 100644 index 00000000000..72abf71d512 --- /dev/null +++ b/spec/linters/migration/use_migration_helpers.rb @@ -0,0 +1,43 @@ +require_relative 'migration_context' + +module RuboCop + module Cop + module Migration + class UseMigrationHelpers < Base + include MigrationContext + + MSG = 'Do not call Sequel::Migrator.run directly in a migration spec that includes ' \ + "the 'migration' shared context. " \ + 'Use the provided helpers instead: run_migration, revert_migration, ' \ + 'test_up_migration_idempotency, test_down_migration_idempotency. ' \ + 'See spec/migrations/Readme.md for details.'.freeze + + HOOK_METHODS = %i[before after around].freeze + + def on_new_investigation + return unless processed_source.ast + return unless includes_migration_context? + + processed_source.ast.each_descendant(:send) do |node| + next unless migrator_run_call?(node) + next if inside_hook_block?(node) + + add_offense(node) + end + end + + private + + def inside_hook_block?(node) + node.each_ancestor(:block).any? { |block| HOOK_METHODS.include?(block.send_node.method_name) } + end + + def migrator_run_call?(node) + node.method_name == :run && + node.receiver&.const_type? && + ['Migrator', 'Sequel::Migrator'].include?(node.receiver.const_name) + end + end + end + end +end diff --git a/spec/linters/migration/use_migration_helpers_spec.rb b/spec/linters/migration/use_migration_helpers_spec.rb new file mode 100644 index 00000000000..e68e3fe6b8c --- /dev/null +++ b/spec/linters/migration/use_migration_helpers_spec.rb @@ -0,0 +1,141 @@ +require 'spec_helper' +require 'rubocop' +require 'rubocop/rspec/cop_helper' +require 'rubocop/config' +require 'linters/migration/use_migration_helpers' + +RSpec.describe RuboCop::Cop::Migration::UseMigrationHelpers do + include CopHelper + + subject(:cop) { described_class.new(RuboCop::Config.new({})) } + + let(:message) { described_class::MSG } + + it 'registers an offense for Sequel::Migrator.run inside an example when the context is present' do + result = inspect_source(<<~RUBY) + RSpec.describe 'migration' do + include_context 'migration' do + let(:migration_filename) { 'x.rb' } + end + + it 'runs' do + expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index) }.not_to raise_error + end + end + RUBY + + expect(result.size).to eq(1) + expect(result.map(&:message)).to eq([message]) + end + + it 'registers an offense for an unqualified Migrator.run when the context is present' do + result = inspect_source(<<~RUBY) + RSpec.describe 'migration' do + include_context 'migration' do + let(:migration_filename) { 'x.rb' } + end + + it 'runs' do + expect { Migrator.run(db, migrations_path, target: current_migration_index) }.not_to raise_error + end + end + RUBY + + expect(result.size).to eq(1) + end + + it 'registers one offense per direct call' do + result = inspect_source(<<~RUBY) + RSpec.describe 'migration' do + include_context 'migration' do + let(:migration_filename) { 'x.rb' } + end + + it 'runs' do + Sequel::Migrator.run(db, migrations_path, target: current_migration_index) + Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1) + end + end + RUBY + + expect(result.size).to eq(2) + end + + it 'does not register an offense for a call inside a before hook' do + result = inspect_source(<<~RUBY) + RSpec.describe 'migration' do + include_context 'migration' do + let(:migration_filename) { 'x.rb' } + end + + before do + Sequel::Migrator.run(db, migrations_path, target: current_migration_index) + end + end + RUBY + + expect(result.size).to eq(0) + end + + it 'does not register an offense for a call inside an after hook' do + result = inspect_source(<<~RUBY) + RSpec.describe 'migration' do + include_context 'migration' do + let(:migration_filename) { 'x.rb' } + end + + after do + Sequel::Migrator.run(db, migrations_path, target: current_migration_index) + end + end + RUBY + + expect(result.size).to eq(0) + end + + it 'does not register an offense for a call inside an around hook' do + result = inspect_source(<<~RUBY) + RSpec.describe 'migration' do + include_context 'migration' do + let(:migration_filename) { 'x.rb' } + end + + around do |example| + Sequel::Migrator.run(db, migrations_path, target: current_migration_index) + example.run + end + end + RUBY + + expect(result.size).to eq(0) + end + + it 'does not register an offense when the migration shared context is absent' do + result = inspect_source(<<~RUBY) + RSpec.describe 'migration' do + it 'runs' do + expect { Sequel::Migrator.run(db, migrations_path, target: 1) }.not_to raise_error + end + end + RUBY + + expect(result.size).to eq(0) + end + + it 'does not register an offense when the helpers are used' do + result = inspect_source(<<~RUBY) + RSpec.describe 'migration' do + include_context 'migration' do + let(:migration_filename) { 'x.rb' } + end + + it 'runs' do + expect { run_migration }.not_to raise_error + test_up_migration_idempotency + end + end + RUBY + + expect(result.size).to eq(0) + end +end diff --git a/spec/migrations/20230822153000_streamline_annotation_key_prefix_spec.rb b/spec/migrations/20230822153000_streamline_annotation_key_prefix_spec.rb index 8732775be59..47f23de15b2 100644 --- a/spec/migrations/20230822153000_streamline_annotation_key_prefix_spec.rb +++ b/spec/migrations/20230822153000_streamline_annotation_key_prefix_spec.rb @@ -18,7 +18,7 @@ anno2 = db[:isolation_segment_annotations].first(key: 'mykey') anno3 = db[:isolation_segment_annotations].first(key: 'yourkey') - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + expect { run_migration }.not_to raise_error # Check legacy prefix was converted anno1_after_mig = db[:isolation_segment_annotations].first(guid: 'anno-1-guid') @@ -36,6 +36,12 @@ anno3_after_mig = db[:isolation_segment_annotations].first(guid: 'anno-3-guid') expect(anno2.values).to eq(anno2_after_mig.values) expect(anno3.values).to eq(anno3_after_mig.values) + + # Up migration idempotency + test_up_migration_idempotency + anno1_after_idempotency = db[:isolation_segment_annotations].first(guid: 'anno-1-guid') + expect(anno1_after_idempotency[:key_prefix]).to eq 'mylegacyprefix' + expect(anno1_after_idempotency[:key]).to eq 'mykey' end end end diff --git a/spec/migrations/20231016094900_microsecond_timestamp_msql_asg_update_spec.rb b/spec/migrations/20231016094900_microsecond_timestamp_msql_asg_update_spec.rb index 7ccd9d1432e..131aa4e859a 100644 --- a/spec/migrations/20231016094900_microsecond_timestamp_msql_asg_update_spec.rb +++ b/spec/migrations/20231016094900_microsecond_timestamp_msql_asg_update_spec.rb @@ -26,7 +26,7 @@ end # Change TIMESTAMP to TIMESTAMP(6) - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + expect { run_migration }.not_to raise_error # the migration shouldn't add accuracy to previously inserted values t1_post_migration = ds.first(id: 1) @@ -38,6 +38,25 @@ expect(t2[:last_update].to_datetime.subsec).not_to eq(0) expect(t2[:last_update].to_datetime.rfc3339(6)).to eq(dt_with_fractional_seconds.rfc3339(6)) + + # The up/down bodies only change the column type on MySQL, so the re-run and revert + # precision assertions below are only meaningful there. + next unless db.database_type == :mysql + + # Up migration idempotency - microsecond precision retained + test_up_migration_idempotency + ds.insert(id: 3, last_update: dt_with_fractional_seconds) + expect(ds.first(id: 3)[:last_update].to_datetime.subsec).not_to eq(0) + + # Down migration - precision reverted to seconds + expect { revert_migration }.not_to raise_error + ds.insert(id: 4, last_update: dt_with_fractional_seconds) + expect(ds.first(id: 4)[:last_update].to_datetime.subsec).to eq(0) + + # Down migration idempotency - still seconds precision + test_down_migration_idempotency + ds.insert(id: 5, last_update: dt_with_fractional_seconds) + expect(ds.first(id: 5)[:last_update].to_datetime.subsec).to eq(0) end end end diff --git a/spec/migrations/20231113105256_add_service_plan_id_index_spec.rb b/spec/migrations/20231113105256_add_service_plan_id_index_spec.rb index 85a620897a7..3349a7b8327 100644 --- a/spec/migrations/20231113105256_add_service_plan_id_index_spec.rb +++ b/spec/migrations/20231113105256_add_service_plan_id_index_spec.rb @@ -6,7 +6,16 @@ let(:migration_filename) { '20231113105256_add_service_plan_id_index.rb' } end - it 'succeeds' do - Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) + # The migration body is a no-op on MySQL, so only exercise it on PostgreSQL. + it 'adds and removes the index' do + skip if db.database_type != :postgres + + expect(db.indexes(:service_plan_visibilities)).not_to include(:spv_service_plan_id_index) + + expect { run_migration }.not_to raise_error + expect(db.indexes(:service_plan_visibilities)).to include(:spv_service_plan_id_index) + + expect { revert_migration }.not_to raise_error + expect(db.indexes(:service_plan_visibilities)).not_to include(:spv_service_plan_id_index) end end diff --git a/spec/migrations/20231205143526_remove_deployments_with_degenerate_spec.rb b/spec/migrations/20231205143526_remove_deployments_with_degenerate_spec.rb index 2597a83adf9..dd9b59bc9b3 100644 --- a/spec/migrations/20231205143526_remove_deployments_with_degenerate_spec.rb +++ b/spec/migrations/20231205143526_remove_deployments_with_degenerate_spec.rb @@ -20,7 +20,7 @@ expect { db[:deployments].where(guid: 'degenerate_guid').delete }.to raise_error(Sequel::ForeignKeyConstraintViolation) - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + expect { run_migration }.not_to raise_error expect(db[:deployments].where(status_reason: 'DEGENERATE').count).to eq(0) @@ -33,6 +33,17 @@ expect(db[:deployment_processes].first(guid: 'deployed_process_guid')).not_to be_nil expect(db[:deployment_annotations].first(guid: 'deployed_annotation_guid')).not_to be_nil expect(db[:deployment_labels].first(guid: 'deployed_label_guid')).not_to be_nil + + # Up migration idempotency - no degenerate records left to remove + test_up_migration_idempotency + expect(db[:deployments].where(status_reason: 'DEGENERATE').count).to eq(0) + + # Down migration is intentionally a no-op (deleted rows cannot be recovered) + expect { revert_migration }.not_to raise_error + expect(db[:deployments].first(guid: 'degenerate_guid')).to be_nil + + test_down_migration_idempotency + expect(db[:deployments].first(guid: 'degenerate_guid')).to be_nil end end end diff --git a/spec/migrations/20231221123000_rename_annotations_key_column_spec.rb b/spec/migrations/20231221123000_rename_annotations_key_column_spec.rb index 561ec6d6342..be6327352b0 100644 --- a/spec/migrations/20231221123000_rename_annotations_key_column_spec.rb +++ b/spec/migrations/20231221123000_rename_annotations_key_column_spec.rb @@ -43,11 +43,32 @@ expect(db[table.to_sym].columns).to include(:key) expect(db[table.to_sym].columns).not_to include(:key_name) end - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + expect { run_migration }.not_to raise_error annotation_tables.each do |table| expect(db[table.to_sym].columns).not_to include(:key) expect(db[table.to_sym].columns).to include(:key_name) end + + # Up migration idempotency - column already renamed + test_up_migration_idempotency + annotation_tables.each do |table| + expect(db[table.to_sym].columns).not_to include(:key) + expect(db[table.to_sym].columns).to include(:key_name) + end + + # Down migration - column renamed back + expect { revert_migration }.not_to raise_error + annotation_tables.each do |table| + expect(db[table.to_sym].columns).to include(:key) + expect(db[table.to_sym].columns).not_to include(:key_name) + end + + # Down migration idempotency - column already renamed back + test_down_migration_idempotency + annotation_tables.each do |table| + expect(db[table.to_sym].columns).to include(:key) + expect(db[table.to_sym].columns).not_to include(:key_name) + end end end end diff --git a/spec/migrations/20240102150000_add_annotation_label_uniqueness_spec.rb b/spec/migrations/20240102150000_add_annotation_label_uniqueness_spec.rb index 6a9d27aad46..5c66356dc8a 100644 --- a/spec/migrations/20240102150000_add_annotation_label_uniqueness_spec.rb +++ b/spec/migrations/20240102150000_add_annotation_label_uniqueness_spec.rb @@ -8,7 +8,7 @@ let(:annotation) { VCAP::CloudController::IsolationSegmentAnnotationModel } let(:label) { VCAP::CloudController::IsolationSegmentLabelModel } - describe 'annotation tables' do + describe 'annotation and label tables' do it 'handles key truncation, duplicate removal, and uniqueness constraints' do # Setup data for truncation test i1 = isolation_segment.create(name: 'bommel') @@ -65,8 +65,54 @@ # In case key_prefix is set annotation.create(resource_guid: i5.guid, key_prefix: 'unique_prefix', key_name: key_f, value: 'v1') + # Setup label data for duplicate removal test + label_i1 = isolation_segment.create(name: 'label_dup_test') + label_key_a = 'a' * 63 + + # In case key_prefix is not set + label_dup_a1 = label.create(resource_guid: label_i1.guid, key_name: label_key_a, value: 'v1') + label_dup_a2 = label.create(resource_guid: label_i1.guid, key_name: label_key_a, value: 'v2') + label_dup_a3 = label.create(resource_guid: label_i1.guid, key_name: label_key_a, value: 'v3') + + # In case key_prefix is set + label_dup_b1 = label.create(resource_guid: label_i1.guid, key_prefix: 'bommel', key_name: label_key_a, value: 'v1') + label_dup_b2 = label.create(resource_guid: label_i1.guid, key_prefix: 'bommel', key_name: label_key_a, value: 'v2') + label_dup_b3 = label.create(resource_guid: label_i1.guid, key_prefix: 'bommel', key_name: label_key_a, value: 'v3') + expect(label_dup_a1.id).to be < label_dup_a2.id + expect(label_dup_a1.id).to be < label_dup_a3.id + expect(label_dup_b1.id).to be < label_dup_b2.id + expect(label_dup_b1.id).to be < label_dup_b3.id + + # Setup label data for preservation test (different columns) + label_i2 = isolation_segment.create(name: 'label_preserve_test') + label_key_b = 'b' * 63 + label_key_c = 'c' * 63 + + # In case key_prefix is not set + label_pres_a1 = label.create(resource_guid: label_i1.guid, key_name: label_key_b, value: 'v1') + label_pres_a2 = label.create(resource_guid: label_i2.guid, key_name: label_key_b, value: 'v2') + label_pres_a3 = label.create(resource_guid: label_i1.guid, key_name: label_key_c, value: 'v3') + + # In case key_prefix is set + label_pres_b1 = label.create(resource_guid: label_i1.guid, key_prefix: 'prefix1', key_name: label_key_b, value: 'v1') + label_pres_b2 = label.create(resource_guid: label_i2.guid, key_prefix: 'prefix1', key_name: label_key_b, value: 'v2') + label_pres_b3 = label.create(resource_guid: label_i1.guid, key_prefix: 'prefix1', key_name: label_key_c, value: 'v3') + label_pres_b4 = label.create(resource_guid: label_i1.guid, key_prefix: 'prefix2', key_name: label_key_b, value: 'v4') + + # Setup label data for uniqueness constraint test + label_i3 = isolation_segment.create(name: 'label_unique_test') + label_i4 = isolation_segment.create(name: 'label_unique_test2') + label_key_d = 'd' * 63 + label_key_e = 'e' * 63 + + # In case key_prefix is not set + label.create(resource_guid: label_i3.guid, key_name: label_key_d, value: 'v1') + + # In case key_prefix is set + label.create(resource_guid: label_i4.guid, key_prefix: 'unique_prefix', key_name: label_key_d, value: 'v1') + # Run migration once - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + expect { run_migration }.not_to raise_error # Verify truncation behavior expect(trunc_a1.reload.key_name).to eq(truncated_key_name) @@ -82,13 +128,7 @@ expect { dup_b3.reload }.to raise_error(Sequel::NoExistingObject) # Verify preservation of records with different columns - expect(pres_a1.reload).to be_a(annotation) - expect(pres_a2.reload).to be_a(annotation) - expect(pres_a3.reload).to be_a(annotation) - expect(pres_b1.reload).to be_a(annotation) - expect(pres_b2.reload).to be_a(annotation) - expect(pres_b3.reload).to be_a(annotation) - expect(pres_b4.reload).to be_a(annotation) + expect([pres_a1, pres_a2, pres_a3, pres_b1, pres_b2, pres_b3, pres_b4].map(&:reload)).to all(be_a(annotation)) # Verify uniqueness constraints: does not allow adding a duplicate expect { annotation.create(resource_guid: i4.guid, key_name: key_f, value: 'v2') }.to raise_error(Sequel::UniqueConstraintViolation) @@ -100,96 +140,46 @@ uniq_b1 = annotation.create(resource_guid: i4.guid, key_prefix: 'other_prefix', key_name: key_f, value: 'v4') uniq_b2 = annotation.create(resource_guid: i5.guid, key_prefix: 'other_prefix', key_name: key_f, value: 'v5') expect(annotation.where(key_name: key_g).count).to eq(2) - expect(uniq_a1.reload).to be_a(annotation) - expect(uniq_a2.reload).to be_a(annotation) - expect(uniq_b1.reload).to be_a(annotation) - expect(uniq_b2.reload).to be_a(annotation) - end - end - - describe 'labels tables' do - it 'handles duplicate removal and uniqueness constraints' do - # Setup data for duplicate removal test - i1 = isolation_segment.create(name: 'label_dup_test') - key_a = 'a' * 63 - - # In case key_prefix is not set - dup_a1 = label.create(resource_guid: i1.guid, key_name: key_a, value: 'v1') - dup_a2 = label.create(resource_guid: i1.guid, key_name: key_a, value: 'v2') - dup_a3 = label.create(resource_guid: i1.guid, key_name: key_a, value: 'v3') - - # In case key_prefix is set - dup_b1 = label.create(resource_guid: i1.guid, key_prefix: 'bommel', key_name: key_a, value: 'v1') - dup_b2 = label.create(resource_guid: i1.guid, key_prefix: 'bommel', key_name: key_a, value: 'v2') - dup_b3 = label.create(resource_guid: i1.guid, key_prefix: 'bommel', key_name: key_a, value: 'v3') - expect(dup_a1.id).to be < dup_a2.id - expect(dup_a1.id).to be < dup_a3.id - expect(dup_b1.id).to be < dup_b2.id - expect(dup_b1.id).to be < dup_b3.id + expect([uniq_a1, uniq_a2, uniq_b1, uniq_b2].map(&:reload)).to all(be_a(annotation)) - # Setup data for preservation test (different columns) - i2 = isolation_segment.create(name: 'label_preserve_test') - key_b = 'b' * 63 - key_c = 'c' * 63 + # Verify label duplicate removal (keeps smallest id) + expect(label.where(resource_guid: label_i1.guid, key_name: label_key_a).count).to eq(2) + expect(label_dup_a1.reload).to be_a(label) + expect { label_dup_a2.reload }.to raise_error(Sequel::NoExistingObject) + expect { label_dup_a3.reload }.to raise_error(Sequel::NoExistingObject) + expect(label_dup_b1.reload).to be_a(label) + expect { label_dup_b2.reload }.to raise_error(Sequel::NoExistingObject) + expect { label_dup_b3.reload }.to raise_error(Sequel::NoExistingObject) - # In case key_prefix is not set - pres_a1 = label.create(resource_guid: i1.guid, key_name: key_b, value: 'v1') - pres_a2 = label.create(resource_guid: i2.guid, key_name: key_b, value: 'v2') - pres_a3 = label.create(resource_guid: i1.guid, key_name: key_c, value: 'v3') + # Verify preservation of labels with different columns + expect([label_pres_a1, label_pres_a2, label_pres_a3, label_pres_b1, label_pres_b2, label_pres_b3, label_pres_b4].map(&:reload)).to all(be_a(label)) - # In case key_prefix is set - pres_b1 = label.create(resource_guid: i1.guid, key_prefix: 'prefix1', key_name: key_b, value: 'v1') - pres_b2 = label.create(resource_guid: i2.guid, key_prefix: 'prefix1', key_name: key_b, value: 'v2') - pres_b3 = label.create(resource_guid: i1.guid, key_prefix: 'prefix1', key_name: key_c, value: 'v3') - pres_b4 = label.create(resource_guid: i1.guid, key_prefix: 'prefix2', key_name: key_b, value: 'v4') - - # Setup data for uniqueness constraint test - i3 = isolation_segment.create(name: 'label_unique_test') - i4 = isolation_segment.create(name: 'label_unique_test2') - key_d = 'd' * 63 - key_e = 'e' * 63 - - # In case key_prefix is not set - label.create(resource_guid: i3.guid, key_name: key_d, value: 'v1') - - # In case key_prefix is set - label.create(resource_guid: i4.guid, key_prefix: 'unique_prefix', key_name: key_d, value: 'v1') - - # Run migration once - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error - - # Verify duplicate removal (keeps smallest id) - expect(label.where(resource_guid: i1.guid, key_name: key_a).count).to eq(2) - expect(dup_a1.reload).to be_a(label) - expect { dup_a2.reload }.to raise_error(Sequel::NoExistingObject) - expect { dup_a3.reload }.to raise_error(Sequel::NoExistingObject) - expect(dup_b1.reload).to be_a(label) - expect { dup_b2.reload }.to raise_error(Sequel::NoExistingObject) - expect { dup_b3.reload }.to raise_error(Sequel::NoExistingObject) - - # Verify preservation of records with different columns - expect(pres_a1.reload).to be_a(label) - expect(pres_a2.reload).to be_a(label) - expect(pres_a3.reload).to be_a(label) - expect(pres_b1.reload).to be_a(label) - expect(pres_b2.reload).to be_a(label) - expect(pres_b3.reload).to be_a(label) - expect(pres_b4.reload).to be_a(label) - - # Verify uniqueness constraints: does not allow adding a duplicate - expect { label.create(resource_guid: i3.guid, key_name: key_d, value: 'v2') }.to raise_error(Sequel::UniqueConstraintViolation) - expect { label.create(resource_guid: i4.guid, key_prefix: 'unique_prefix', key_name: key_d, value: 'v2') }.to raise_error(Sequel::UniqueConstraintViolation) + # Verify label uniqueness constraints: does not allow adding a duplicate + expect { label.create(resource_guid: label_i3.guid, key_name: label_key_d, value: 'v2') }.to raise_error(Sequel::UniqueConstraintViolation) + expect { label.create(resource_guid: label_i4.guid, key_prefix: 'unique_prefix', key_name: label_key_d, value: 'v2') }.to raise_error(Sequel::UniqueConstraintViolation) # Verify uniqueness constraints: does allow adding different labels - uniq_a1 = label.create(resource_guid: i3.guid, key_name: key_e, value: 'v3') - uniq_a2 = label.create(resource_guid: i4.guid, key_name: key_e, value: 'v2') - uniq_b1 = label.create(resource_guid: i3.guid, key_prefix: 'other_prefix', key_name: key_d, value: 'v4') - uniq_b2 = label.create(resource_guid: i4.guid, key_prefix: 'other_prefix', key_name: key_d, value: 'v5') - expect(label.where(key_name: key_e).count).to eq(2) - expect(uniq_a1.reload).to be_a(label) - expect(uniq_a2.reload).to be_a(label) - expect(uniq_b1.reload).to be_a(label) - expect(uniq_b2.reload).to be_a(label) + label_uniq_a1 = label.create(resource_guid: label_i3.guid, key_name: label_key_e, value: 'v3') + label_uniq_a2 = label.create(resource_guid: label_i4.guid, key_name: label_key_e, value: 'v2') + label_uniq_b1 = label.create(resource_guid: label_i3.guid, key_prefix: 'other_prefix', key_name: label_key_d, value: 'v4') + label_uniq_b2 = label.create(resource_guid: label_i4.guid, key_prefix: 'other_prefix', key_name: label_key_d, value: 'v5') + expect(label.where(key_name: label_key_e).count).to eq(2) + expect([label_uniq_a1, label_uniq_a2, label_uniq_b1, label_uniq_b2].map(&:reload)).to all(be_a(label)) + + # Up migration idempotency - uniqueness constraint still enforced + test_up_migration_idempotency + expect { annotation.create(resource_guid: i4.guid, key_name: key_f, value: 'v6') }.to raise_error(Sequel::UniqueConstraintViolation) + expect { label.create(resource_guid: label_i3.guid, key_name: label_key_d, value: 'v6') }.to raise_error(Sequel::UniqueConstraintViolation) + + # Down migration - uniqueness constraint removed, duplicates allowed again + expect { revert_migration }.not_to raise_error + expect { annotation.create(resource_guid: i4.guid, key_name: key_f, value: 'v7') }.not_to raise_error + expect { label.create(resource_guid: label_i3.guid, key_name: label_key_d, value: 'v7') }.not_to raise_error + + # Down migration idempotency - constraint still absent + test_down_migration_idempotency + expect { annotation.create(resource_guid: i4.guid, key_name: key_f, value: 'v8') }.not_to raise_error + expect { label.create(resource_guid: label_i3.guid, key_name: label_key_d, value: 'v8') }.not_to raise_error end end end diff --git a/spec/migrations/20240115163000_add_delete_cascade_to_foreign_keys_spec.rb b/spec/migrations/20240115163000_add_delete_cascade_to_foreign_keys_spec.rb index 9e0d290847a..c70a6513cb8 100644 --- a/spec/migrations/20240115163000_add_delete_cascade_to_foreign_keys_spec.rb +++ b/spec/migrations/20240115163000_add_delete_cascade_to_foreign_keys_spec.rb @@ -8,6 +8,7 @@ describe 'buildpack_lifecycle_data table' do after do + db[:buildpack_lifecycle_buildpacks].delete db[:buildpack_lifecycle_data].delete db[:builds].delete end @@ -24,7 +25,7 @@ db[:buildpack_lifecycle_data].insert(guid: 'another_bld_guid', build_guid: 'not_exists') db[:buildpack_lifecycle_buildpacks].insert(guid: 'another_blb_guid', buildpack_lifecycle_data_guid: 'another_bld_guid') - Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) + run_migration # After migration: prevents inserts with non-existent build_guid expect { db[:buildpack_lifecycle_data].insert(guid: 'bld_guid_new', build_guid: 'not_exists') }.to raise_error(Sequel::ForeignKeyConstraintViolation) @@ -34,6 +35,24 @@ expect(db[:buildpack_lifecycle_buildpacks].where(guid: 'blb_guid').count).to eq(1) expect(db[:buildpack_lifecycle_data].where(guid: 'another_bld_guid').count).to eq(0) expect(db[:buildpack_lifecycle_buildpacks].where(guid: 'another_blb_guid').count).to eq(0) + + # After migration: deleting a parent cascades to its children + db[:buildpack_lifecycle_data].where(guid: 'bld_guid').delete + expect(db[:buildpack_lifecycle_buildpacks].where(guid: 'blb_guid').count).to eq(0) + + # Up migration idempotency - cascade already added + test_up_migration_idempotency + expect { db[:buildpack_lifecycle_data].insert(guid: 'bld_guid_idem', build_guid: 'not_exists') }.to raise_error(Sequel::ForeignKeyConstraintViolation) + + # Down migration - restores foreign keys without delete cascade + expect { revert_migration }.not_to raise_error + db[:buildpack_lifecycle_data].insert(guid: 'no_cascade_bld_guid', build_guid: 'build_guid') + db[:buildpack_lifecycle_buildpacks].insert(guid: 'no_cascade_blb_guid', buildpack_lifecycle_data_guid: 'no_cascade_bld_guid') + expect { db[:buildpack_lifecycle_data].where(guid: 'no_cascade_bld_guid').delete }.to raise_error(Sequel::ForeignKeyConstraintViolation) + + # Down migration idempotency - cascade already removed + test_down_migration_idempotency + expect { db[:buildpack_lifecycle_data].where(guid: 'no_cascade_bld_guid').delete }.to raise_error(Sequel::ForeignKeyConstraintViolation) end end end diff --git a/spec/migrations/20240219113000_add_routes_space_id_index_spec.rb b/spec/migrations/20240219113000_add_routes_space_id_index_spec.rb index 3c04f8b98f0..4e5a72100c8 100644 --- a/spec/migrations/20240219113000_add_routes_space_id_index_spec.rb +++ b/spec/migrations/20240219113000_add_routes_space_id_index_spec.rb @@ -6,7 +6,22 @@ let(:migration_filename) { '20240219113000_add_routes_space_id_index.rb' } end - it 'succeeds' do - Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) + # The migration body is a no-op on MySQL, so only exercise it on PostgreSQL. + it 'adds and removes the index and is idempotent' do + skip if db.database_type != :postgres + + expect(db.indexes(:routes)).not_to include(:routes_space_id_index) + + expect { run_migration }.not_to raise_error + expect(db.indexes(:routes)).to include(:routes_space_id_index) + + test_up_migration_idempotency + expect(db.indexes(:routes)).to include(:routes_space_id_index) + + expect { revert_migration }.not_to raise_error + expect(db.indexes(:routes)).not_to include(:routes_space_id_index) + + test_down_migration_idempotency + expect(db.indexes(:routes)).not_to include(:routes_space_id_index) end end diff --git a/spec/migrations/20240222131500_change_delayed_jobs_reserve_index_spec.rb b/spec/migrations/20240222131500_change_delayed_jobs_reserve_index_spec.rb index fa0683d7029..f0439eca159 100644 --- a/spec/migrations/20240222131500_change_delayed_jobs_reserve_index_spec.rb +++ b/spec/migrations/20240222131500_change_delayed_jobs_reserve_index_spec.rb @@ -6,7 +6,26 @@ let(:migration_filename) { '20240222131500_change_delayed_jobs_reserve_index.rb' } end - it 'succeeds' do - Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) + def reserve_index_definition + db[:pg_indexes].where(tablename: 'delayed_jobs', indexname: 'delayed_jobs_reserve').get(:indexdef) + end + + # The migration body is a no-op on MySQL, so only exercise it on PostgreSQL. + it 'changes the index and is idempotent' do + skip if db.database_type != :postgres + + expect(reserve_index_definition).to end_with('(queue, locked_at, locked_by, failed_at, run_at, priority)') + + expect { run_migration }.not_to raise_error + expect(reserve_index_definition).to end_with('(queue, locked_at, locked_by, failed_at, run_at, priority) WHERE (failed_at IS NULL)') + + test_up_migration_idempotency + expect(reserve_index_definition).to end_with('(queue, locked_at, locked_by, failed_at, run_at, priority) WHERE (failed_at IS NULL)') + + expect { revert_migration }.not_to raise_error + expect(reserve_index_definition).to end_with('(queue, locked_at, locked_by, failed_at, run_at, priority)') + + test_down_migration_idempotency + expect(reserve_index_definition).to end_with('(queue, locked_at, locked_by, failed_at, run_at, priority)') end end diff --git a/spec/migrations/20240314131908_add_user_guid_to_jobs_table_spec.rb b/spec/migrations/20240314131908_add_user_guid_to_jobs_table_spec.rb index 7fc29acbacd..3067730a526 100644 --- a/spec/migrations/20240314131908_add_user_guid_to_jobs_table_spec.rb +++ b/spec/migrations/20240314131908_add_user_guid_to_jobs_table_spec.rb @@ -12,23 +12,23 @@ expect(db[:jobs].columns).not_to include(:user_guid) expect(db.indexes(:jobs)).not_to include(:jobs_user_guid_index) - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + expect { run_migration }.not_to raise_error expect(db[:jobs].columns).to include(:user_guid) expect(db.indexes(:jobs)).to include(:jobs_user_guid_index) # Test up migration again (both column and index already exist - idempotency) - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency expect(db[:jobs].columns).to include(:user_guid) expect(db.indexes(:jobs)).to include(:jobs_user_guid_index) # Test down migration with pre-dropped index db.drop_index :jobs, :user_guid, name: :jobs_user_guid_index - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + expect { revert_migration }.not_to raise_error expect(db[:jobs].columns).not_to include(:user_guid) expect(db.indexes(:jobs)).not_to include(:jobs_user_guid_index) # Test down migration when both already removed (idempotency) - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + test_down_migration_idempotency expect(db[:jobs].columns).not_to include(:user_guid) expect(db.indexes(:jobs)).not_to include(:jobs_user_guid_index) end diff --git a/spec/migrations/20240529195136_add_task_guid_index_to_app_usage_events_spec.rb b/spec/migrations/20240529195136_add_task_guid_index_to_app_usage_events_spec.rb index 48b1513cd1f..b2e362410b1 100644 --- a/spec/migrations/20240529195136_add_task_guid_index_to_app_usage_events_spec.rb +++ b/spec/migrations/20240529195136_add_task_guid_index_to_app_usage_events_spec.rb @@ -10,19 +10,19 @@ it 'adds and removes index with idempotency' do # Test up migration expect(db.indexes(:app_usage_events)).not_to include(:app_usage_events_task_guid_index) - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + expect { run_migration }.not_to raise_error expect(db.indexes(:app_usage_events)).to include(:app_usage_events_task_guid_index) # Test up migration idempotency: running again when index exists should not fail - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency expect(db.indexes(:app_usage_events)).to include(:app_usage_events_task_guid_index) # Test down migration - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + expect { revert_migration }.not_to raise_error expect(db.indexes(:app_usage_events)).not_to include(:app_usage_events_task_guid_index) # Test down migration idempotency: running rollback again when index doesn't exist should not fail - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + test_down_migration_idempotency expect(db.indexes(:app_usage_events)).not_to include(:app_usage_events_task_guid_index) end end diff --git a/spec/migrations/20240820070742_add_jobs_user_guid_state_index_spec.rb b/spec/migrations/20240820070742_add_jobs_user_guid_state_index_spec.rb index f8601a9ef64..3096ea85fd4 100644 --- a/spec/migrations/20240820070742_add_jobs_user_guid_state_index_spec.rb +++ b/spec/migrations/20240820070742_add_jobs_user_guid_state_index_spec.rb @@ -26,23 +26,23 @@ def partial_index_present expect(db.indexes(:jobs)).to include(:jobs_user_guid_index) expect(partial_index_present).to be_falsey - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + expect { run_migration }.not_to raise_error expect(db.indexes(:jobs)).not_to include(:jobs_user_guid_index) expect(partial_index_present).to be_truthy # Test up migration idempotency: running again when new index exists should not fail - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency expect(db.indexes(:jobs)).not_to include(:jobs_user_guid_index) expect(partial_index_present).to be_truthy # Test down migration - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + expect { revert_migration }.not_to raise_error expect(partial_index_present).to be_falsey expect(db.indexes(:jobs)).to include(:jobs_user_guid_index) # Test down migration idempotency: running again when old index exists should not fail - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + test_down_migration_idempotency expect(partial_index_present).to be_falsey expect(db.indexes(:jobs)).to include(:jobs_user_guid_index) end diff --git a/spec/migrations/20240904132000_add_foreign_key_apps_droplet_guid_spec.rb b/spec/migrations/20240904132000_add_foreign_key_apps_droplet_guid_spec.rb index 1d2940b8673..3b2ccefe4af 100644 --- a/spec/migrations/20240904132000_add_foreign_key_apps_droplet_guid_spec.rb +++ b/spec/migrations/20240904132000_add_foreign_key_apps_droplet_guid_spec.rb @@ -21,7 +21,7 @@ db[:apps].insert(guid: 'app_guid', droplet_guid: 'droplet_guid') db[:apps].insert(guid: 'another_app_guid', droplet_guid: 'not_exists') - Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) + run_migration # After migration: prevents inserts with non-existent droplet_guid expect { db[:apps].insert(guid: 'app_guid_new', droplet_guid: 'not_exists') }.to raise_error(Sequel::ForeignKeyConstraintViolation) @@ -29,6 +29,18 @@ # After migration: invalid references removed, valid ones kept expect(db[:apps].where(guid: 'app_guid').get(:droplet_guid)).to eq('droplet_guid') expect(db[:apps].where(guid: 'another_app_guid').get(:droplet_guid)).to be_nil + + # Up migration idempotency - constraint already added + test_up_migration_idempotency + expect(db.foreign_key_list(:apps).any? { |fk| fk[:name] == :fk_apps_droplet_guid }).to be(true) + + # Down migration - constraint removed + expect { revert_migration }.not_to raise_error + expect(db.foreign_key_list(:apps).any? { |fk| fk[:name] == :fk_apps_droplet_guid }).to be(false) + + # Down migration idempotency - constraint already removed + test_down_migration_idempotency + expect(db.foreign_key_list(:apps).any? { |fk| fk[:name] == :fk_apps_droplet_guid }).to be(false) end end end diff --git a/spec/migrations/20241016118000_drop_unique_constraint_quota_definitions_name_key_spec.rb b/spec/migrations/20241016118000_drop_unique_constraint_quota_definitions_name_key_spec.rb index c3af1f6c70b..81975f9e1e7 100644 --- a/spec/migrations/20241016118000_drop_unique_constraint_quota_definitions_name_key_spec.rb +++ b/spec/migrations/20241016118000_drop_unique_constraint_quota_definitions_name_key_spec.rb @@ -1,4 +1,3 @@ -# rubocop:disable Migration/TooManyMigrationRuns require 'spec_helper' require 'migrations/helpers/migration_shared_context' @@ -6,52 +5,27 @@ include_context 'migration' do let(:migration_filename) { '20241016118000_drop_unique_constraint_quota_definitions_name_key.rb' } end - describe 'quota_definitions table' do - context 'mysql' do - it 'removes and restores unique constraint with idempotency' do - skip if db.database_type != :mysql - - # Test up migration - removes unique constraint - expect(db.indexes(:quota_definitions)).to include(:name) - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error - expect(db.indexes(:quota_definitions)).not_to include(:name) - - # Test up migration idempotency - constraint already removed - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error - expect(db.indexes(:quota_definitions)).not_to include(:name) - - # Test down migration - restores unique constraint - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error - expect(db.indexes(:quota_definitions)).to include(:name) - - # Test down migration idempotency - constraint already exists - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error - expect(db.indexes(:quota_definitions)).to include(:name) - end - end - - context 'postgres' do - it 'removes and restores unique constraint with idempotency' do - skip if db.database_type != :postgres - - # Test up migration - removes unique constraint - expect(db.indexes(:quota_definitions)).to include(:quota_definitions_name_key) - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error - expect(db.indexes(:quota_definitions)).not_to include(:quota_definitions_name_key) - # Test up migration idempotency - constraint already removed - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error - expect(db.indexes(:quota_definitions)).not_to include(:quota_definitions_name_key) + let(:index_name) { db.database_type == :mysql ? :name : :quota_definitions_name_key } - # Test down migration - restores unique constraint - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error - expect(db.indexes(:quota_definitions)).to include(:quota_definitions_name_key) - - # Test down migration idempotency - constraint already exists - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error - expect(db.indexes(:quota_definitions)).to include(:quota_definitions_name_key) - end + describe 'quota_definitions table' do + it 'removes and restores unique constraint with idempotency' do + # Test up migration - removes unique constraint + expect(db.indexes(:quota_definitions)).to include(index_name) + expect { run_migration }.not_to raise_error + expect(db.indexes(:quota_definitions)).not_to include(index_name) + + # Test up migration idempotency - constraint already removed + test_up_migration_idempotency + expect(db.indexes(:quota_definitions)).not_to include(index_name) + + # Test down migration - restores unique constraint + expect { revert_migration }.not_to raise_error + expect(db.indexes(:quota_definitions)).to include(index_name) + + # Test down migration idempotency - constraint already exists + test_down_migration_idempotency + expect(db.indexes(:quota_definitions)).to include(index_name) end end end -# rubocop:enable Migration/TooManyMigrationRuns diff --git a/spec/migrations/20241203085500_add_apps_file_based_service_bindings_enabled_column_spec.rb b/spec/migrations/20241203085500_add_apps_file_based_service_bindings_enabled_column_spec.rb index 8d48828fe0f..f43e4442256 100644 --- a/spec/migrations/20241203085500_add_apps_file_based_service_bindings_enabled_column_spec.rb +++ b/spec/migrations/20241203085500_add_apps_file_based_service_bindings_enabled_column_spec.rb @@ -15,7 +15,7 @@ expect(db[:apps].columns).not_to include(:file_based_service_bindings_enabled) # Run migration - Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) + run_migration # Verify column was added expect(db[:apps].columns).to include(:file_based_service_bindings_enabled) @@ -29,6 +29,10 @@ # Verify null values are forbidden expect { db[:apps].insert(guid: 'app_guid__nil', file_based_service_bindings_enabled: nil) }.to raise_error(Sequel::NotNullConstraintViolation) + + # Down migration + expect { revert_migration }.not_to raise_error + expect(db[:apps].columns).not_to include(:file_based_service_bindings_enabled) end end end diff --git a/spec/migrations/20250116144231_remove_unnecessary_fk_in_job_warnings_spec.rb b/spec/migrations/20250116144231_remove_unnecessary_fk_in_job_warnings_spec.rb index c954f0cb703..f365e9e3447 100644 --- a/spec/migrations/20250116144231_remove_unnecessary_fk_in_job_warnings_spec.rb +++ b/spec/migrations/20250116144231_remove_unnecessary_fk_in_job_warnings_spec.rb @@ -9,13 +9,15 @@ describe 'job_warnings table' do it 'removes the fk constraint and column, handles idempotency' do # Run migration - Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) + run_migration expect(db.foreign_key_list(:job_warnings)).to be_empty expect(db[:job_warnings].columns).not_to include(:fk_jobs_id) # Test idempotency: running again when constraint doesn't exist should not fail - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency + expect(db.foreign_key_list(:job_warnings)).to be_empty + expect(db[:job_warnings].columns).not_to include(:fk_jobs_id) end end end diff --git a/spec/migrations/20250225132929_add_apps_file_based_service_binding_feature_columns_spec.rb b/spec/migrations/20250225132929_add_apps_file_based_service_binding_feature_columns_spec.rb index 436a459aa72..c563321df7f 100644 --- a/spec/migrations/20250225132929_add_apps_file_based_service_binding_feature_columns_spec.rb +++ b/spec/migrations/20250225132929_add_apps_file_based_service_binding_feature_columns_spec.rb @@ -17,7 +17,7 @@ expect(check_constraint_exists?(db)).to be(false) if check_constraint_supported?(db) # === UP MIGRATION === - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + expect { run_migration }.not_to raise_error # Verify both columns were added expect(db[:apps].columns).to include(:service_binding_k8s_enabled) @@ -45,13 +45,13 @@ end # Test up migration idempotency: running migration again should not fail - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency expect(db[:apps].columns).to include(:service_binding_k8s_enabled) expect(db[:apps].columns).to include(:file_based_vcap_services_enabled) expect(check_constraint_exists?(db)).to be(true) if check_constraint_supported?(db) # === DOWN MIGRATION === - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + expect { revert_migration }.not_to raise_error # Verify columns were removed expect(db[:apps].columns).not_to include(:service_binding_k8s_enabled) @@ -59,7 +59,7 @@ expect(check_constraint_exists?(db)).to be(false) # Test down migration idempotency: running rollback again should not fail - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + test_down_migration_idempotency expect(db[:apps].columns).not_to include(:service_binding_k8s_enabled) expect(db[:apps].columns).not_to include(:file_based_vcap_services_enabled) expect(check_constraint_exists?(db)).to be(false) diff --git a/spec/migrations/20250318112800_add_user_id_index_to_roles_tables_spec.rb b/spec/migrations/20250318112800_add_user_id_index_to_roles_tables_spec.rb index 87e7c9c1da5..918c8c6a6a2 100644 --- a/spec/migrations/20250318112800_add_user_id_index_to_roles_tables_spec.rb +++ b/spec/migrations/20250318112800_add_user_id_index_to_roles_tables_spec.rb @@ -33,7 +33,7 @@ end # === UP MIGRATION === - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + expect { run_migration }.not_to raise_error # Verify all indexes were created tables.each do |table| @@ -43,7 +43,7 @@ end # Test up migration idempotency - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency tables.each do |table| table_sym = table.to_sym index_sym = :"#{table}_user_id_index" @@ -51,7 +51,7 @@ end # === DOWN MIGRATION === - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + expect { revert_migration }.not_to raise_error # Verify all indexes were removed tables.each do |table| @@ -61,7 +61,7 @@ end # Test down migration idempotency - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + test_down_migration_idempotency tables.each do |table| table_sym = table.to_sym index_sym = :"#{table}_user_id_index" diff --git a/spec/migrations/20250610212414_add_user_to_processes_spec.rb b/spec/migrations/20250610212414_add_user_to_processes_spec.rb index 6b859a26139..bd15d6074b3 100644 --- a/spec/migrations/20250610212414_add_user_to_processes_spec.rb +++ b/spec/migrations/20250610212414_add_user_to_processes_spec.rb @@ -12,19 +12,19 @@ expect(db[:processes].columns).not_to include(:user) # === UP MIGRATION === - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + expect { run_migration }.not_to raise_error expect(db[:processes].columns).to include(:user) # Test up migration idempotency - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency expect(db[:processes].columns).to include(:user) # === DOWN MIGRATION === - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + expect { revert_migration }.not_to raise_error expect(db[:processes].columns).not_to include(:user) # Test down migration idempotency - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + test_down_migration_idempotency expect(db[:processes].columns).not_to include(:user) end end diff --git a/spec/migrations/20250630170610_add_user_to_tasks_spec.rb b/spec/migrations/20250630170610_add_user_to_tasks_spec.rb index 015487f6a7b..e4d49d10226 100644 --- a/spec/migrations/20250630170610_add_user_to_tasks_spec.rb +++ b/spec/migrations/20250630170610_add_user_to_tasks_spec.rb @@ -12,19 +12,19 @@ expect(db[:tasks].columns).not_to include(:user) # === UP MIGRATION === - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + expect { run_migration }.not_to raise_error expect(db[:tasks].columns).to include(:user) # Test up migration idempotency - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency expect(db[:tasks].columns).to include(:user) # === DOWN MIGRATION === - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + expect { revert_migration }.not_to raise_error expect(db[:tasks].columns).not_to include(:user) # Test down migration idempotency - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + test_down_migration_idempotency expect(db[:tasks].columns).not_to include(:user) end end diff --git a/spec/migrations/20251015071027_allow_multiple_service_bindings_spec.rb b/spec/migrations/20251015071027_allow_multiple_service_bindings_spec.rb index d1a75a4db87..0699c4d274b 100644 --- a/spec/migrations/20251015071027_allow_multiple_service_bindings_spec.rb +++ b/spec/migrations/20251015071027_allow_multiple_service_bindings_spec.rb @@ -15,26 +15,26 @@ expect(db.indexes(:service_bindings)).not_to include(:service_bindings_app_guid_name_index) # === UP MIGRATION === - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + expect { run_migration }.not_to raise_error expect(db.indexes(:service_bindings)).not_to include(:unique_service_binding_app_guid_name) expect(db.indexes(:service_bindings)).not_to include(:unique_service_binding_service_instance_guid_app_guid) expect(db.indexes(:service_bindings)).to include(:service_bindings_app_guid_service_instance_guid_index) expect(db.indexes(:service_bindings)).to include(:service_bindings_app_guid_name_index) # Test up migration idempotency - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency expect(db.indexes(:service_bindings)).to include(:service_bindings_app_guid_service_instance_guid_index) expect(db.indexes(:service_bindings)).to include(:service_bindings_app_guid_name_index) # === DOWN MIGRATION === - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + expect { revert_migration }.not_to raise_error expect(db.indexes(:service_bindings)).to include(:unique_service_binding_service_instance_guid_app_guid) expect(db.indexes(:service_bindings)).to include(:unique_service_binding_app_guid_name) expect(db.indexes(:service_bindings)).not_to include(:service_bindings_app_guid_service_instance_guid_index) expect(db.indexes(:service_bindings)).not_to include(:service_bindings_app_guid_name_index) # Test down migration idempotency - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + test_down_migration_idempotency expect(db.indexes(:service_bindings)).to include(:unique_service_binding_service_instance_guid_app_guid) expect(db.indexes(:service_bindings)).to include(:unique_service_binding_app_guid_name) end diff --git a/spec/migrations/20251016120006_security_groups_spaces_unique_index_spec.rb b/spec/migrations/20251016120006_security_groups_spaces_unique_index_spec.rb index 0528a5dd2f2..78c58161cb8 100644 --- a/spec/migrations/20251016120006_security_groups_spaces_unique_index_spec.rb +++ b/spec/migrations/20251016120006_security_groups_spaces_unique_index_spec.rb @@ -3,7 +3,7 @@ RSpec.describe 'security groups spaces unique index', isolation: :truncation, type: :migration do include_context 'migration' do - let(:migration_filename) { '20251016120006_security_groups_spaces_unique_index_spec.rb' } + let(:migration_filename) { '20251016120006_security_groups_spaces_unique_index.rb' } end let(:space_1) { create(:space) } @@ -33,7 +33,7 @@ expect(db[:security_groups_spaces].where(security_group_id: sec_group_2.id, space_id: space_2.id).count).to eq(3) # === UP MIGRATION === - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + expect { run_migration }.not_to raise_error # Verify duplicates are removed after migration expect(db[:security_groups_spaces].where(security_group_id: sec_group_1.id, space_id: space_1.id).count).to eq(1) @@ -46,16 +46,16 @@ expect(db.indexes(:security_groups_spaces)).to include(:security_groups_spaces_ids) # Test up migration idempotency - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency expect(db.indexes(:security_groups_spaces)).to include(:security_groups_spaces_ids) # === DOWN MIGRATION === - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + expect { revert_migration }.not_to raise_error expect(db.indexes(:security_groups_spaces)).to include(:sgs_spaces_ids) expect(db.indexes(:security_groups_spaces)).not_to include(:security_groups_spaces_ids) # Test down migration idempotency - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + test_down_migration_idempotency expect(db.indexes(:security_groups_spaces)).to include(:sgs_spaces_ids) expect(db.indexes(:security_groups_spaces)).not_to include(:security_groups_spaces_ids) end diff --git a/spec/migrations/20251028135214_route_bindings_unique_index_spec.rb b/spec/migrations/20251028135214_route_bindings_unique_index_spec.rb index dc6dedef54b..97de204ff61 100644 --- a/spec/migrations/20251028135214_route_bindings_unique_index_spec.rb +++ b/spec/migrations/20251028135214_route_bindings_unique_index_spec.rb @@ -33,7 +33,7 @@ expect(db[:route_bindings].where(service_instance_id: service_instance_2.id, route_id: route_2.id).count).to eq(3) # === UP MIGRATION === - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + expect { run_migration }.not_to raise_error # Verify duplicates are removed after migration expect(db[:route_bindings].where(service_instance_id: service_instance_1.id, route_id: route_1.id).count).to eq(1) @@ -45,16 +45,16 @@ expect(db.indexes(:route_bindings)).to include(:route_bindings_route_id_service_instance_id_index) # Test up migration idempotency - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency expect(db.indexes(:route_bindings)).to include(:route_bindings_route_id_service_instance_id_index) # === DOWN MIGRATION === - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + expect { revert_migration }.not_to raise_error expect(db.indexes(:route_bindings)).not_to include(:route_bindings_route_id_service_instance_id_index) expect(db.indexes(:route_bindings)).to include(:route_id) if db.database_type == :mysql # Test down migration idempotency - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + test_down_migration_idempotency expect(db.indexes(:route_bindings)).not_to include(:route_bindings_route_id_service_instance_id_index) end end diff --git a/spec/migrations/20251030100000_add_unique_constraint_to_sidecar_process_types_spec.rb b/spec/migrations/20251030100000_add_unique_constraint_to_sidecar_process_types_spec.rb index 1186fe84586..e11f0339c86 100644 --- a/spec/migrations/20251030100000_add_unique_constraint_to_sidecar_process_types_spec.rb +++ b/spec/migrations/20251030100000_add_unique_constraint_to_sidecar_process_types_spec.rb @@ -31,7 +31,7 @@ # ========================================================================================= # UP MIGRATION: Run the migration to apply the unique constraints. # ========================================================================================= - Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) + run_migration # ========================================================================================= # ASSERT UP MIGRATION: Verify that duplicates are removed and constraints are enforced. @@ -47,12 +47,14 @@ # ========================================================================================= # TEST IDEMPOTENCY: Running the migration again should not cause any errors. # ========================================================================================= - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency + expect(db.indexes(:sidecar_process_types)).to include(:sidecar_process_types_sidecar_guid_type_index) + expect(db.indexes(:revision_sidecar_process_types)).to include(:revision_sidecar_process_types_revision_sidecar_guid_type_index) # ========================================================================================= # DOWN MIGRATION: Roll back the migration to remove the constraints. # ========================================================================================= - Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) + revert_migration # ========================================================================================= # ASSERT DOWN MIGRATION: Verify that constraints are removed and duplicates can be re-inserted. @@ -62,5 +64,12 @@ expect(db.indexes(:revision_sidecar_process_types)).not_to include(:revision_sidecar_process_types_revision_sidecar_guid_type_index) expect { db[:revision_sidecar_process_types].insert(revision_sidecar_guid: revision_sidecar_guid, type: 'worker', guid: SecureRandom.uuid) }.not_to raise_error + + # ========================================================================================= + # TEST IDEMPOTENCY: Running the rollback again should not cause any errors. + # ========================================================================================= + test_down_migration_idempotency + expect(db.indexes(:sidecar_process_types)).not_to include(:sidecar_process_types_sidecar_guid_type_index) + expect(db.indexes(:revision_sidecar_process_types)).not_to include(:revision_sidecar_process_types_revision_sidecar_guid_type_index) end end diff --git a/spec/migrations/20251117123719_add_state_to_stacks_spec.rb b/spec/migrations/20251117123719_add_state_to_stacks_spec.rb index 504ad77ba9c..4f8ff3ce4a4 100644 --- a/spec/migrations/20251117123719_add_state_to_stacks_spec.rb +++ b/spec/migrations/20251117123719_add_state_to_stacks_spec.rb @@ -2,8 +2,6 @@ require 'migrations/helpers/migration_shared_context' RSpec.describe 'migration to add state column to stacks table', isolation: :truncation, type: :migration do - subject(:run_migration) { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) } - include_context 'migration' do let(:migration_filename) { '20251117123719_add_state_to_stacks.rb' } end @@ -33,14 +31,20 @@ end # Verify UP is idempotent - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency + expect(db[:stacks].columns).to include(:state) + expect(db[:stacks].first(name: 'existing-stack')[:state]).to eq('ACTIVE') + expect(db[:stacks].first(name: 'new-stack')[:state]).to eq('ACTIVE') + %w[DEPRECATED RESTRICTED DISABLED].each do |state| + expect(db[:stacks].first(name: "stack-#{state.downcase}")[:state]).to eq(state) + end # Run migration DOWN - Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) + revert_migration expect(db[:stacks].columns).not_to include(:state) # Verify DOWN is idempotent - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + test_down_migration_idempotency expect(db[:stacks].columns).not_to include(:state) end end diff --git a/spec/migrations/20251121174647_add_broker_provided_metadata_to_service_instances_spec.rb b/spec/migrations/20251121174647_add_broker_provided_metadata_to_service_instances_spec.rb index da70615cb4d..bbb0faac116 100644 --- a/spec/migrations/20251121174647_add_broker_provided_metadata_to_service_instances_spec.rb +++ b/spec/migrations/20251121174647_add_broker_provided_metadata_to_service_instances_spec.rb @@ -26,7 +26,7 @@ expect(db[:service_instances].columns).not_to include(:broker_provided_metadata) # Run migration - Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) + run_migration # Verify column was added expect(db[:service_instances].columns).to include(:broker_provided_metadata) @@ -56,6 +56,10 @@ ) instance_with_metadata = db[:service_instances].first(guid: 'test-service-instance-with-metadata') expect(instance_with_metadata[:broker_provided_metadata]).to eq(metadata_json) + + # Down migration + expect { revert_migration }.not_to raise_error + expect(db[:service_instances].columns).not_to include(:broker_provided_metadata) end end end diff --git a/spec/migrations/20260318083940_add_unique_constraint_to_buildpacks_spec.rb b/spec/migrations/20260318083940_add_unique_constraint_to_buildpacks_spec.rb index 2347f8b1b59..1ddbd8967ce 100644 --- a/spec/migrations/20260318083940_add_unique_constraint_to_buildpacks_spec.rb +++ b/spec/migrations/20260318083940_add_unique_constraint_to_buildpacks_spec.rb @@ -32,7 +32,7 @@ db[:buildpack_labels].insert(guid: SecureRandom.uuid, resource_guid: duplicate_guid, key_name: 'team', value: 'b') # run the migration - Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) + run_migration # Verify duplicates are removed, keeping one per (name, stack, lifecycle) expect(db[:buildpacks].where(name: 'ruby', stack: 'cflinuxfs3', lifecycle: 'buildpack').count).to eq(1) @@ -51,14 +51,16 @@ expect(db.indexes(:buildpacks)).to include(:buildpacks_name_stack_lifecycle_index) # Test up migration idempotency - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency + expect(db.indexes(:buildpacks)).not_to include(:unique_name_and_stack) + expect(db.indexes(:buildpacks)).to include(:buildpacks_name_stack_lifecycle_index) # First remove test data that would conflict with the old (name, stack) unique index db[:buildpack_annotations].delete db[:buildpack_labels].delete db[:buildpacks].delete - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + expect { revert_migration }.not_to raise_error # Verify new index is dropped and old index is restored expect(db.indexes(:buildpacks)).not_to include(:buildpacks_name_stack_lifecycle_index) @@ -72,7 +74,7 @@ db[:buildpacks].delete # Test down migration idempotency - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + test_down_migration_idempotency expect(db.indexes(:buildpacks)).not_to include(:buildpacks_name_stack_lifecycle_index) end end diff --git a/spec/migrations/20260320141005_add_unique_constraint_to_revision_sidecars_spec.rb b/spec/migrations/20260320141005_add_unique_constraint_to_revision_sidecars_spec.rb index cf427949f09..51a14de2e9a 100644 --- a/spec/migrations/20260320141005_add_unique_constraint_to_revision_sidecars_spec.rb +++ b/spec/migrations/20260320141005_add_unique_constraint_to_revision_sidecars_spec.rb @@ -18,7 +18,7 @@ expect(db[:revision_sidecars].where(name: 'app', revision_guid: revision_guid).count).to eq(2) # run the migration - Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) + run_migration # verify duplicates are removed and constraint is enforced expect(db[:revision_sidecars].where(name: 'app', revision_guid: revision_guid).count).to eq(1) @@ -26,13 +26,19 @@ expect { db[:revision_sidecars].insert(guid: SecureRandom.uuid, name: 'app', command: 'command', revision_guid: revision_guid) }.to raise_error(Sequel::UniqueConstraintViolation) # running the migration again should not cause any errors - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency + expect(db[:revision_sidecars].where(name: 'app', revision_guid: revision_guid).count).to eq(1) + expect(db.indexes(:revision_sidecars)).to include(:revision_sidecars_revision_guid_name_index) # roll back the migration - Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) + revert_migration # verify constraint is removed and duplicates can be re-inserted expect(db.indexes(:revision_sidecars)).not_to include(:revision_sidecars_revision_guid_name_index) expect { db[:revision_sidecars].insert(guid: SecureRandom.uuid, name: 'app', command: 'command', revision_guid: revision_guid) }.not_to raise_error + + # rolling back the migration again should not cause any errors + test_down_migration_idempotency + expect(db.indexes(:revision_sidecars)).not_to include(:revision_sidecars_revision_guid_name_index) end end diff --git a/spec/migrations/20260323092954_add_unique_constraint_to_sidecars_spec.rb b/spec/migrations/20260323092954_add_unique_constraint_to_sidecars_spec.rb index cbc84da70db..7813089c8d7 100644 --- a/spec/migrations/20260323092954_add_unique_constraint_to_sidecars_spec.rb +++ b/spec/migrations/20260323092954_add_unique_constraint_to_sidecars_spec.rb @@ -16,7 +16,7 @@ expect(db[:sidecars].where(name: 'app', app_guid: app_guid).count).to eq(2) # run the migration - Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) + run_migration # verify duplicates are removed and constraint is enforced expect(db[:sidecars].where(name: 'app', app_guid: app_guid).count).to eq(1) @@ -24,13 +24,19 @@ expect { db[:sidecars].insert(guid: SecureRandom.uuid, name: 'app', command: 'command', app_guid: app_guid) }.to raise_error(Sequel::UniqueConstraintViolation) # running the migration again should not cause any errors - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency + expect(db[:sidecars].where(name: 'app', app_guid: app_guid).count).to eq(1) + expect(db.indexes(:sidecars)).to include(:sidecars_app_guid_name_index) # roll back the migration - Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) + revert_migration # verify constraint is removed and duplicates can be re-inserted expect(db.indexes(:sidecars)).not_to include(:sidecars_app_guid_name_index) expect { db[:sidecars].insert(guid: SecureRandom.uuid, name: 'app', command: 'command', app_guid: app_guid) }.not_to raise_error + + # rolling back the migration again should not cause any errors + test_down_migration_idempotency + expect(db.indexes(:sidecars)).not_to include(:sidecars_app_guid_name_index) end end diff --git a/spec/migrations/20260323130619_add_unique_constraint_to_security_groups_spec.rb b/spec/migrations/20260323130619_add_unique_constraint_to_security_groups_spec.rb index 6385ef80ba0..597b848a1e8 100644 --- a/spec/migrations/20260323130619_add_unique_constraint_to_security_groups_spec.rb +++ b/spec/migrations/20260323130619_add_unique_constraint_to_security_groups_spec.rb @@ -20,7 +20,7 @@ db[:staging_security_groups_spaces].insert(staging_security_group_id: duplicate_id, staging_space_id: space.id) # run the migration - Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) + run_migration # verify duplicates and their join table references are removed, surviving group intact expect(db[:security_groups].where(name: 'sec1').count).to eq(1) @@ -35,14 +35,24 @@ expect { db[:security_groups].insert(guid: SecureRandom.uuid, name: 'sec1') }.to raise_error(Sequel::UniqueConstraintViolation) # running the migration again should not cause any errors - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency + expect(db[:security_groups].where(name: 'sec1').count).to eq(1) + expect(db[:security_groups].where(name: 'sec1').first[:id]).to eq(surviving_id) + expect(db[:security_groups_spaces].where(security_group_id: surviving_id, space_id: space.id).count).to eq(1) + expect(db[:staging_security_groups_spaces].where(staging_security_group_id: surviving_id, staging_space_id: space.id).count).to eq(1) + expect(db.indexes(:security_groups)).to include(:security_groups_name_index) # roll back the migration - Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) + revert_migration # verify constraint is removed and duplicates can be re-inserted expect(db.indexes(:security_groups)).not_to include(:security_groups_name_index) expect(db.indexes(:security_groups)).to include(:sg_name_index) expect { db[:security_groups].insert(guid: SecureRandom.uuid, name: 'sec1') }.not_to raise_error + + # rolling back the migration again should not cause any errors + test_down_migration_idempotency + expect(db.indexes(:security_groups)).not_to include(:security_groups_name_index) + expect(db.indexes(:security_groups)).to include(:sg_name_index) end end diff --git a/spec/migrations/20260323144429_add_unique_constraint_to_revision_process_commands_spec.rb b/spec/migrations/20260323144429_add_unique_constraint_to_revision_process_commands_spec.rb index ae49122ee66..3a676235524 100644 --- a/spec/migrations/20260323144429_add_unique_constraint_to_revision_process_commands_spec.rb +++ b/spec/migrations/20260323144429_add_unique_constraint_to_revision_process_commands_spec.rb @@ -19,7 +19,7 @@ expect(db[:revision_process_commands].where(revision_guid: revision_guid, process_type: 'worker').count).to eq(2) # run the migration - Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) + run_migration # verify duplicates are removed and constraint is enforced expect(db[:revision_process_commands].where(revision_guid: revision_guid, process_type: 'worker').count).to eq(1) @@ -29,15 +29,21 @@ end.to raise_error(Sequel::UniqueConstraintViolation) # running the migration again should not cause any errors - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency + expect(db[:revision_process_commands].where(revision_guid: revision_guid, process_type: 'worker').count).to eq(1) + expect(db.indexes(:revision_process_commands)).to include(:revision_process_commands_revision_guid_process_type_index) # roll back the migration - Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) + revert_migration # verify constraint is removed and duplicates can be re-inserted expect(db.indexes(:revision_process_commands)).not_to include(:revision_process_commands_revision_guid_process_type_index) expect do db[:revision_process_commands].insert(guid: SecureRandom.uuid, revision_guid: revision_guid, process_type: 'worker') end.not_to raise_error + + # rolling back the migration again should not cause any errors + test_down_migration_idempotency + expect(db.indexes(:revision_process_commands)).not_to include(:revision_process_commands_revision_guid_process_type_index) end end diff --git a/spec/migrations/20260324120000_add_composite_indexes_to_events_spec.rb b/spec/migrations/20260324120000_add_composite_indexes_to_events_spec.rb index a2c39d58799..1cfb42290b7 100644 --- a/spec/migrations/20260324120000_add_composite_indexes_to_events_spec.rb +++ b/spec/migrations/20260324120000_add_composite_indexes_to_events_spec.rb @@ -14,7 +14,7 @@ expect(db.indexes(:events)).not_to include(:events_organization_guid_created_at_guid_index) # Test up migration - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + expect { run_migration }.not_to raise_error expect(db.indexes(:events)).to include(:events_actee_created_at_guid_index) expect(db.indexes(:events)).to include(:events_space_guid_created_at_guid_index) @@ -26,19 +26,19 @@ expect(db.indexes(:events)[:events_organization_guid_created_at_guid_index][:columns]).to eq(%i[organization_guid created_at guid]) # Test up migration idempotency: running again should not fail - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency expect(db.indexes(:events)).to include(:events_actee_created_at_guid_index) expect(db.indexes(:events)).to include(:events_space_guid_created_at_guid_index) expect(db.indexes(:events)).to include(:events_organization_guid_created_at_guid_index) # Test down migration - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + expect { revert_migration }.not_to raise_error expect(db.indexes(:events)).not_to include(:events_actee_created_at_guid_index) expect(db.indexes(:events)).not_to include(:events_space_guid_created_at_guid_index) expect(db.indexes(:events)).not_to include(:events_organization_guid_created_at_guid_index) # Test down migration idempotency: running again should not fail - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + test_down_migration_idempotency expect(db.indexes(:events)).not_to include(:events_actee_created_at_guid_index) expect(db.indexes(:events)).not_to include(:events_space_guid_created_at_guid_index) expect(db.indexes(:events)).not_to include(:events_organization_guid_created_at_guid_index) diff --git a/spec/migrations/20260428120000_add_lifecycle_type_to_apps_spec.rb b/spec/migrations/20260428120000_add_lifecycle_type_to_apps_spec.rb index c806949c85e..b61f524f607 100644 --- a/spec/migrations/20260428120000_add_lifecycle_type_to_apps_spec.rb +++ b/spec/migrations/20260428120000_add_lifecycle_type_to_apps_spec.rb @@ -11,7 +11,7 @@ expect(db.indexes(:apps)).not_to have_key(:apps_lifecycle_type_index) # up - Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) + run_migration expect(db.schema(:apps).map(&:first)).to include(:lifecycle_type) expect(db.indexes(:apps)).to have_key(:apps_lifecycle_type_index) @@ -21,15 +21,20 @@ expect(lifecycle_type_column[1][:allow_null]).to be true # up is idempotent - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency + expect(db.schema(:apps).map(&:first)).to include(:lifecycle_type) + expect(db.indexes(:apps)[:apps_lifecycle_type_index][:columns]).to eq([:lifecycle_type]) + expect(db.schema(:apps).find { |col| col[0] == :lifecycle_type }[1][:allow_null]).to be true # down - Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) + revert_migration expect(db.schema(:apps).map(&:first)).not_to include(:lifecycle_type) expect(db.indexes(:apps)).not_to have_key(:apps_lifecycle_type_index) # down is idempotent - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + test_down_migration_idempotency + expect(db.schema(:apps).map(&:first)).not_to include(:lifecycle_type) + expect(db.indexes(:apps)).not_to have_key(:apps_lifecycle_type_index) end end diff --git a/spec/migrations/20260428120100_add_lifecycle_type_to_droplets_spec.rb b/spec/migrations/20260428120100_add_lifecycle_type_to_droplets_spec.rb index 1b944ac2548..29f797a0d3c 100644 --- a/spec/migrations/20260428120100_add_lifecycle_type_to_droplets_spec.rb +++ b/spec/migrations/20260428120100_add_lifecycle_type_to_droplets_spec.rb @@ -11,7 +11,7 @@ expect(db.indexes(:droplets)).not_to have_key(:droplets_lifecycle_type_index) # up - Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) + run_migration expect(db.schema(:droplets).map(&:first)).to include(:lifecycle_type) expect(db.indexes(:droplets)).to have_key(:droplets_lifecycle_type_index) @@ -21,15 +21,20 @@ expect(lifecycle_type_column[1][:allow_null]).to be true # up is idempotent - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency + expect(db.schema(:droplets).map(&:first)).to include(:lifecycle_type) + expect(db.indexes(:droplets)[:droplets_lifecycle_type_index][:columns]).to eq([:lifecycle_type]) + expect(db.schema(:droplets).find { |col| col[0] == :lifecycle_type }[1][:allow_null]).to be true # down - Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) + revert_migration expect(db.schema(:droplets).map(&:first)).not_to include(:lifecycle_type) expect(db.indexes(:droplets)).not_to have_key(:droplets_lifecycle_type_index) # down is idempotent - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + test_down_migration_idempotency + expect(db.schema(:droplets).map(&:first)).not_to include(:lifecycle_type) + expect(db.indexes(:droplets)).not_to have_key(:droplets_lifecycle_type_index) end end diff --git a/spec/migrations/20260428120200_add_lifecycle_type_to_builds_spec.rb b/spec/migrations/20260428120200_add_lifecycle_type_to_builds_spec.rb index a0834c24784..b7a8917d47c 100644 --- a/spec/migrations/20260428120200_add_lifecycle_type_to_builds_spec.rb +++ b/spec/migrations/20260428120200_add_lifecycle_type_to_builds_spec.rb @@ -11,7 +11,7 @@ expect(db.indexes(:builds)).not_to have_key(:builds_lifecycle_type_index) # up - Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) + run_migration expect(db.schema(:builds).map(&:first)).to include(:lifecycle_type) expect(db.indexes(:builds)).to have_key(:builds_lifecycle_type_index) @@ -21,15 +21,20 @@ expect(lifecycle_type_column[1][:allow_null]).to be true # up is idempotent - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency + expect(db.schema(:builds).map(&:first)).to include(:lifecycle_type) + expect(db.indexes(:builds)[:builds_lifecycle_type_index][:columns]).to eq([:lifecycle_type]) + expect(db.schema(:builds).find { |col| col[0] == :lifecycle_type }[1][:allow_null]).to be true # down - Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) + revert_migration expect(db.schema(:builds).map(&:first)).not_to include(:lifecycle_type) expect(db.indexes(:builds)).not_to have_key(:builds_lifecycle_type_index) # down is idempotent - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + test_down_migration_idempotency + expect(db.schema(:builds).map(&:first)).not_to include(:lifecycle_type) + expect(db.indexes(:builds)).not_to have_key(:builds_lifecycle_type_index) end end diff --git a/spec/migrations/20260505071445_add_jobs_operation_state_index_spec.rb b/spec/migrations/20260505071445_add_jobs_operation_state_index_spec.rb index 162c1e51b00..fd2dfd37e95 100644 --- a/spec/migrations/20260505071445_add_jobs_operation_state_index_spec.rb +++ b/spec/migrations/20260505071445_add_jobs_operation_state_index_spec.rb @@ -18,19 +18,17 @@ def operation_state_index_present? it 'adds index and handles idempotency gracefully' do # Test up migration expect(operation_state_index_present?).to be_falsey - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + expect { run_migration }.not_to raise_error expect(operation_state_index_present?).to be_truthy - # Test up migration idempotency - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency expect(operation_state_index_present?).to be_truthy # Test down migration - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + expect { revert_migration }.not_to raise_error expect(operation_state_index_present?).to be_falsey - # Test down migration idempotency - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + test_down_migration_idempotency expect(operation_state_index_present?).to be_falsey end end diff --git a/spec/migrations/20260630120000_add_status_to_spaces_spec.rb b/spec/migrations/20260630120000_add_status_to_spaces_spec.rb index c339fd087fd..70a6a48d8b6 100644 --- a/spec/migrations/20260630120000_add_status_to_spaces_spec.rb +++ b/spec/migrations/20260630120000_add_status_to_spaces_spec.rb @@ -21,7 +21,7 @@ expect(db[:spaces].columns).not_to include(:status) - Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) + run_migration expect(db[:spaces].columns).to include(:status) @@ -30,16 +30,16 @@ db[:spaces].insert(guid: 'new-space-guid', name: 'new-space', organization_id: org_id) expect(db[:spaces].first(guid: 'new-space-guid')[:status]).to eq('active') - expect do - Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) - end.not_to raise_error + test_up_migration_idempotency + expect(db[:spaces].columns).to include(:status) + expect(db[:spaces].first(guid: 'existing-space-guid')[:status]).to eq('active') + expect(db[:spaces].first(guid: 'new-space-guid')[:status]).to eq('active') - Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) + revert_migration expect(db[:spaces].columns).not_to include(:status) - expect do - Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) - end.not_to raise_error + test_down_migration_idempotency + expect(db[:spaces].columns).not_to include(:status) end end end diff --git a/spec/migrations/20260811120000_add_root_job_guid_to_jobs_spec.rb b/spec/migrations/20260811120000_add_root_job_guid_to_jobs_spec.rb index d82aa96ad6d..ab3bd049276 100644 --- a/spec/migrations/20260811120000_add_root_job_guid_to_jobs_spec.rb +++ b/spec/migrations/20260811120000_add_root_job_guid_to_jobs_spec.rb @@ -10,19 +10,19 @@ it 'adds column and index, and handles idempotency gracefully' do expect(db[:jobs].columns).not_to include(:root_job_guid) expect(db.indexes(:jobs)).not_to be_key(:jobs_root_job_guid_index) - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + expect { run_migration }.not_to raise_error expect(db[:jobs].columns).to include(:root_job_guid) expect(db.indexes(:jobs)).to be_key(:jobs_root_job_guid_index) - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency expect(db[:jobs].columns).to include(:root_job_guid) expect(db.indexes(:jobs)).to be_key(:jobs_root_job_guid_index) - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + expect { revert_migration }.not_to raise_error expect(db[:jobs].columns).not_to include(:root_job_guid) expect(db.indexes(:jobs)).not_to be_key(:jobs_root_job_guid_index) - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + test_down_migration_idempotency expect(db[:jobs].columns).not_to include(:root_job_guid) expect(db.indexes(:jobs)).not_to be_key(:jobs_root_job_guid_index) end diff --git a/spec/migrations/20260825120000_backfill_lifecycle_type_spec.rb b/spec/migrations/20260825120000_backfill_lifecycle_type_spec.rb index 2547b82ba48..3232d832c21 100644 --- a/spec/migrations/20260825120000_backfill_lifecycle_type_spec.rb +++ b/spec/migrations/20260825120000_backfill_lifecycle_type_spec.rb @@ -36,7 +36,7 @@ end it 'backfills lifecycle_type for apps, droplets, and builds, does not overwrite existing values, and prefers buildpack over cnb' do - Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) + run_migration expect(db[:apps].first(guid: 'buildpack-app-guid')[:lifecycle_type]).to eq('buildpack') expect(db[:apps].first(guid: 'cnb-app-guid')[:lifecycle_type]).to eq('cnb') @@ -52,6 +52,20 @@ expect(db[:builds].first(guid: 'cnb-build-guid')[:lifecycle_type]).to eq('cnb') expect(db[:builds].first(guid: 'docker-build-guid')[:lifecycle_type]).to eq('docker') - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency + + expect(db[:apps].first(guid: 'buildpack-app-guid')[:lifecycle_type]).to eq('buildpack') + expect(db[:apps].first(guid: 'cnb-app-guid')[:lifecycle_type]).to eq('cnb') + expect(db[:apps].first(guid: 'docker-app-guid')[:lifecycle_type]).to eq('docker') + expect(db[:apps].first(guid: 'already-set-guid')[:lifecycle_type]).to eq('docker') + expect(db[:apps].first(guid: 'both-app-guid')[:lifecycle_type]).to eq('buildpack') + + expect(db[:droplets].first(guid: 'buildpack-droplet-guid')[:lifecycle_type]).to eq('buildpack') + expect(db[:droplets].first(guid: 'cnb-droplet-guid')[:lifecycle_type]).to eq('cnb') + expect(db[:droplets].first(guid: 'docker-droplet-guid')[:lifecycle_type]).to eq('docker') + + expect(db[:builds].first(guid: 'buildpack-build-guid')[:lifecycle_type]).to eq('buildpack') + expect(db[:builds].first(guid: 'cnb-build-guid')[:lifecycle_type]).to eq('cnb') + expect(db[:builds].first(guid: 'docker-build-guid')[:lifecycle_type]).to eq('docker') end end diff --git a/spec/migrations/20260825120100_make_lifecycle_type_non_nullable_spec.rb b/spec/migrations/20260825120100_make_lifecycle_type_non_nullable_spec.rb index fb87344af29..3463fb43172 100644 --- a/spec/migrations/20260825120100_make_lifecycle_type_non_nullable_spec.rb +++ b/spec/migrations/20260825120100_make_lifecycle_type_non_nullable_spec.rb @@ -13,16 +13,24 @@ end it 'makes lifecycle_type non-nullable, is reversible, and is idempotent' do - Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) + run_migration expect(db.schema(:apps).find { |col| col[0] == :lifecycle_type }[1][:allow_null]).to be false expect(db.schema(:droplets).find { |col| col[0] == :lifecycle_type }[1][:allow_null]).to be false expect(db.schema(:builds).find { |col| col[0] == :lifecycle_type }[1][:allow_null]).to be false - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + test_up_migration_idempotency + expect(db.schema(:apps).find { |col| col[0] == :lifecycle_type }[1][:allow_null]).to be false + expect(db.schema(:droplets).find { |col| col[0] == :lifecycle_type }[1][:allow_null]).to be false + expect(db.schema(:builds).find { |col| col[0] == :lifecycle_type }[1][:allow_null]).to be false + + revert_migration - Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) + expect(db.schema(:apps).find { |col| col[0] == :lifecycle_type }[1][:allow_null]).to be true + expect(db.schema(:droplets).find { |col| col[0] == :lifecycle_type }[1][:allow_null]).to be true + expect(db.schema(:builds).find { |col| col[0] == :lifecycle_type }[1][:allow_null]).to be true + test_down_migration_idempotency expect(db.schema(:apps).find { |col| col[0] == :lifecycle_type }[1][:allow_null]).to be true expect(db.schema(:droplets).find { |col| col[0] == :lifecycle_type }[1][:allow_null]).to be true expect(db.schema(:builds).find { |col| col[0] == :lifecycle_type }[1][:allow_null]).to be true diff --git a/spec/migrations/20261001120000_add_buildpack_lifecycle_credentials_spec.rb b/spec/migrations/20261001120000_add_buildpack_lifecycle_credentials_spec.rb index 69ae5b27284..76d83b4b169 100644 --- a/spec/migrations/20261001120000_add_buildpack_lifecycle_credentials_spec.rb +++ b/spec/migrations/20261001120000_add_buildpack_lifecycle_credentials_spec.rb @@ -7,30 +7,33 @@ end describe 'buildpack_lifecycle_data table' do - it 'adds and removes credential columns, handling idempotency gracefully' do + it 'adds and removes credential columns' do # Before migration: columns must not exist expect(db[:buildpack_lifecycle_data].columns).not_to include(:encrypted_credentials_json) expect(db[:buildpack_lifecycle_data].columns).not_to include(:encrypted_credentials_json_salt) # Run up migration - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + expect { run_migration }.not_to raise_error expect(db[:buildpack_lifecycle_data].columns).to include(:encrypted_credentials_json) expect(db[:buildpack_lifecycle_data].columns).to include(:encrypted_credentials_json_salt) - # Run up again - idempotent due to if_not_exists - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error - expect(db[:buildpack_lifecycle_data].columns).to include(:encrypted_credentials_json) - expect(db[:buildpack_lifecycle_data].columns).to include(:encrypted_credentials_json_salt) + # if_not_exists:/if_exists: are only honoured on PostgreSQL. + if db.database_type == :postgres + test_up_migration_idempotency + expect(db[:buildpack_lifecycle_data].columns).to include(:encrypted_credentials_json) + expect(db[:buildpack_lifecycle_data].columns).to include(:encrypted_credentials_json_salt) + end # Run down migration - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error + expect { revert_migration }.not_to raise_error expect(db[:buildpack_lifecycle_data].columns).not_to include(:encrypted_credentials_json) expect(db[:buildpack_lifecycle_data].columns).not_to include(:encrypted_credentials_json_salt) - # Run down again - idempotent due to if_exists - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) }.not_to raise_error - expect(db[:buildpack_lifecycle_data].columns).not_to include(:encrypted_credentials_json) - expect(db[:buildpack_lifecycle_data].columns).not_to include(:encrypted_credentials_json_salt) + if db.database_type == :postgres + test_down_migration_idempotency + expect(db[:buildpack_lifecycle_data].columns).not_to include(:encrypted_credentials_json) + expect(db[:buildpack_lifecycle_data].columns).not_to include(:encrypted_credentials_json_salt) + end end end end diff --git a/spec/migrations/Readme.md b/spec/migrations/Readme.md index 22693090e8a..552a31d42fe 100644 --- a/spec/migrations/Readme.md +++ b/spec/migrations/Readme.md @@ -82,10 +82,22 @@ Sequel migration tests have a distinct operation compared to conventional RSpec 1. **Shared Context**: It's recommended to use the `migration` shared context, as it ensures that the database schema first reverts to the version before the migration you aim to test. This shared context also provides a directory containing a single migration for running a particular migration within a test. When the test is done, this shared context makes sure to restore the correct schema by running the migrations that post-date the one being tested. Thus, avoiding cases of a half-migrated database that could result in random test failures. It also makes sure to test not every migration that comes after the test migration, but just a single migration is executed and then the expected behavior is evaluated. 1. **Performance**: Running migrations (`Sequel::Migrator.run(...)`) can be time-consuming and take serval seconds with each call. Therefore, it's advisable to limit the number of migration calls within a single spec file as much as possible. Group related tests into a single it block even if it does not follow the usual RSpec best practices. This approach minimizes the number of migration calls and enhances test performance. +### Helper methods + +The `migration` shared context uses the `migration_filename` variable, containing the filename of the migration under review. It also provides a path to all migrations in `migrations_path` as well as the index of the current migration in the `current_migration_index` variable. On top of these, it exposes four helper methods that should be used instead of calling `Sequel::Migrator.run(...)` directly. They keep specs readable and force repeated execution for idempotency checks: + +1. `run_migration` – runs the migration under test (migrates up to `current_migration_index`). +1. `revert_migration` – reverts the migration under test (migrates down to `current_migration_index - 1`). Use this to test the down part of a migration. +1. `test_up_migration_idempotency` – asserts that running the migration's up part a second time does not raise. It first asserts that the migration is recorded as applied in `schema_migrations`; call `run_migration` before using this helper. It removes the migration's row and then calls `run_migration`, which forces the up part to actually execute again rather than being skipped. This catches errors such as `DuplicateColumn` when an operation cannot be repeated. +1. `test_down_migration_idempotency` – the counterpart for the down part. It first asserts that the migration's row is absent from `schema_migrations`; the migration must already be reverted. It re-inserts the row and then calls `revert_migration`, forcing the down part to execute again. + +**Successful re-execution alone does not prove idempotency:** a migration can silently change data or schema on its second run. After each idempotency helper, query the database again and assert the expected state, including data that must be preserved (see rule 4 in [Rules when writing migrations](#rules-when-writing-migrations)). + +All other processes, including migrating one version before the test migration and fully migrating the schema after the test has finished, are handled automatically by the shared context. + ### Usage -Here’s a guide on how to write a migration spec. The `migration` shared context uses the `migration_file` variable, containing the filename of the migration under review. This shared context also provides a path to all migrations in `migrations_path` as well as the index of the current migration in `current_migration_index` variable to perform the specific migration. All other processes, including migrating one version before the test migration and fully migrating the table after the test has finished, are handled automatically. -For testing the down part of a migration one can use `Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true)` +Here’s a guide on how to write a migration spec. ```ruby require 'spec_helper' require 'migrations/helpers/migration_shared_context' @@ -98,17 +110,38 @@ RSpec.describe 'migration to modify isolation_segments', isolation: :truncation describe 'isolation_segments table' do it 'retains the initial name and guid' do db[:isolation_segments].insert(name: 'name', guid: '123') - a1 = db[:isolation_segment_annotations].first(resource_guid: '123') - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error - b1 = db[:isolation_segment_annotations].first(resource_guid: '123') + a1 = db[:isolation_segments].first(guid: '123') + + # Run the migration under test + run_migration + + b1 = db[:isolation_segments].first(guid: '123') expect(b1[:guid]).to eq a1[:guid] expect(b1[:name]).to eq a1[:name] - - # Test idempotency of the migration - expect { Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) }.not_to raise_error + + # Test idempotency of the up migration + test_up_migration_idempotency + c1 = db[:isolation_segments].first(guid: '123') + expect(c1[:guid]).to eq b1[:guid] + expect(c1[:name]).to eq b1[:name] end end end ``` The code mentioned above tests a migration that alters the isolation_segments table. It confirms that the initial name and guid remain intact even after the migration operation. Note that in this scenario, the CC models are not used. Instead, the selects and inserts are performed directly with Sequel, keeping in mind the schema that exists before and after the migration. This approach ensures accuracy, and the test will continue to work even if later migrations alter the table, CC code and models, or even drop tables, etc. Essentially, the migration is tested in the state that the DB was in at the time of writing the migration. + +If the migration is reversible, test the down part as well with `revert_migration` and, where the body is idempotent, `test_down_migration_idempotency`: +```ruby + # Run the migration under test + run_migration + # ... assert the post-up state ... + test_up_migration_idempotency + # ... query again and reassert the post-up state ... + + # Revert the migration under test + revert_migration + # ... assert the post-down state ... + test_down_migration_idempotency + # ... query again and reassert the post-down state ... +``` diff --git a/spec/migrations/helpers/migration_shared_context.rb b/spec/migrations/helpers/migration_shared_context.rb index 574ea93ad5d..481416d595d 100644 --- a/spec/migrations/helpers/migration_shared_context.rb +++ b/spec/migrations/helpers/migration_shared_context.rb @@ -12,7 +12,7 @@ Sequel.extension :migration # Revert the given migration and everything newer so we are at the database version exactly before our migration we want to test. - Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) + revert_migration end after do @@ -23,4 +23,28 @@ # Complete the migration to not leave the test database half migrated and following tests fail due to this Sequel::Migrator.run(db, migrations_path, target: last_migration_index, allow_missing_migration_files: true) end + + def run_migration + Sequel::Migrator.run(db, migrations_path, target: current_migration_index, allow_missing_migration_files: true) + end + + def revert_migration + Sequel::Migrator.run(db, migrations_path, target: current_migration_index - 1, allow_missing_migration_files: true) + end + + def test_up_migration_idempotency + migration = db[:schema_migrations].where(filename: migration_filename) + expect(migration).not_to be_empty, 'Run run_migration before testing up migration idempotency' + + migration.delete + expect { run_migration }.not_to raise_error + end + + def test_down_migration_idempotency + migration = db[:schema_migrations].where(filename: migration_filename) + expect(migration).to be_empty, 'Revert the migration before testing down migration idempotency' + + db[:schema_migrations].insert(filename: migration_filename) + expect { revert_migration }.not_to raise_error + end end diff --git a/spec/migrations/helpers/migration_shared_context_spec.rb b/spec/migrations/helpers/migration_shared_context_spec.rb new file mode 100644 index 00000000000..5a731e23b80 --- /dev/null +++ b/spec/migrations/helpers/migration_shared_context_spec.rb @@ -0,0 +1,28 @@ +require 'spec_helper' +require 'migrations/helpers/migration_shared_context' + +RSpec.describe 'migration shared context', isolation: :truncation, type: :migration do + include_context 'migration' do + let(:migration_filename) { '20260630120000_add_status_to_spaces.rb' } + end + + it 'rejects idempotency checks in the wrong migration state without changing the database' do + expect { test_up_migration_idempotency }.to raise_error( + RSpec::Expectations::ExpectationNotMetError, + 'Run run_migration before testing up migration idempotency' + ) + + expect(db[:schema_migrations].where(filename: migration_filename)).to be_empty + expect(db[:spaces].columns).not_to include(:status) + + run_migration + + expect { test_down_migration_idempotency }.to raise_error( + RSpec::Expectations::ExpectationNotMetError, + 'Revert the migration before testing down migration idempotency' + ) + + expect(db[:schema_migrations].where(filename: migration_filename)).not_to be_empty + expect(db[:spaces].columns).to include(:status) + end +end From 8b4d21dac0b801842100f3297ef9a8e0e9319eac Mon Sep 17 00:00:00 2001 From: Philipp Thun Date: Fri, 27 Nov 2026 14:12:38 +0100 Subject: [PATCH 2/2] Add PostgreSQL indexes for domain ownership and sharing Create both indexes concurrently and keep MySQL unchanged. Test their definitions, preservation and up/down idempotency. --- ...0261127140000_add_domain_lookup_indexes.rb | 23 ++++++++++++ ...27140000_add_domain_lookup_indexes_spec.rb | 35 +++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 db/migrations/20261127140000_add_domain_lookup_indexes.rb create mode 100644 spec/migrations/20261127140000_add_domain_lookup_indexes_spec.rb diff --git a/db/migrations/20261127140000_add_domain_lookup_indexes.rb b/db/migrations/20261127140000_add_domain_lookup_indexes.rb new file mode 100644 index 00000000000..4df45626d88 --- /dev/null +++ b/db/migrations/20261127140000_add_domain_lookup_indexes.rb @@ -0,0 +1,23 @@ +Sequel.migration do + no_transaction # to create and drop indexes concurrently + + up do + # MySQL already indexes these foreign key columns. + next unless database_type == :postgres + + VCAP::Migration.with_concurrent_timeout(self) do + add_index :domains, :owning_organization_id, name: :domains_owning_org_id_index, if_not_exists: true, concurrently: true + add_index :organizations_private_domains, %i[private_domain_id organization_id], + name: :orgs_pd_domain_org_ids, if_not_exists: true, concurrently: true + end + end + + down do + next unless database_type == :postgres + + VCAP::Migration.with_concurrent_timeout(self) do + drop_index :domains, nil, name: :domains_owning_org_id_index, if_exists: true, concurrently: true + drop_index :organizations_private_domains, nil, name: :orgs_pd_domain_org_ids, if_exists: true, concurrently: true + end + end +end diff --git a/spec/migrations/20261127140000_add_domain_lookup_indexes_spec.rb b/spec/migrations/20261127140000_add_domain_lookup_indexes_spec.rb new file mode 100644 index 00000000000..a87a8b87f58 --- /dev/null +++ b/spec/migrations/20261127140000_add_domain_lookup_indexes_spec.rb @@ -0,0 +1,35 @@ +require 'spec_helper' +require 'migrations/helpers/migration_shared_context' + +RSpec.describe 'migration to add domain lookup indexes', isolation: :truncation, type: :migration do + include_context 'migration' do + let(:migration_filename) { '20261127140000_add_domain_lookup_indexes.rb' } + end + + it 'adds and removes non-unique indexes idempotently' do + skip unless db.database_type == :postgres + + expect(db.indexes(:domains)).not_to include(:domains_owning_org_id_index) + expect(db.indexes(:organizations_private_domains)).not_to include(:orgs_pd_domain_org_ids) + + expect { run_migration }.not_to raise_error + expect(db.indexes(:domains)[:domains_owning_org_id_index]).to include(columns: [:owning_organization_id], unique: false) + expect(db.indexes(:organizations_private_domains)[:orgs_pd_domain_org_ids]).to include(columns: %i[private_domain_id organization_id], unique: false) + expect(db.indexes(:organizations_private_domains)[:orgs_pd_ids]).to include(columns: %i[organization_id private_domain_id], unique: true) + + test_up_migration_idempotency + expect(db.indexes(:domains)[:domains_owning_org_id_index]).to include(columns: [:owning_organization_id], unique: false) + expect(db.indexes(:organizations_private_domains)[:orgs_pd_domain_org_ids]).to include(columns: %i[private_domain_id organization_id], unique: false) + expect(db.indexes(:organizations_private_domains)[:orgs_pd_ids]).to include(columns: %i[organization_id private_domain_id], unique: true) + + expect { revert_migration }.not_to raise_error + expect(db.indexes(:domains)).not_to include(:domains_owning_org_id_index) + expect(db.indexes(:organizations_private_domains)).not_to include(:orgs_pd_domain_org_ids) + expect(db.indexes(:organizations_private_domains)[:orgs_pd_ids]).to include(columns: %i[organization_id private_domain_id], unique: true) + + test_down_migration_idempotency + expect(db.indexes(:domains)).not_to include(:domains_owning_org_id_index) + expect(db.indexes(:organizations_private_domains)).not_to include(:orgs_pd_domain_org_ids) + expect(db.indexes(:organizations_private_domains)[:orgs_pd_ids]).to include(columns: %i[organization_id private_domain_id], unique: true) + end +end