Skip to content

Instantly share code, notes, and snippets.

@hauleth
Created April 17, 2018 17:22
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hauleth/7b239be7a1dd08664d8a9484449232eb to your computer and use it in GitHub Desktop.
Save hauleth/7b239be7a1dd08664d8a9484449232eb to your computer and use it in GitHub Desktop.
Script to generate DOT graph of dependencies between tables in PostgreSQL
#!/bin/sh
psql -qX "$@" <<EOF
\t on
\timing off
\echo 'Digraph F{'
\echo 'ranksep=1.0; size="18.5, 15.5"; rankdir=LR;'
SELECT
'"' || tc.table_name || '"->"' || ccu.table_name || '" [label="' || tc.constraint_name || '"];'
FROM
information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu ON
tc.constraint_name = kcu.constraint_name
JOIN information_schema.constraint_column_usage AS ccu ON
ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY';
\echo '}'
EOF
@bartekupartek
Copy link

usage example pg_graph db_name | dot -Tsvg > out.svg

@davidfetter
Copy link

Awesome!

Would there be any point to adding functions, procedures, and views?

@jaydorsey
Copy link

This is excellent. Thank you!

@hauleth
Copy link
Author

hauleth commented Jun 5, 2020

I have created repo with some small improvements and additional scripts https://github.com/hauleth/pg-utils. If anyone is interested.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment