title: Optimize RLS Policies for Performanceimpact: HIGHimpactDescription: 5-10x faster RLS queries with proper patternstags: rls, performance, security, optimization优化 RLS 策略以提升性能编写不当的 RLS 策略会导致严重的性能问题。应策略性地使用子查询和索引。错误做法每行都调用函数createpolicy orders_policyonordersusing(auth.uid()user_id);-- auth.uid() 每行都会调用-- 有 100 万行时auth.uid() 会被调用 100 万次正确做法将函数包在 SELECT 中createpolicy orders_policyonordersusing((selectauth.uid())user_id);-- 只调用一次并缓存-- 在大表上快 100 倍以上复杂检查使用安全定义函数SECURITY DEFINER函数以创建者的权限运行并会绕过它们访问的任何表上的 RLS——这使它们对内部查询很有用但如果使用不当也很危险。务必在函数体内显式包含auth.uid()检查将它们放在不对外暴露的 schema 中并对任何不应直接调用它们的角色撤销EXECUTE权限。-- 在私有 schema 中创建辅助函数createorreplacefunctionprivate.is_team_member(team_idbigint)returnsbooleanlanguagesqlsecuritydefinersetsearch_pathas$$selectexists(select1frompublic.team_members-- 始终在函数内部检查调用用户的身份whereteam_id$1anduser_id(selectauth.uid()));$$;-- 撤销公共角色的直接执行权限revokeexecuteonfunctionprivate.is_team_member(bigint)fromPUBLIC,anon,authenticated,service_role;-- 在策略中使用走索引查找而非逐行检查createpolicy team_orders_policyonordersusing((selectprivate.is_team_member(team_id)));始终为 RLS 策略中使用的列添加索引createindexorders_user_id_idxonorders(user_id);参考RLS 性能