def METHOD_NAME(self, codes):
    codes = list(codes)
    relationship_table = TPPRelationship._meta.db_table
    placeholders = ", ".join(["%s"] * len(codes))
    sql = f"""
    WITH RECURSIVE tree(ancestor_id, descendant_id) AS (
    SELECT ancestor_id, descendant_id
    FROM {relationship_table}
    WHERE ancestor_id IN ({placeholders}) AND distance = 1
    UNION
    SELECT r.ancestor_id, r.descendant_id
    FROM {relationship_table} r
    INNER JOIN tree t
        ON r.ancestor_id = t.descendant_id
    WHERE distance = 1
    )
    SELECT ancestor_id, descendant_id FROM tree
    """
    return query(sql, codes, database=self.database_alias)