Module: PGSpecHelper::ForeignKeys

Included in:
PGSpecHelper
Defined in:
lib/pg_spec_helper/foreign_keys.rb

Instance Method Summary collapse

Instance Method Details

#create_foreign_key(schema_name, table_name, column_names, foreign_schema_name, foreign_table_name, foreign_column_names, foreign_key_name) ⇒ Object

Create a foreign key



6
7
8
9
10
11
12
13
14
15
16
# File 'lib/pg_spec_helper/foreign_keys.rb', line 6

def create_foreign_key schema_name, table_name, column_names, foreign_schema_name, foreign_table_name, foreign_column_names, foreign_key_name
  column_names_sql = column_names.join(", ")
  foreign_column_names_sql = foreign_column_names.join(", ")
  # add the foreign key
  connection.exec(<<~SQL)
    ALTER TABLE #{schema_name}.#{table_name}
      ADD CONSTRAINT #{foreign_key_name}
      FOREIGN KEY (#{column_names_sql})
        REFERENCES #{foreign_schema_name}.#{foreign_table_name} (#{foreign_column_names_sql})
  SQL
end

#get_foreign_key_names(schema_name, table_name) ⇒ Object

returns a list of foreign keys for the provided table



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/pg_spec_helper/foreign_keys.rb', line 19

def get_foreign_key_names schema_name, table_name
  rows = connection.exec_params(<<~SQL, [schema_name.to_s, table_name.to_s])
    SELECT constraint_name
    FROM information_schema.table_constraints
    WHERE table_schema = $1
      AND table_name = $2
      AND constraint_type = 'FOREIGN KEY'
    ORDER BY constraint_name;
  SQL
  rows.map { |row| row["constraint_name"].to_sym }
end