Module: PGSpecHelper::UniqueConstraints

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

Instance Method Summary collapse

Instance Method Details

#create_unique_constraint(schema_name, table_name, column_names, constraint_key_name) ⇒ Object

add a unique constraint to the provided table and columns



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

def create_unique_constraint schema_name, table_name, column_names, constraint_key_name
  column_names_sql = column_names.map { |n| connection.quote_ident n.to_s }.join(", ")
  # add the constraint key
  connection.exec("    ALTER TABLE \#{connection.quote_ident schema_name.to_s}.\#{connection.quote_ident table_name.to_s}\n      ADD CONSTRAINT \#{connection.quote_ident constraint_key_name.to_s}\n      UNIQUE (\#{column_names_sql})\n  SQL\nend\n")

#get_unique_constraint_names(schema_name, table_name) ⇒ Object

get a list of unique constraints for the provided table



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

def get_unique_constraint_names schema_name, table_name
  # get the unique constraint names
  rows = connection.exec("    SELECT\n      constraint_name\n    FROM\n      information_schema.table_constraints\n    WHERE\n      table_schema = $1\n      AND table_name = $2\n      AND constraint_type = 'UNIQUE'\n  SQL\n  rows.map { |r| r[\"constraint_name\"].to_sym }\nend\n", [schema_name.to_s, table_name.to_s])