Skip to content

Instantly share code, notes, and snippets.

@topalovic
Last active October 17, 2023 05:14
Show Gist options
  • Save topalovic/3c3bebd33c1ae4b11d9bb2a479b33f13 to your computer and use it in GitHub Desktop.
Save topalovic/3c3bebd33c1ae4b11d9bb2a479b33f13 to your computer and use it in GitHub Desktop.
Dependency graph of Postgres tables based on FK constraints
# Provides a dependency graph of PG tables based on FK constraints,
# in the form of a hash map:
# {
# "some_table" => ["dependent_table_1", "dependent_table_2"],
# "dependent_table_1"=> ["dependent_table_3"],
# # ...
# }
def fk_dependency_graph
query = <<~SQL
SELECT
ccu.table_name AS main_table,
tc.table_name AS dependent_table
FROM
information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
ON tc.constraint_name = kcu.constraint_name
AND tc.table_schema = kcu.table_schema
JOIN information_schema.constraint_column_usage AS ccu
ON ccu.constraint_name = tc.constraint_name
AND ccu.table_schema = tc.table_schema
WHERE constraint_type = 'FOREIGN KEY'
SQL
tuples = ActiveRecord::Base.connection.execute(query).values
tuples.each_with_object(Hash.new([])) { |(k, v), r| r[k] |= [v] }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment