--
-- util__primary_key_exists/3
--
create or replace function util__primary_key_exists(
  p_table_name text,
  p_column text,
  p_single_p boolean DEFAULT true
) returns bool as $$

DECLARE
BEGIN
      return exists (select 1
       from
         information_schema.table_constraints AS tc,
         information_schema.key_column_usage  AS kcu
      where tc.constraint_name    = kcu.constraint_name
        and tc.constraint_catalog = kcu.constraint_catalog
        and tc.constraint_schema  = kcu.constraint_schema
        and tc.table_catalog      = kcu.table_catalog
        and tc.table_schema       = kcu.table_schema
        and tc.constraint_type    = 'PRIMARY KEY'
        and tc.table_name   = lower(p_table_name)
        and kcu.column_name = lower(p_column)
        and (not p_single_p or (
           -- this to ensure the constraint involves only one
           -- column
           select count(*) from information_schema.key_column_usage
            where constraint_name    = kcu.constraint_name
              and constraint_catalog = kcu.constraint_catalog
              and constraint_schema  = kcu.constraint_schema) = 1));
END;
$$ language plpgsql;