Skip to content

Commit 584e5ec

Browse files
committed
Add FK between Adjustments and Adjustment Reasons
This migration will fail if there are any adjustments with invalid adjustment reason IDs. The suggested path of action for store owners is to change those adjustment reason IDs to NULL, because we don't want to accidentally lose adjustments.
1 parent 8d2aaaa commit 584e5ec

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# frozen_string_literal: true
2+
3+
class AddAdjustmentReasonForeignKeys < ActiveRecord::Migration[7.0]
4+
def up
5+
# Uncomment the following code to remove orphaned records if this migration fails
6+
#
7+
# say_with_time "Removing invalid adjustment reason IDs from adjustments table" do
8+
# Spree::Adjustment.where.not(adjustment_reason_id: nil).left_joins(:adjustment_reason).where(spree_adjustment_reasons: { id: nil }).update_all(adjustment_reason_id: nil)
9+
# end
10+
11+
add_foreign_key :spree_adjustments, :spree_adjustment_reasons, column: :adjustment_reason_id, null: true, on_delete: :restrict
12+
rescue ActiveRecord::StatementInvalid => e
13+
if e.cause.is_a?(PG::ForeignKeyViolation) || e.cause.is_a?(Mysql2::Error) || e.cause.is_a?(SQLite3::ConstraintException)
14+
Rails.logger.warn <<~MSG
15+
⚠️ Foreign key constraint failed when adding :spree_adjustments => :spree_adjustment_reasons.
16+
To fix this:
17+
1. Uncomment the code that removes invalid adjustment reason IDs from the spree_adjustments table.
18+
2. Rerun the migration.
19+
Offending error: #{e.cause.class} - #{e.cause.message}
20+
MSG
21+
end
22+
raise
23+
end
24+
25+
def down
26+
remove_foreign_key :spree_adjustments, :spree_adjustment_reasons, column: :adjustment_reason_id, null: true, on_delete: :restrict
27+
end
28+
end

0 commit comments

Comments
 (0)