import { tableListQuery } from "https://deno.land/x/denogres@v4.0.1/src/queries/introspection.ts";
type
`
WITH RECURSIVE depTable AS (
SELECT DISTINCT pg_constraint.conrelid, tc.relname tablename,
pg_constraint.confrelid foreign_id, ftc.relname, 1 AS level
FROM pg_constraint
INNER JOIN pg_class tc ON pg_constraint.conrelid = tc.oid
INNER JOIN pg_class ftc ON pg_constraint.confrelid = ftc.oid
INNER JOIN pg_tables tables on tc.relname = tables.tablename AND tables.schemaname NOT IN
('pg_catalog', 'information_schema')
WHERE contype = 'f'
UNION ALL
SELECT DISTINCT pgc.conrelid, class1.relname, pgc.confrelid, classf.relname, depTable.level + 1
FROM depTable
INNER JOIN pg_class class1 ON depTable.foreign_id = class1.oid
INNER JOIN pg_constraint pgc ON depTable.foreign_id = pgc.conrelid AND pgc.confrelid != 0
INNER JOIN pg_class classf ON pgc.confrelid = classf.oid
)
SELECT relname AS table_name
FROM (
SELECT DISTINCT dT.relname, MAX(dT.level) max_level
FROM depTable dT
GROUP BY dT.relname
UNION
SELECT class.relname AS table_name, 0 max_level
FROM pg_class class
INNER JOIN pg_tables tables on class.relname = tables.tablename
WHERE tables.schemaname NOT IN ('pg_catalog', 'information_schema')
AND class.relname NOT IN (SELECT relname FROM depTable)
ORDER BY max_level DESC
) AS TableList;`