PostgreSQL - 在关系策略中检测到无限递归

Pow*_*der 5 sql postgresql policy row-level-security

数据库中有 3 个表 - 部门、员工、帐户。一个部门有很多员工。Employee 包含列department_id bigintAccount 表包含 columns login varcharemployee_id bigint用于将 Postgres 用户(角色)绑定到 Employee 中的行。

我的目标是让用户仅查看和使用 Employee 的值与department_id用户相同的那些行。

一定有类似的东西:

CREATE POLICY locale_policy ON employee
TO justuser, operator
USING (department_id =
    (SELECT department_id FROM employee WHERE id =
        (SELECT employee_id FROM account WHERE login = CURRENT_USER)
    )
)
Run Code Online (Sandbox Code Playgroud)

但由于 Employee 的子查询,它正在提高infinite recursion detected in policy for relation employee

编辑:关系定义为:

create table department(
    id serial primary key);
create table employee(
    id serial primary key,
    department_id int8 not null references department(id));
create table account(
    id serial primary key,
    login varchar(100) not null unique,
    employee_id int8 not null unique references employee(id));
Run Code Online (Sandbox Code Playgroud)

Pow*_*der 3

好吧,我不知道它有多好,但它对我有用。我找到了一个解决方案,创建一个视图,其中 current_user 的部门 id ,然后检查它是否匹配:

CREATE VIEW curr_department AS
    (SELECT department_id as id FROM employee WHERE id =
        (SELECT employee_id FROM account WHERE login = current_user)
    );

CREATE POLICY locale_policy ON employee
    TO justuser, operator
    USING (department_id =
        (SELECT id FROM curr_department)
    );
Run Code Online (Sandbox Code Playgroud)

  • 我相信它起作用的原因是因为 VIEW 属于执行 CREATE VIEW 命令的任何用户(在本例中,不是“员工”)。所以VIEW不受该政策的约束。 (2认同)