PostgreSQL: 隐藏 table INSERT UPDATE DELETE 函数后面

PostgreSQL: hide table INSERT UPDATE DELETE behind a function

我了解如何使用 GRANT 来控制谁可以对数据库对象执行什么操作。

我有一个案例,在阻止用户直接访问 table.

的同时,拥有修改 table 内容的特定功能会很有用

假设我有一个库存控件 table,我想要一个只修改一列的函数 increase_stock(int)。还有其他函数也可以修改其他列。

我的实际 table 有 ltree 数组和 int 数组,这使得触发器成为一个不受欢迎的选项,因为它没有提供一种直接操作一个字段而不测试每个字段的变化的干净方法。更重要的是,它不会创建我想要的 API。

无论采用哪种方法,我能否创建一个对用户可见的函数,同时该函数访问一个对该用户不可见的 table?

我正在使用 PG 10。

这里有一个 select 的例子。 insert.update 和 delete:

大致相同
t=# create table sd(i int);
CREATE TABLE
t=# insert into sd select 1;
INSERT 0 1
t=# create user nr;
CREATE ROLE
t=# create function s() returns table (i int) as $$ 
begin
return query select * from sd;
end;
$$ language plpgsql security definer;
CREATE FUNCTION

现在以号码登录:

-bash-4.2$ psql -U nr t
psql (9.3.14)
Type "help" for help.

t=> select * from sd;
ERROR:  permission denied for relation sd
t=> select * from s();
 i
---
 1
(1 row)

https://www.postgresql.org/docs/current/static/sql-createfunction.html

SECURITY INVOKER indicates that the function is to be executed with the privileges of the user that calls it. That is the default. SECURITY DEFINER specifies that the function is to be executed with the privileges of the user that owns it.

当然这意味着函数所有者需要对关系的权限