模式#
PostgREST可以公开单个或多个模式的表、视图和函数。这个 active database role 必须对架构具有USAGE权限才能访问它们。
单一模式#
要公开单个架构,请在中指定单个值 DB-架构 。
db-schemas = "api"
此架构将添加到 search_path 每个请求都使用 事务作用域设置 。
多个模式#
若要公开多个架构,请在 DB-架构 :
db-schemas = "tenant1, tenant2"
若要切换架构,请使用 Accept-Profile
和 Content-Profile
标题。
如果不指定配置文件头,则列表中的第一个架构 (tenant1
此处)被选为默认模式。
只有选定的架构才会添加到 search_path 每一个请求。
备注
这些标头基于“内容协商按配置文件”规范:https://www.w3.org/TR/dx-prof-conneg
获取/获取#
对于GET或HEAD,使用以下命令选择架构 Accept-Profile
。
curl "http://localhost:3000/items" \
-H "Accept-Profile: tenant2"
其他方法#
对于POST、PATCH、PUT和DELETE,选择模式 Content-Profile
。
curl "http://localhost:3000/items" \
-X POST -H "Content-Type: application/json" \
-H "Content-Profile: tenant2" \
-d '{...}'
受限架构#
您只能切换到中包含的架构 DB-架构 。使用其他架构将导致错误:
curl "http://localhost:3000/items" \
-H "Accept-Profile: tenant3"
{
"code":"PGRST106",
"details":null,
"hint":null,
"message":"The schema must be one of the following: tenant1, tenant2"
}
动态模式#
要动态添加模式,您可以使用 数据库内配置 加 config reloading 和 schema cache reloading 。以下是如何做到这一点的一些选择:
如果架构的名称具有模式,如
tenant_
前缀,DO:
create or replace function postgrest.pre_config()
returns void as $$
select
set_config('pgrst.db_schemas', string_agg(nspname, ','), true)
from pg_namespace
where nspname like 'tenant_%';
$$ language sql;
如果没有命名模式,但它们是使用特定角色创建的 (
CREATE SCHEMA mine AUTHORIZATION joe
),执行以下操作:
create or replace function postgrest.pre_config()
returns void as $$
select
set_config('pgrst.db_schemas', string_agg(nspname, ','), true)
from pg_namespace
where nspowner = 'joe'::regrole;
$$ language sql;
否则,您可能需要创建一个存储允许的模式的表。
create table postgrest.config (schemas text);
create or replace function postgrest.pre_config()
returns void as $$
select
set_config('pgrst.db_schemas', schemas, true)
from postgrest.config;
$$ language sql;
然后,每次添加架构时,请执行以下操作:
NOTIFY pgrst, 'reload config';
NOTIFY pgrst, 'reload schema';