Module: DynamicMigrations::ActiveRecord::Migrators::UniqueConstraint

Included in:
DynamicMigrations::ActiveRecord::Migrators
Defined in:
lib/dynamic_migrations/active_record/migrators/unique_constraint.rb

Instance Method Summary collapse

Instance Method Details

#add_unique_constraint(table_name, column_names, name:, deferrable: false, initially_deferred: false, comment: nil) ⇒ Object

because rails migrations don’t support composite (multiple column) foreign keys column_names can be a single column name or an array of column names



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/dynamic_migrations/active_record/migrators/unique_constraint.rb', line 7

def add_unique_constraint table_name, column_names, name:, deferrable: false, initially_deferred: false, comment: nil
  if initially_deferred == true && deferrable == false
    raise DeferrableOptionsError, "A constraint can only be initially deferred if it is also deferrable"
  end

  # convert single column names into arrays, this simplifies the logic below
  column_names = column_names.is_a?(Array) ? column_names : [column_names]

  # allow it to be deferred, and defer it by default
  deferrable_sql = if initially_deferred
    "DEFERRABLE INITIALLY DEFERRED"

  # allow it to be deferred, but do not deferr by default
  elsif deferrable
    "DEFERRABLE INITIALLY IMMEDIATE"

  # it can not be deferred (this is the default)
  else
    "NOT DEFERRABLE"
  end

  execute <<~SQL
    ALTER TABLE #{table_name}
      ADD CONSTRAINT #{name}
        UNIQUE (#{column_names.join(", ")})
        #{deferrable_sql};
  SQL

  if comment.is_a? String
    set_unique_constraint_comment table_name, name, comment
  end
end

#remove_unique_constraint(table_name, name) ⇒ Object



40
41
42
43
44
45
# File 'lib/dynamic_migrations/active_record/migrators/unique_constraint.rb', line 40

def remove_unique_constraint table_name, name
  execute <<~SQL
    ALTER TABLE #{table_name}
      DROP CONSTRAINT #{name};
  SQL
end

#remove_unique_constraint_comment(table_name, unique_constraint_name) ⇒ Object

remove a unique_constraint comment



55
56
57
58
59
# File 'lib/dynamic_migrations/active_record/migrators/unique_constraint.rb', line 55

def remove_unique_constraint_comment table_name, unique_constraint_name
  execute <<~SQL
    COMMENT ON CONSTRAINT #{unique_constraint_name} ON #{schema_name}.#{table_name} IS NULL;
  SQL
end

#set_unique_constraint_comment(table_name, unique_constraint_name, comment) ⇒ Object

add a comment to the unique_constraint



48
49
50
51
52
# File 'lib/dynamic_migrations/active_record/migrators/unique_constraint.rb', line 48

def set_unique_constraint_comment table_name, unique_constraint_name, comment
  execute <<~SQL
    COMMENT ON CONSTRAINT #{unique_constraint_name} ON #{schema_name}.#{table_name} IS #{quote comment};
  SQL
end