模式

PostgREST 可以公开一个或多个模式的表、视图和函数。 活动数据库角色 必须对这些模式具有使用权限才能访问它们。

单一模式

要公开单个模式,请在 db-schemas 中指定单个值。

db-schemas = "api"

此模式将添加到每个请求的 search_path 中,使用 事务范围设置

多个模式

要公开多个模式,请在 db-schemas 上指定以逗号分隔的列表。

db-schemas = "tenant1, tenant2"

要切换模式,请使用 Accept-ProfileContent-Profile 标头。

如果您没有指定 Profile 标头,则列表中的第一个模式(此处为 tenant1)将被选为默认模式。

只有选定的模式会被添加到每个请求的 search_path 中。

注意

这些标头基于“通过配置文件进行内容协商”规范:https://www.w3.org/TR/dx-prof-conneg

GET/HEAD

对于 GET 或 HEAD,请使用 Accept-Profile 选择模式。

curl "https://:3000/items" \
  -H "Accept-Profile: tenant2"

其他方法

对于 POST、PATCH、PUT 和 DELETE,请使用 Content-Profile 选择模式。

curl "https://:3000/items" \
  -X POST -H "Content-Type: application/json" \
  -H "Content-Profile: tenant2" \
  -d '{...}'

您也可以为 函数作为 RPCOpenAPI 选择模式。

受限模式

您只能切换到 db-schemas 中包含的模式。使用其他模式会导致错误。

curl "https://:3000/items" \
  -H "Accept-Profile: tenant3"
{
  "code":"PGRST106",
  "details":null,
  "hint":null,
  "message":"The schema must be one of the following: tenant1, tenant2"
}

动态模式

要动态添加模式,可以使用 数据库内配置 以及 配置重新加载模式缓存重新加载。以下是一些操作方法:

  • 如果模式名称有规律,例如 tenant_ 前缀,请执行以下操作:

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';