Skip to content

Commit

Permalink
Adding a unique index to migrations (#815)
Browse files Browse the repository at this point in the history
* Adding an index to migrations with a unique constraint to avoid duplicate versions. Fixes #814

* Using the test db for this spec since the sample db seems to fail in CI
  • Loading branch information
jwoertink authored Mar 7, 2022
1 parent 6d03a13 commit 60108b5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
14 changes: 14 additions & 0 deletions spec/avram/migrator/runner_spec.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
require "../../spec_helper"

describe Avram::Migrator::Runner do
describe "setup_migration_tracking_table" do
it "includes a unique index" do
Avram.temp_config(database_to_migrate: TestDatabase) do
Avram::Migrator::Runner.setup_migration_tracking_tables

results = TestDatabase.query_all("SELECT indexname FROM pg_catalog.pg_indexes WHERE tablename = 'migrations'", as: String)
results.should contain("migrations_version_index")
end
end
end
end
11 changes: 10 additions & 1 deletion src/avram/migrator/runner.cr
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,9 @@ class Avram::Migrator::Runner
end

def self.setup_migration_tracking_tables
Avram.settings.database_to_migrate.exec create_table_for_tracking_migrations
db = Avram.settings.database_to_migrate
db.exec create_table_for_tracking_migrations
db.exec create_unique_index_for_migrations
end

private def self.create_table_for_tracking_migrations
Expand All @@ -115,6 +117,13 @@ class Avram::Migrator::Runner
SQL
end

private def self.create_unique_index_for_migrations
<<-SQL
CREATE UNIQUE INDEX IF NOT EXISTS migrations_version_index
ON #{MIGRATIONS_TABLE_NAME} (version)
SQL
end

def self.run(command : String, output : IO = STDOUT)
error_messages = IO::Memory.new
ENV["PGPASSWORD"] = self.db_password if self.db_password
Expand Down

0 comments on commit 60108b5

Please sign in to comment.