防止 Postgresql 递归查询中的无限循环

mad*_*low 8 postgresql recursive-query common-table-expression

对不起 - 这有点含糊......

这里:(在 CTE 中找到无限递归循环)讨论了如何防止递归查询中出现无限循环。在“查询级别”上阻止了递归 - 至少在关于 Postgresql 的答案中是这样。

Postgresql (10) 有没有办法实现某种安全网来防止无限递归?这是一种可行的方法,statement_timeout还是有其他广泛接受的方法?

kli*_*lin 13

在我的开发环境中,我总是使用两个保险丝来进行递归查询或函数。我的客户端在启动时自动设置

set statement_timeout to '10s'
Run Code Online (Sandbox Code Playgroud)

我需要更多的情况很少见,而且它经常使我免于死循环。

当我从头开始编写递归查询时,我总是使用一个额外的列来限制所涉及的级别数,如下所示:

with recursive cte (root, parent, depth) as (
    select id, parent_id, 1
    from ...
union all
    select c.id, t.parent_id, depth+ 1
    from ...
    where depth < 10
)
select * 
from cte;
Run Code Online (Sandbox Code Playgroud)

在生产中,这两种方式都可能有问题。相反,您可以根据操作系统和/或硬件的预期需求和功能调整配置参数max_stack_depth(整数)的值。

a_horse_with_no_name描述的方法显然非常有效,在生产环境中也是如此,但不能一直使用(或者成本太高)。