Postgres allows for automatic cycle detection in recursive queries (see https://www.postgresql.org/docs/current/queries-with.html). Check if this can be done with SQLite too and add it for at least postgres.