Created
April 19, 2019 14:42
-
-
Save aleph-naught2tog/09450dc9a5db2d34b3ca118c3db74974 to your computer and use it in GitHub Desktop.
Find all the tables that reference a given table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
table_to_check_references_to='table_name' | |
database_name='dbname' | |
query=$(cat <<SQL | |
SELECT | |
table_constraints.table_schema, | |
table_constraints.constraint_name, | |
table_constraints.table_name, | |
key_column_usage.column_name, | |
constraint_column_usage.table_schema AS foreign_table_schema, | |
constraint_column_usage.table_name AS foreign_table_name, | |
constraint_column_usage.column_name AS foreign_column_name | |
FROM | |
information_schema.table_constraints AS table_constraints | |
JOIN information_schema.key_column_usage AS key_column_usage | |
ON table_constraints.constraint_name = key_column_usage.constraint_name | |
AND table_constraints.table_schema = key_column_usage.table_schema | |
JOIN information_schema.constraint_column_usage AS constraint_column_usage | |
ON constraint_column_usage.constraint_name = table_constraints.constraint_name | |
AND constraint_column_usage.table_schema = table_constraints.table_schema | |
WHERE table_constraints.constraint_type = 'FOREIGN KEY' | |
AND table_constraints.table_name='$table_to_check_references_to'; | |
SQL) | |
psql --dbname $database_name --echo-all --command "$query" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment