2017-08-07 43 views
1

隔離租戶的一種可能方式是將tenant_id添加到每個表中,並將範圍與該字段的每個請求範圍。是否可以在PostgreSQL中用tenant_id限制所有查詢?

但是你必須非常小心,並把它放在每個SQL查詢中。

我想知道是否有辦法告訴PostgreSQL自動執行該操作?喜歡的東西

scope tenant_id = 'foo' 

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

回答

3

您可以結合使用的觀點與自定義的配置參數,例如:

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查詢使用視圖,而不是表。您必須設置自定義配置參數以使查詢運行:

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) 
相關問題