Sha256: 9ad37bb2cb01869d58c0a5cca49473cd92718275c59e2c68d35929ed3e735ced

Contents?: true

Size: 1.34 KB

Versions: 1

Compression:

Stored size: 1.34 KB

Contents

require 'rein/util'

module Rein
  module Constraint
    # This module contains methods for defining unique constraints.
    module Unique
      include ActiveRecord::ConnectionAdapters::Quoting

      def add_unique_constraint(*args)
        reversible do |dir|
          dir.up do _add_unique_constraint(*args) end
          dir.down { _remove_unique_constraint(*args) }
        end
      end

      def remove_unique_constraint(*args)
        reversible do |dir|
          dir.up do _remove_unique_constraint(*args) end
          dir.down { _add_unique_constraint(*args) }
        end
      end

      private

      def _add_unique_constraint(table, attributes, options = {})
        attributes = [attributes].flatten
        name = Util.constraint_name(table, attributes.join('_'), 'unique', options)
        initially = options[:deferred] ? 'DEFERRED' : 'IMMEDIATE'
        sql = "ALTER TABLE #{table} ADD CONSTRAINT #{name} UNIQUE (#{attributes.join(', ')})"
        sql << " DEFERRABLE INITIALLY #{initially}" unless options[:deferrable] == false
        execute(sql)
      end

      def _remove_unique_constraint(table, attributes, options = {})
        attributes = [attributes].flatten
        name = Util.constraint_name(table, attributes.join('_'), 'unique', options)
        execute("ALTER TABLE #{table} DROP CONSTRAINT #{name}")
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rein-3.3.0 lib/rein/constraint/unique.rb