You can do that a lot simpler and save fetches by letting the server build a common table expression that checks for cycles:
create table rec_test (id int, parent_id int) -- that's just for the example
with recursive check_cycle(id, parent_id, is_cycle) as (select id, parent_id, False from rec_test union all select check_cycle.id, rec_test.parent_id, check_cycle.id = rec_test.parent_id from check_cycle join rec_test on check_cycle.parent_id=rec_test.id and rec_test.parent_id is not null and not is_cycle) select * from check_cycle -- that's the real thing
Filter for the ids to check in the non-recursive part, then select rows with is_cycle=True and you're done with just this statement.
You can do that a lot simpler and save fetches by letting the server build a common table expression that checks for cycles:
create table rec_test (id int, parent_id int) -- that's just for the example
with recursive check_cycle(id, parent_id, is_cycle) as (select id, parent_id, False from rec_test union all select check_cycle.id, rec_test.parent_id, check_cycle.id = rec_test.parent_id from check_cycle join rec_test on check_cycle. parent_ id=rec_ test.id and rec_test.parent_id is not null and not is_cycle) select * from check_cycle -- that's the real thing
Filter for the ids to check in the non-recursive part, then select rows with is_cycle=True and you're done with just this statement.