Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Add unique index on property_id and product_id on spree_product_properties

Szymon Iwacz678047dd1db9
diff --git a/core/db/migrate/20210713131614_add_unique_index_on_property_id_and_product_id_to_product_properties.rb b/core/db/migrate/20210713131614_add_unique_index_on_property_id_and_product_id_to_product_properties.rb
new file mode 100644
index 0000000000..8ba49dc52f
--- /dev/null
+++ b/core/db/migrate/20210713131614_add_unique_index_on_property_id_and_product_id_to_product_properties.rb
@@ -0,0 +1,29 @@
+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