 SELECT E'\n  -- delete references to '||$3||'s'
   || E'\n  WITH delete_'||$3||'_refs AS ('
   || E'\n    DELETE FROM'
-  || E'\n      '||$1
+  || E'\n      '||$1||' t'
+  || E'\n    USING'
+  || E'\n      unnest($1) a(a_id)'
   || E'\n    WHERE'
-  || E'\n      '||$2||' = $1'
+  || E'\n      t.'||$2||' = a.a_id'
   || E'\n    RETURNING'
-  || E'\n      '||$4
+  || E'\n      t.'||$4
   || E'\n  )'
   || E'\n  SELECT'
   || E'\n    array_agg('||$4||')'

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

          AND conrelid <> confrelid
          AND contype = 'f'
        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'
      )
      SELECT
        count(parent_table) AS m_table_count,
        max(depth) AS m_table_depth
      FROM
        ref_table_depth
      GROUP BY
        parent_table
    ) rtrf ON (true)
    -- check for FKs in n:m tables which cover same columns as PK
    -- if found = extra delete function to clean parent, except parent table = $1
