PostgreSQL - 依赖于用户角色的 WHERE 子句中给定的附加条件

PostgreSQL - additional condition over the given in WHERE clause in dependency on user's role

我有一个 table,其中包含 a intb boolean 等列。数据库中的所有用户都具有特权或非特权角色。特权用户可以访问 table 中的所有行,非特权用户 - 只能访问 b 为真的那些行。

因此,当非特权用户执行 SELECTUPDATEDELETE 查询时,它必须保存它的 WHERE 条件,但也过滤所有不是 b.


示例:如果我们在 table 中有:

a | c
--+--
1 | T
2 | T
3 | F
4 | F

并且特权用户执行SELECT FROM table WHERE a > 1,他必须得到

a | c
--+--
2 | T
3 | F
4 | F

而同一查询的非特权用户必须获得

a | c
--+--
2 | T

有什么方法可以使用触发器之类的来实现吗?

如果您有 9.5 及更高版本 - 使用

https://www.postgresql.org/docs/current/static/ddl-rowsecurity.html

In addition to the SQL-standard privilege system available through GRANT, tables can have row security policies that restrict, on a per-user basis, which rows can be returned by normal queries or inserted, updated, or deleted by data modification commands. This feature is also known as Row-Level Security.

一种方法使用一个视图:

create view v_table as
    select t.*
    from table t
    where c = 'F' or
          exists (select 1 from users u where u.user = current_user and u.role = 'privileged');

然后,仅通过视图访问table。