DEV: Add protection for migrations that creates index concurrently (#31763)

This commit updates `Migration::SafeMigrate` to protect against unsafe
ways of adding a Postgres index concurrently.

Per postgres documentation:

If a problem arises while scanning the table, such as a deadlock or a
uniqueness violation in a unique index,
the CREATE INDEX command will fail but leave behind an "invalid" index.
This index will be ignored for querying
purposes because it might be incomplete; however it will still consume
update overhead. The recommended recovery
method in such cases is to drop the index and try again to perform
CREATE INDEX CONCURRENTLY .

Therefore, the simplest way for us to ensure that migrations that create
indexes concurrently are idempotent is to follow postgres'
recommendation of dropping the index first before trying to create the
index concurrently.
This commit is contained in:
Alan Guo Xiang Tan
2025-03-13 09:34:14 +08:00
committed by GitHub
parent 962bdf3697
commit 6820622467
4 changed files with 91 additions and 0 deletions

View File

@ -71,6 +71,24 @@ RSpec.describe Migration::SafeMigrate do
expect { User.first.username }.not_to raise_error
end
it "allows running a migration that creates an index concurrently if it drops the index first" do
path = File.expand_path "#{Rails.root}/spec/fixtures/db/migrate/create_index_concurrently_safe"
output = capture_stdout { expect do migrate_up(path) end.to raise_error(StandardError) }
expect(output).not_to include(described_class::UNSAFE_DROP_INDEX_CONCURRENTLY_WARNING)
end
it "bans running a migration that creates an index concurrently without first dropping the index if it exists" do
Migration::SafeMigrate.enable!
path =
File.expand_path("#{Rails.root}/spec/fixtures/db/migrate/create_index_concurrently_unsafe")
output = capture_stdout { expect do migrate_up(path) end.to raise_error(StandardError) }
expect(output).to include(described_class::UNSAFE_DROP_INDEX_CONCURRENTLY_WARNING)
end
it "allows dropping NOT NULL" do
Migration::SafeMigrate.enable!