     LEFT JOIN (
       -- count references of referencing tables
       -- > 1 ref = extra delete function
-      WITH RECURSIVE ref_table_depth(parent_oid, child_oid, depth) AS (
+      WITH RECURSIVE ref_table_depth(parent_table, ref_table, depth) AS (
         SELECT DISTINCT ON (conrelid)
-          confrelid AS parent_oid,
-          conrelid AS child_oid,
+          confrelid AS parent_table,
+          conrelid AS ref_table,
           1 AS depth
         FROM
           pg_constraint

          AND contype = 'f'
          AND confdeltype = 'a'
        UNION ALL
          SELECT DISTINCT ON (conrelid)
            c.confrelid AS parent_oid,
            c.conrelid AS child_oid,
            d.depth + 1 AS depth
          FROM
            pg_constraint c,
            ref_table_depth d
          WHERE (d.child_oid = c.confrelid)
            AND d.child_oid <> c.conrelid
            AND c.contype = 'f'
            AND confdeltype = 'a'
      )
      SELECT
        parent_oid AS ref_node,
        count(parent_oid) AS ref_count,
        max(depth) AS ref_depth
      FROM
        ref_table_depth
      GROUP BY
        parent_oid
    ) rf
    ON rf.ref_node = c.conrelid
    -- check for FKs in ref tables which cover same columns as the PK
    -- if found = extra delete function to clean parent, except parent table = $1
    LEFT JOIN LATERAL (

          AND contype = 'f'
          AND confdeltype = 'a'
        UNION ALL
          SELECT DISTINCT ON (ct.conrelid)
            ct.confrelid AS parent_table,
            ct.conrelid AS ref_table,
            d.depth + 1 AS depth
          FROM
            pg_constraint ct,
            ref_table_depth d
          WHERE d.ref_table = ct.confrelid
            AND d.ref_table <> ct.conrelid
            AND ct.contype = 'f'
            AND ct.confdeltype = 'a'
      )
      SELECT
        parent_table,
        count(parent_table) AS ref_count,
        max(depth) AS ref_depth
      FROM
        ref_table_depth
      GROUP BY
        parent_table
    ) rf
    ON rf.parent_table = c.conrelid
    -- check for FKs in ref tables which cover same columns as the PK
    -- if found = extra delete function to clean parent, except parent table = $1
    LEFT JOIN LATERAL (
