Postgresql – List foreign keys dependencies that refer to a given table

information-schemapostgresql

RDBMS: PostgreSQL 9.6

I desire to list the foreign keys for a given table and schema. I am about 90 % there but I also desire to know what options were used to make the fkey. Example on delete restrict or on delete update

create or replace function it.table_foreign_keys_getlist(_schema text
                                                       , _table text) 
                           returns TABLE(primary_key_ns text
                                       , primary_key_table text
                                       , foreign_key_ns text
                                       , foreign_key_table text
                                        )
     language sql
 as $$
 SELECT
     n1.nspname::TEXT  AS primary_key_ns,
     c1.relname::TEXT  AS primary_key_table,
     n2.nspname::TEXT  AS foreign_key_ns,
     c2.relname::TEXT  AS foreign_key_table
 FROM pg_catalog.pg_constraint c
 JOIN ONLY pg_catalog.pg_class c1     ON c1.oid = c.confrelid
 JOIN ONLY pg_catalog.pg_class c2     ON c2.oid = c.conrelid
 JOIN ONLY pg_catalog.pg_namespace n1 ON n1.oid = c1.relnamespace
 JOIN ONLY pg_catalog.pg_namespace n2 ON n2.oid = c2.relnamespace
 WHERE c1.relkind = 'r'
   AND c.contype  = 'f'
   AND CASE WHEN _schema = '' THEN TRUE ELSE n1.nspname = _schema END
   AND CASE WHEN _table  = '' THEN TRUE ELSE c1.relname = _table  END
 ORDER BY 1,2,3,4;
 $$;

Best Answer

You are looking for the columns confupdtype and confdeltype in the catalog pg_constraint.

The codes mean:

Foreign key deletion action code: a = no action, r = restrict, c = cascade, n = set null, d = set default