Postgresql Postgres行级安全性插入返回

Postgresql Postgres行级安全性插入返回,postgresql,row-level-security,Postgresql,Row Level Security,给定我的模式中的以下代码段: create table users ( id serial primary key, name text not null ); create table user_groups ( id serial primary key, name text not null ); create table user_user_group ( user_id integer not null references users(id

给定我的模式中的以下代码段:

create table users (
  id   serial primary key,
  name text not null
);

create table user_groups (
  id   serial primary key,
  name text not null
);

create table user_user_group (
  user_id       integer not null references users(id),
  user_group_id integer not null references user_groups(id)
);

grant all on users to staff;
grant all on user_groups to staff;
grant all on user_user_group to staff;

create function can_access_user_group(id integer) returns boolean as $$
  select exists(
    select 1
    from user_user_group
    where user_group_id = id
    and user_id = current_user_id()
  );
$$ language sql stable security invoker;

create function can_access_user(id integer) returns boolean as $$
  select exists(
    select 1
    from user_user_group
    where user_id = id
    and can_access_user_group(user_group_id)
  );
$$ language sql stable security invoker;

alter table users enable row level security;
create policy staff_users_policy
  on users
  to staff
  using (
    can_access_user(id)
  );
请假定
staff
角色和
current\u user\u id()
功能已测试并正常工作。我希望允许“staff”角色在用户组中创建用户,这些用户可以通过
user\u user\u group
表访问。以下语句未通过
员工用户策略

begin;
set local role staff;

with new_user as (
  insert into users (
    name
  ) values (
    'Some name'
  )
  returning id
) 
insert into user_user_group (
  user_id,
  user_group_id
) 
select 
  new_user.id, 
  1 as user_group_id
from new_user;
          
commit;
我可以像这样添加
staff\u insert\u users\u policy

create policy staff_insert_users_policy
  on users
  for insert
  to staff
  with check (
    true
  );
这允许我插入用户,但在
返回id
时失败,我需要新的用户id才能将行添加到
用户组
表中


我理解它失败的原因,但从概念上讲,我如何避免这个问题?我可以为此创建一个“定义者”函数,或者一个有自己策略的新角色,但我希望有一个更直接的方法。

您找到解决此问题的方法了吗?我也有。不,对不起。我最终使用了定义函数和手动检查。好的。我最后也做了同样的事情。你找到解决这个问题的办法了吗?我也有。不,对不起。我最终使用了定义函数和手动检查。好的。我最后也做了同样的事情。