|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +class AddFkToProductProperties < 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 orphaned product properties (no corresponding product)" do |
| 8 | + # Spree::ProductProperty.left_joins(:product).where(spree_products: { id: nil }).delete_all |
| 9 | + # end |
| 10 | + begin |
| 11 | + add_foreign_key :spree_product_properties, :spree_products, column: :product_id, null: false |
| 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_product_properties => :spree_products. |
| 16 | + To fix this: |
| 17 | + 1. Uncomment the code that removes orphaned records. |
| 18 | + 2. Rerun the migration. |
| 19 | + Offending error: #{e.cause.class} - #{e.cause.message} |
| 20 | + MSG |
| 21 | + end |
| 22 | + raise |
| 23 | + end |
| 24 | + |
| 25 | + # Uncomment the following code to remove orphaned records if this migration fails |
| 26 | + # |
| 27 | + # say_with_time "Removing orphaned product properties (no corresponding property)" do |
| 28 | + # Spree::ProductProperty.left_joins(:property).where(spree_properties: { id: nil }).delete_all |
| 29 | + # end |
| 30 | + begin |
| 31 | + add_foreign_key :spree_product_properties, :spree_properties, column: :property_id, null: false |
| 32 | + rescue ActiveRecord::StatementInvalid => e |
| 33 | + if e.cause.is_a?(PG::ForeignKeyViolation) || e.cause.is_a?(Mysql2::Error) || e.cause.is_a?(SQLite3::ConstraintException) |
| 34 | + Rails.logger.warn <<~MSG |
| 35 | + ⚠️ Foreign key constraint failed when adding :spree_product_properties => :spree_properties. |
| 36 | + To fix this: |
| 37 | + 1. Uncomment the code that removes orphaned records. |
| 38 | + 2. Rerun the migration. |
| 39 | + Offending error: #{e.cause.class} - #{e.cause.message} |
| 40 | + MSG |
| 41 | + end |
| 42 | + raise |
| 43 | + end |
| 44 | + end |
| 45 | + |
| 46 | + def down |
| 47 | + remove_foreign_key :spree_product_properties, :spree_products, column: :product_id, null: false |
| 48 | + remove_foreign_key :spree_product_properties, :spree_properties, column: :property_id, null: false |
| 49 | + end |
| 50 | +end |
0 commit comments