def get_ancestors(cur, term_id):
    """Return a set of ancestors for a given term ID, all the way to the top-level (below owl:Thing)

    :param cur: database Cursor object to query
    :param term_id: term ID to get the ancestors of"""
    cur.execute(
        f"""WITH RECURSIVE ancestors(node) AS (
                VALUES ('{term_id}')
                UNION
                 SELECT object AS node
                FROM statements
                WHERE predicate IN ('rdfs:subClassOf', 'rdfs:subPropertyOf')
                  AND object = '{term_id}'
                UNION
                SELECT object AS node
                FROM statements, ancestors
                WHERE ancestors.node = statements.stanza
                  AND statements.predicate IN ('rdfs:subClassOf', 'rdfs:subPropertyOf')
                  AND statements.object NOT LIKE '_:%'
            )
            SELECT * FROM ancestors""",
    )
    return set([x[0] for x in cur.fetchall()])