Sha256: 101784a9ab2ee667ef13d42571a1cb2aa5a75be3954a6a5501daeda7b9d5d975

Contents?: true

Size: 1.29 KB

Versions: 8

Compression:

Stored size: 1.29 KB

Contents

# This migration comes from spree (originally 20170323151450)
class AddMissingUniqueIndexesForUniqueAttributes < ActiveRecord::Migration[5.0]
  def change
    tables = {
      country: [:name, :iso_name],
      refund_reason: [:name],
      reimbursement_type: [:name],
      return_authorization_reason: [:name],
      role: [:name],
      store: [:code]
    }

    tables.each do |table, columns|
      table_class = "Spree::#{table.to_s.classify}".constantize
      table_name = table_class.table_name

      columns.each do |column|
        unless index_exists?(table_name, column, unique: true)
          attributes = table_class.unscoped.group(column).having('sum(1) > 1').pluck(column)
          instances = table_class.where(column => [nil, attributes])

          instances.find_each do |instance|
            column_value = 'Unique String ' + SecureRandom.urlsafe_base64(8).upcase.delete('/+=_-')[0, 8]
            instance.send("#{column}=", column_value)
            instance.save
          end

          remove_index table_name, column if index_exists?(table_name, column)
          if supports_expression_index?
            add_index table_name, "lower(#{column})", unique: true
          else
            add_index table_name, column, unique: true
          end
        end
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 2 rubygems

Version Path
spree_purchase_order-3.7.0 spec/dummy/db/migrate/20191113195949_add_missing_unique_indexes_for_unique_attributes.spree.rb
spree_billing_sisow-0.9.2 spec/dummy/db/migrate/20190729091890_add_missing_unique_indexes_for_unique_attributes.spree.rb
spree_billing_sisow-0.9.1 spec/dummy/db/migrate/20190729091890_add_missing_unique_indexes_for_unique_attributes.spree.rb
spree_purchase_order-3.6.0 spec/dummy/db/migrate/20180516191814_add_missing_unique_indexes_for_unique_attributes.spree.rb
spree_purchase_order-3.5.0 spec/dummy/db/migrate/20180516191814_add_missing_unique_indexes_for_unique_attributes.spree.rb
spree_purchase_order-3.5.0.rc1 spec/dummy/db/migrate/20180516191814_add_missing_unique_indexes_for_unique_attributes.spree.rb
spree_purchase_order-3.4.0 spec/dummy/db/migrate/20180516191814_add_missing_unique_indexes_for_unique_attributes.spree.rb
spree_purchase_order-3.3.0 spec/dummy/db/migrate/20180516191814_add_missing_unique_indexes_for_unique_attributes.spree.rb