Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save valichek/bf55a3a7e70e56dd01aeb32abcf3b1e7 to your computer and use it in GitHub Desktop.
Save valichek/bf55a3a7e70e56dd01aeb32abcf3b1e7 to your computer and use it in GitHub Desktop.
запрос к PostgreSQL, который для указанных табличек сообщит все foreign keys
select
pg_namespace_parent.nspname as parent_schema, pg_class_parent.relname as parent_table, pg_attribute_parent.attname as parent_column,
pg_namespace_child.nspname as child_schema, pg_class_child.relname as child_table, pg_attribute_child.attname as child_column
from
(
select
pg_constraint.conrelid as "parent_table_id",
unnest(pg_constraint.conkey) as "parent_column_id",
pg_constraint.confrelid as "child_table_id",
unnest(pg_constraint.confkey) as "child_column_id"
from
pg_class
join pg_namespace on pg_class.relnamespace = pg_namespace.oid
join pg_constraint on pg_class.oid = pg_constraint.conrelid
where
(pg_namespace.nspname, pg_class.relname) in (('SCHEMA_NAME', 'TABLE_NAME_1'), ('SCHEMA_NAME', 'TABLE_NAME_2'))
and pg_constraint.contype = 'f'
) info
join pg_attribute as pg_attribute_parent on pg_attribute_parent.attrelid = info.parent_table_id and pg_attribute_parent.attnum = info.parent_column_id
join pg_attribute as pg_attribute_child on pg_attribute_child.attrelid = info.child_table_id and pg_attribute_child.attnum = info.child_column_id
join pg_class as pg_class_parent on pg_class_parent.oid = info.parent_table_id
join pg_class as pg_class_child on pg_class_child.oid = info.child_table_id
join pg_namespace as pg_namespace_parent on pg_namespace_parent.oid = pg_class_parent.relnamespace
join pg_namespace as pg_namespace_child on pg_namespace_child.oid = pg_class_child.relnamespace;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment