-
Notifications
You must be signed in to change notification settings - Fork 368
Replacing validate uniqueness with db constraint on SecurityGroup model #4955
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
serdarozerr
wants to merge
3
commits into
cloudfoundry:main
Choose a base branch
from
sap-contributions:feature/replace-validate-uniqueness-with-db-constraint-on-securitygroup
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
64 changes: 64 additions & 0 deletions
64
db/migrations/20260323130619_add_unique_constraint_to_security_groups.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| Sequel.migration do # rubocop:disable Metrics/BlockLength | ||
| no_transaction # required for concurrently option on postgres | ||
|
|
||
| up do | ||
| transaction do | ||
| duplicates = self[:security_groups].select(:name). | ||
| group(:name). | ||
| having { count(1) > 1 } | ||
|
|
||
| duplicates.each do |dup| | ||
| ids_to_remove = self[:security_groups]. | ||
| where(name: dup[:name]). | ||
| select(:id). | ||
| order(:id). | ||
| offset(1). | ||
| map(:id) | ||
| self[:security_groups].where(id: ids_to_remove).delete | ||
| end | ||
| end | ||
|
|
||
| if database_type == :postgres | ||
| VCAP::Migration.with_concurrent_timeout(self) do | ||
| add_index :security_groups, :name, | ||
| name: :security_group_name_index, | ||
| unique: true, | ||
| concurrently: true, | ||
| if_not_exists: true | ||
| drop_index :security_groups, nil, | ||
| name: :sg_name_index, | ||
| concurrently: true, | ||
| if_exists: true | ||
| end | ||
| else | ||
| alter_table(:security_groups) do | ||
| # rubocop:disable Sequel/ConcurrentIndex -- MySQL does not support concurrent index operations | ||
| add_index :name, name: :security_group_name_index, unique: true unless @db.indexes(:security_groups).key?(:security_group_name_index) | ||
| drop_index :name, name: :sg_name_index if @db.indexes(:security_groups).key?(:sg_name_index) | ||
| # rubocop:enable Sequel/ConcurrentIndex | ||
| end | ||
| end | ||
| end | ||
|
|
||
| down do | ||
| if database_type == :postgres | ||
| VCAP::Migration.with_concurrent_timeout(self) do | ||
| add_index :security_groups, :name, | ||
| name: :sg_name_index, | ||
| concurrently: true, | ||
| if_not_exists: true | ||
| drop_index :security_groups, nil, | ||
| name: :security_group_name_index, | ||
| concurrently: true, | ||
| if_exists: true | ||
| end | ||
| else | ||
| alter_table(:security_groups) do | ||
| # rubocop:disable Sequel/ConcurrentIndex -- MySQL does not support concurrent index operations | ||
| add_index :name, name: :sg_name_index unless @db.indexes(:security_groups).key?(:sg_name_index) | ||
| drop_index :name, name: :security_group_name_index if @db.indexes(:security_groups).key?(:security_group_name_index) | ||
| # rubocop:enable Sequel/ConcurrentIndex | ||
| end | ||
| end | ||
| end | ||
| end | ||
45 changes: 45 additions & 0 deletions
45
spec/migrations/20260323130619_add_unique_constraint_to_security_groups_spec.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| require 'spec_helper' | ||
| require 'migrations/helpers/migration_shared_context' | ||
| RSpec.describe 'add unique constraint to security_groups', isolation: :truncation, type: :migration do | ||
| include_context 'migration' do | ||
| let(:migration_filename) { '20260323130619_add_unique_constraint_to_security_groups.rb' } | ||
| end | ||
|
|
||
| it 'remove dublicates, add constraint and revert migration' do | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. typo: duplicates |
||
| # ========================================================================================= | ||
| # SETUP: Create duplicate entries to test the de-duplication logic. | ||
| # ========================================================================================= | ||
| db[:security_groups].insert(guid: SecureRandom.uuid, name: 'sec1') | ||
| db[:security_groups].insert(guid: SecureRandom.uuid, name: 'sec1') | ||
| expect(db[:security_groups].where(name: 'sec1').count).to eq(2) | ||
|
|
||
| # ========================================================================================= | ||
| # 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) | ||
|
|
||
| # ========================================================================================= | ||
| # ASSERT UP MIGRATION: Verify that duplicates are removed and constraints are enforced. | ||
| # ========================================================================================= | ||
| expect(db[:security_groups].where(name: 'sec1').count).to eq(1) | ||
| expect(db.indexes(:security_groups)).to include(:security_group_name_index) | ||
| expect { db[:security_groups].insert(guid: SecureRandom.uuid, name: 'sec1') }.to raise_error(Sequel::UniqueConstraintViolation) | ||
|
|
||
| # ========================================================================================= | ||
| # 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 | ||
|
|
||
| # ========================================================================================= | ||
| # 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) | ||
|
|
||
| # ========================================================================================= | ||
| # ASSERT DOWN MIGRATION: Verify that constraints are removed and duplicates can be re-inserted. | ||
| # ========================================================================================= | ||
| expect(db.indexes(:security_groups)).not_to include(:security_group_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 | ||
| end | ||
| end | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -441,7 +441,6 @@ def build_all_rule(attrs={}) | |
|
|
||
| describe 'Validations' do | ||
| it { is_expected.to validate_presence :name } | ||
| it { is_expected.to validate_uniqueness :name } | ||
|
|
||
| context 'name' do | ||
| subject(:sec_group) { SecurityGroup.make } | ||
|
|
@@ -971,6 +970,29 @@ def build_all_rule(attrs={}) | |
| end | ||
| end | ||
|
|
||
| describe 'security_group_model #around_save' do | ||
| it 'raises validation error on unique constraint violation for securit group' do | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. typo: security |
||
| sg = SecurityGroup.make(name: 'sec') | ||
| expect do | ||
| SecurityGroup.make(name: sg.name) | ||
| end.to raise_error(Sequel::ValidationFailed) { |error| expect(error.message).to match(/unique/) } | ||
| end | ||
|
|
||
| it 'raises the original error on other unique constraint violations' do | ||
| sg = SecurityGroup.make(name: 'sec1') | ||
|
|
||
| # Unlike other models, security_groups.guid does not have a unique index, | ||
| # so we use the primary key (id) to trigger a UniqueConstraintViolation. | ||
| # Sequel restricts setting id by default, so unrestrict_primary_key is required. | ||
| SecurityGroup.unrestrict_primary_key | ||
| expect do | ||
| SecurityGroup.create(id: sg.id, name: 'sec2') | ||
| end.to raise_error(Sequel::UniqueConstraintViolation) | ||
| ensure | ||
| SecurityGroup.restrict_primary_key | ||
| end | ||
| end | ||
|
|
||
| describe '.user_visibility_filter' do | ||
| let(:security_group) { SecurityGroup.make } | ||
| let(:space) { Space.make } | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The other indexes use the plural form for models. Should we name this
security_groups_name_index?