【问题标题】:Is it possible to limit all the queries with tenant_id in PostgreSQL?是否可以在 PostgreSQL 中使用tenant_id 限制所有查询?
【发布时间】:2017-08-07 14:25:40
【问题描述】:

隔离租户的一种可能方法是将tenant_id 添加到每个表中,并使用该字段限定每个请求。

但是您必须非常小心,并将其放入每个 SQL 查询中。

我想知道是否有办法告诉 PostgreSQL 自动执行此操作?类似的东西

scope tenant_id = 'foo'

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

【问题讨论】:

    标签: postgresql multi-tenant


    【解决方案1】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 2011-02-23
      • 2018-12-16
      • 2011-01-28
      • 2016-03-20
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多