是否可以在PostgreSQL中使用tenant_id限制所有查询?

时间:2017-08-07 05:38:01

标签: postgresql multi-tenant

隔离租户的一种可能方法是向每个表添加tenant_id,并使用该字段确定每个请求的范围。

但是你必须非常小心并将其放在每个SQL查询中。

我想知道是否有办法告诉PostgreSQL自动执行此操作?像

这样的东西
scope tenant_id = 'foo'

select * from my_table -- tenant_id = 'foo' should be added automatically

1 个答案:

答案 0 :(得分:5)

您可以将视图与自定义配置参数结合使用,例如:

create table customers_table(id serial primary key, tenant_id int, name text);
insert into customers_table (tenant_id, name) values
(1, 'a'),
(2, 'b'),
(1, 'c'),
(2, 'd');

create view customers as
select *
from customers_table
where tenant_id = current_setting('glb.tenant_id')::int;

在选择查询中使用视图而不是表格。您必须设置自定义配置参数才能运行查询:

select * from customers;

ERROR:  unrecognized configuration parameter "glb.tenant_id"

set glb.tenant_id to 1;
select * from customers;

 id | tenant_id | name 
----+-----------+------
  1 |         1 | a
  3 |         1 | c
(2 rows)
相关问题