Depth of relational tree of a table T (DRT(T)) is defined by Piattini et al. (2001) as "the longest referential path between tables, from the table T to any other table in the schema". The result may help to classify the data. If the depth is 0, then probably the table contains classifers. Tables with the largest depth probably contain some extra information about main entities.
Notes
The query finds transitive closure of tables. In other words it finds all possible paths between tables where it is possible to reach from one table to another based on parent-child relationships. The query assumes that these relationships have been enforced in the database by declaring foreign key (referential) constraints.
Type
Sofware measure (Numeric values (software measures) about the database)
WITH RECURSIVE transitive_closure AS (
WITH foo AS (SELECT conrelid AS child, confrelid AS parent
FROM pg_constraint
WHERE contype='f')
SELECT child, parent, 1 AS distance, child || '.' || parent || '.' AS path_string
FROM foo
UNION ALL
SELECT tc.child, e.parent, tc.distance + 1, tc.path_string || e.parent || '.' AS path_string
FROM foo AS e INNER JOIN transitive_closure AS tc ON e.child = tc.parent
WHERE tc.path_string NOT LIKE '%' || e.parent || '.%'),
biggest_distance AS (SELECT child, Max(distance) AS depth
FROM transitive_closure
GROUP BY child)
SELECT nc.nspname AS table_schema, c.relname AS table_name, depth
FROM biggest_distance AS o INNER JOIN pg_class AS c ON o.child=c.oid
INNER JOIN pg_namespace AS nc ON c.relnamespace=nc.oid
INNER JOIN pg_authid AS a ON nc.nspowner=a.oid
WHERE (nc.nspname='public' OR rolname<>'postgres')
UNION SELECT nc.nspname AS table_schema, c.relname AS table_name, 0 AS depth
FROM pg_class AS c INNER JOIN pg_namespace AS nc ON c.relnamespace=nc.oid
INNER JOIN pg_authid AS a ON nc.nspowner=a.oid
WHERE (nc.nspname='public' OR rolname<>'postgres')
AND c.relkind='r'
AND NOT EXISTS (SELECT *
FROM pg_constraint
WHERE contype='f'
AND pg_constraint.conrelid=c.oid)
ORDER BY depth DESC, table_schema, table_name;
Collections
This query belongs to the following collections:
Name
Description
Find problems by overview
Queries that results point to different aspects of database that might have problems. A human reviewer has to decide based on the results as to whether there are problems or not .
Find quick numeric overview of the database
Queries that return numeric values showing mostly the number of different types of database objects in the database
Categories
This query is classified under the following categories:
Name
Description
Relationships between tables
Queries of this category provide information about how database tables are connected to each other and whether such connections have been explicitly defined and whether it has been done correctly.
Further reading and related materials:
Reference
Piattini, M., Calero, C., Sahraoui, H. A., & Lounis, H. (2001). Object-relational database metrics. L'Objet, 7(4), 477-496.