Module: PostgresMigrationHelper

Defined in:
lib/pg_migrations/migrations_helper.rb

Instance Method Summary collapse

Instance Method Details

#add_foreign_key(from_table, from_column, to_table, options = {}) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
# File 'lib/pg_migrations/migrations_helper.rb', line 2

def add_foreign_key(from_table, from_column, to_table, options = {})
  constraint_name = "fk_#{from_table}_#{from_column}"

  sql= %{ALTER TABLE #{from_table}
            ADD CONSTRAINT #{constraint_name}
            FOREIGN KEY (#{from_column})
            REFERENCES #{to_table}(id)
            ON UPDATE RESTRICT}
  sql << " ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED" if options[:cascade_delete]
  execute sql
end

#add_unique_constraint(from_table, *fields) ⇒ Object

Adds a UNIQUE CONSTRAINT on a number of fields eg. add_unique_constraint(users, table1_id, table2_id, table3_id)



23
24
25
26
27
28
29
30
31
32
# File 'lib/pg_migrations/migrations_helper.rb', line 23

def add_unique_constraint(from_table, *fields)
  constraint_name = "#{from_table}_unique_on_#{fields.join('_')}"
  constraint_name = "#{from_table}_unique_on_#{fields.join('_')}" if constraint_name.length > 60

  sql = %{ALTER TABLE #{from_table}
            ADD CONSTRAINT #{constraint_name}
              UNIQUE (#{fields.join(',')})
            }
  execute sql
end

#remove_foreign_key(from_table, from_column, to_table) ⇒ Object



14
15
16
17
18
19
# File 'lib/pg_migrations/migrations_helper.rb', line 14

def remove_foreign_key(from_table, from_column, to_table)
  constraint_name = "fk_#{from_table}_#{from_column}"

  execute %{ALTER TABLE #{from_table}
            DROP CONSTRAINT #{constraint_name}}
end

#remove_unique_constraint(from_table, *fields) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/pg_migrations/migrations_helper.rb', line 34

def remove_unique_constraint(from_table, *fields)
  constraint_name = "#{from_table}_unique_on_#{fields.join('_')}"
  constraint_name = "#{from_table}_unique_on_#{fields.join('_')}" if constraint_name.length > 60

  execute %{ALTER TABLE #{from_table}
            DROP CONSTRAINT #{constraint_name}}
end

#set_mandatory_column(table, column) ⇒ Object



42
43
44
45
# File 'lib/pg_migrations/migrations_helper.rb', line 42

def set_mandatory_column(table, column)
  execute %{ALTER TABLE #{table}
             ALTER COLUMN #{column} SET NOT NULL}
end

#unset_mandatory_column(table, column) ⇒ Object



47
48
49
50
# File 'lib/pg_migrations/migrations_helper.rb', line 47

def unset_mandatory_column(table, column)
  execute %{ALTER TABLE #{table}
             ALTER COLUMN #{column} DROP NOT NULL}
end