Sha256: f02e3abc6ff2e30fb749155ecbda9211c8a4633e75c8f5745ae5ed6d51b4d912

Contents?: true

Size: 941 Bytes

Versions: 7

Compression:

Stored size: 941 Bytes

Contents

class AddUniqueIndexOnPropertyIdAndProductIdToProductProperties < ActiveRecord::Migration[5.2]
  def up
    klass   = Spree::ProductProperty
    columns = %w[property_id product_id]

    unless index_exists?(klass.table_name, columns)
      scope   = klass.unscoped

      say "Find duplicate #{klass} records"
      duplicates = scope.
        select((columns + %w[COUNT(*)]).join(',')).
        group("#{columns.join(',')}").
        having('COUNT(*) > 1').
        map { |row| row.attributes.slice(*columns) }

      say "Delete all but the oldest duplicate #{klass} record"
      duplicates.each do |conditions|
        scope.where(conditions).order(:created_at).drop(1).each(&:destroy)
      end

      say "Add unique index to #{klass.table_name} for #{columns.inspect}"
      add_index klass.table_name, columns, unique: true
    end
  end

  def down
    remove_index :spree_product_properties, [:property_id, :product_id]
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
spree_core-4.3.3 db/migrate/20210713131614_add_unique_index_on_property_id_and_product_id_to_product_properties.rb
spree_core-4.3.2 db/migrate/20210713131614_add_unique_index_on_property_id_and_product_id_to_product_properties.rb
spree_core-4.3.1 db/migrate/20210713131614_add_unique_index_on_property_id_and_product_id_to_product_properties.rb
spree_core-4.3.0 db/migrate/20210713131614_add_unique_index_on_property_id_and_product_id_to_product_properties.rb
spree_core-4.3.0.rc3 db/migrate/20210713131614_add_unique_index_on_property_id_and_product_id_to_product_properties.rb
spree_core-4.3.0.rc2 db/migrate/20210713131614_add_unique_index_on_property_id_and_product_id_to_product_properties.rb
spree_core-4.3.0.rc1 db/migrate/20210713131614_add_unique_index_on_property_id_and_product_id_to_product_properties.rb