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

时间:2018-01-13 10:21:39

标签: sql postgresql policy rls

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

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

必须有:

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)
    )
)

但是由于员工的子查询,它正在筹集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));

2 个答案:

答案 0 :(得分:1)

嗯,我不知道它有多么体面,但它对我有用。我找到了创建视图的解决方案,其中是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)
    );

答案 1 :(得分:0)

唉,雷克斯特不允许创建角色.. http://rextester.com/QDYC6798

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));
insert into department default values;
insert into department default values;
insert into employee (department_id ) select 1;
insert into employee (department_id ) select 2;
insert into account (login,employee_id) select 'justuser',1;
insert into account (login,employee_id) select 'operator',2;
create role justuser;
create role operator;
set role justuser;
select * from employee;

无法重现。这不是答案 - 只是一个格式化的脚本。解析后我会删除它