RLS policy causes infinite recursion
Last edited: 8/12/2026
如果你的存储或数据库请求遇到错误,并且相应的 Postgres 日志显示“在关系 'table_name' 的策略中检测到无限递归”,那是因为你的行级安全 (RLS) 策略中存在无限递归。
🌐 If your Storage or database requests encounter an error and the corresponding Postgres logs show 'infinite recursion detected in policy for relation "table_name"', it is because of infinite recursion in your Row-Level Security (RLS) policies.
这是为什么会发生?
这个错误表示 RLS 策略之间存在循环依赖。它发生在一个 RLS 策略查询启用了 RLS 的表时,而该表的策略最终又触发了原来的策略。
🌐 This error indicates a circular dependency between RLS policies. It occurs when an RLS policy queries a table with RLS enabled, and that table's policies end up triggering the original policy again.
这种情况可能发生在:
🌐 This can happen when:
- 一条策略查询同一张表。
- 一个策略查询另一个表,而那个表的 RLS 策略最终又引用了原始表,造成了循环依赖。
Postgres 会检测到递归策略的评估,并终止查询以防止无限递归。如果存储操作中的存储 RLS 策略引用了带有自引用或相互递归 RLS 策略的表,这个错误也可能发生。
🌐 Postgres detects the recursive policy evaluation and terminates the query to prevent infinite recursion. This error can also occur during Storage operations if a Storage RLS policy references a table with self-referencing or mutually recursive RLS policies.
如何解决这个问题:
选项 1:更新表的 RLS 策略,确保它们不会直接或间接地创建循环依赖。
🌐 Option 1: Update the table's RLS policies to ensure they do not directly or indirectly create a circular dependency.
选项 2:将权限检查封装在一个 SECURITY DEFINER 函数中。这个函数会以创建者的权限执行——如果用像 postgres 这样的角色创建,它可以绕过目标表的 RLS 并打破递归。详情见 使用 Security Definer 函数。
🌐 Option 2: Wrap the permission check in a SECURITY DEFINER function. This executes with the privileges of the user who created the function — if created with a role like postgres, it bypasses RLS on the target table and breaks the recursion. See Use Security Definer Functions for details.