Skip to content

Commit e8ff683

Browse files
authored
Merge pull request #5803 from simpledotorg/fix/idempotent-patient-scores-migration
fix: Make CreatePatientScores migration idempotent
2 parents 16ac10e + 92f6e9d commit e8ff683

1 file changed

Lines changed: 26 additions & 11 deletions

File tree

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,36 @@
11
class CreatePatientScores < ActiveRecord::Migration[6.1]
2+
REQUIRED_COLUMNS = %i[patient_id score_type score_value device_created_at device_updated_at deleted_at].freeze
3+
24
def up
3-
create_table :patient_scores, id: :uuid do |t|
4-
t.references :patient, null: false, foreign_key: true, type: :uuid
5-
t.string :score_type, null: false, limit: 100
6-
t.decimal :score_value, precision: 5, scale: 2, null: false
7-
t.datetime :device_created_at, null: false
8-
t.datetime :device_updated_at, null: false
9-
t.datetime :deleted_at
5+
if table_exists?(:patient_scores) && !schema_complete?
6+
say "Dropping patient_scores table due to incomplete schema"
7+
drop_table :patient_scores
8+
end
9+
10+
unless table_exists?(:patient_scores)
11+
create_table :patient_scores, id: :uuid do |t|
12+
t.references :patient, null: false, foreign_key: true, type: :uuid
13+
t.string :score_type, null: false, limit: 100
14+
t.decimal :score_value, precision: 5, scale: 2, null: false
15+
t.datetime :device_created_at, null: false
16+
t.datetime :device_updated_at, null: false
17+
t.datetime :deleted_at
1018

11-
t.timestamps
19+
t.timestamps
20+
end
1221
end
1322

14-
add_index :patient_scores, [:patient_id, :score_type]
15-
add_index :patient_scores, :updated_at
23+
add_index :patient_scores, [:patient_id, :score_type], unique: true unless index_exists?(:patient_scores, [:patient_id, :score_type])
24+
add_index :patient_scores, :updated_at unless index_exists?(:patient_scores, :updated_at)
1625
end
1726

1827
def down
19-
drop_table :patient_scores
28+
drop_table :patient_scores, if_exists: true
29+
end
30+
31+
private
32+
33+
def schema_complete?
34+
REQUIRED_COLUMNS.all? { |col| column_exists?(:patient_scores, col) }
2035
end
2136
end

0 commit comments

Comments
 (0)