Skip to main content

Polymorphism in PostGraphilePostGraphile 中的多态支持

Polymorphism in PostgreSQL schemas can take many forms. For PostGraphile to detect and generate GraphQL interfaces and unions (rather than regular object types) from your database tables, you need to provide PostGraphile some hints or instructions; one way to do this is with smart tags. Which smart tags to apply will depend on what shape your data is.

PostgreSQL schema 中的多态建模有多种形式。为了让 PostGraphile 识别数据库表中的多态结构,并据此生成 GraphQL 接口(interface)和联合类型(union),而非普通对象类型,你需要向它提供相应的提示或指令——其中一种方式就是使用 smart tag。具体应用哪些 smart tag,取决于你的数据结构形态。

tip提示

Under the hood, PostGraphile polymorphism is powered by @dataplan/pg's polymorphism; some restrictions may apply to what PostGraphile generates for polymorphic types and fields based on what @dataplan/pg supports. For example, CRUD mutations are not generated for polymorphic types at this time — see instead Custom Mutations.

在底层,PostGraphile 的多态能力由 @dataplan/pg 的多态机制驱动;因此,PostGraphile 为多态类型与字段生成的能力会受限于 @dataplan/pg 当前的支持范围。例如,目前不会为多态类型自动生成 CRUD mutation,如需变更数据,请改用自定义 Mutation。

@interface mode:single@interface mode:single(单表多态)​

In the simplest case you have a single table that represents all of your possible polymorphic types, perhaps using a 'type' column or similar to indicate the underlying type. For this style, you should:

最简单的情况是用一张表来容纳所有可能的多态子类型,通常通过一个“type”列或类似字段来标识底层具体类型。采用这种结构时,你需要:

  • add the @interface smart tag to the table, with mode:single and the name of the type column indicated via the type: parameter.

    为该表添加 @interface smart tag,并指定 mode:single 以及通过 type: 参数指明类型列的列名。

  • add @type smart tags to the table for each possible value of the type column

    为 type 列的每一个可能取值在该表上添加对应的 @type smart tag。

For example you might have a table like this one:

例如,你可能有如下这样一张表:

create type polymorphic.item_type as enum (
'TOPIC',
'POST',
'DIVIDER',
'CHECKLIST',
'CHECKLIST_ITEM'
);

create table polymorphic.single_table_items (
id serial primary key,

-- Rails-style polymorphic column
type polymorphic.item_type not null default 'POST'::polymorphic.item_type,

-- Shared attributes:
parent_id int references polymorphic.single_table_items on delete cascade,
root_topic_id int constraint single_table_items_root_topic_fkey references polymorphic.single_table_items on delete cascade,
position bigint not null default 0,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now(),
is_explicitly_archived bool not null default false,
archived_at timestamptz,

-- Attributes that may be used by one or more item subtypes.
title text,
description text,
note text,
color text
);

To have PostGraphile generate an interface for this table, you might use a comment such as:

为了让 PostGraphile 为该表生成 GraphQL 接口,可以添加如下注释:

comment on table polymorphic.single_table_items is $$
@interface mode:single type:type
@type TOPIC name:SingleTableTopic attributes:title
@type POST name:SingleTablePost attributes:title,description,note
@type DIVIDER name:SingleTableDivider attributes:title,color
@type CHECKLIST name:SingleTableChecklist attributes:title
@type CHECKLIST_ITEM name:SingleTableChecklistItem attributes:description,note
$$;

The @type tags take the value of the type column as the first argument and then accept name: and attributes: arguments; name being the name to create the GraphQL object type with and attributes: to be a comma-separated list of any columns that are specific to this type (and shouldn't be on the main interface).

@type 标签以 type 列的取值作为第一个参数,随后接受 name: 和 attributes: 参数:其中 name 用于指定生成的 GraphQL 对象类型名称,而 attributes: 则以逗号分隔列出仅属于该类型的列(这些列不应出现在主接口上)。

tip提示

The type column doesn't have to be an enum, any string-y type is fine but do ensure that all possible values it can have are declared in your @type smart tags!

type 列不一定要是枚举类型,任何字符串类类型均可;但务必确保它所有可能出现的值都已在 @type smart tag 中声明!

tip提示

For polymorphism to work, your table must have a primary key; we currently do not automatically detect the lack of primary key, so you may receive unexpected results (typically nulls) without one. If you have a view instead of a table, make sure to define a primary key using the @primaryKey smart tag.

要使多态正常工作,表必须拥有主键;PostGraphile 目前不会自动检测缺失主键的情况,缺少主键时可能会返回异常结果(通常是 null)。如果你使用的是视图(view)而非表(table),请务必通过 @primaryKey smart tag 显式声明主键。

@interface mode:relational@interface mode:relational(关联表多态)​

A slightly more complex case is having a table that defines the common fields as above, but then you join in additional data from other tables in a relational manner. This is similar to the above, but we use mode:relational and the @type tags declare the table that each type references rather than the columns that are specific to that type.

稍微复杂一点的场景是:像上面那样用一张主表定义公共字段,再以关系型连接的方式从其他表中关联读取额外数据。这种结构的配置与单表多态类似,但需要使用 mode:relational,且 @type 标签不再列出专属列名,而是通过 references 声明各类型所关联的子表。

For example, for the following set of related relationally-polymorphic tables:

例如,针对下面这组采用关联式多态设计的表:

create table polymorphic.relational_items (
id serial primary key,

-- This column is used to tell us which table we need to join to
type polymorphic.item_type not null default 'POST'::polymorphic.item_type,

-- Shared attributes (also 'id'):
parent_id int references polymorphic.relational_items on delete cascade,
root_topic_id int, -- constraint being created below
position bigint not null default 0,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now(),
is_explicitly_archived bool not null default false,
archived_at timestamptz
);

create table polymorphic.relational_topics (
id int primary key references polymorphic.relational_items,
title text not null
);
alter table polymorphic.relational_items add constraint relational_items_root_topic_fkey foreign key (root_topic_id) references polymorphic.relational_topics on delete cascade;
create table polymorphic.relational_posts (
id int primary key references polymorphic.relational_items,
title text not null,
description text default '-- Enter description here --',
note text
);
create table polymorphic.relational_dividers (
id int primary key references polymorphic.relational_items,
title text,
color text
);
create table polymorphic.relational_checklists (
id int primary key references polymorphic.relational_items,
title text not null
);
create table polymorphic.relational_checklist_items (
id int primary key references polymorphic.relational_items,
description text not null,
note text
);

You might use a comment such as this one:

可以添加如下表注释:

comment on table polymorphic.relational_items is $$
@interface mode:relational type:type
@type TOPIC references:relational_topics
@type POST references:relational_posts
@type DIVIDER references:relational_dividers
@type CHECKLIST references:relational_checklists
@type CHECKLIST_ITEM references:relational_checklist_items
$$;

@interface mode:union@interface mode:union(联合表多态)​

Sometimes you might have multiple independent tables that you want to be part of an interface, for this you can define a composite type that declares the shared attributes, and then add the @interface smart tag to this composite type, with mode:union (this is an SQL union, not a GraphQL union!).

有时你可能希望让多张彼此独立的表共同成为某个接口的成员。此时可以先定义一个声明公共属性的复合类型(composite type),再为该复合类型添加带 mode:union 的 @interface smart tag(注意:这里指的是 SQL 的 union,而非 GraphQL 的 union!)。

For example, imagine that we have a table for AWS applications and a table for GCP applications (and maybe more for other cloud providers):

举例来说,假设我们分别有一张 AWS 应用表和一张 GCP 应用表(后续还可能接入其他云厂商):

create table polymorphic.aws_applications (
id int primary key,
name text not null,
last_deployed timestamptz,
person_id int references polymorphic.people,
organization_id int references polymorphic.organizations,
aws_id text
);

create table polymorphic.gcp_applications (
id int primary key,
name text not null,
last_deployed timestamptz,
person_id int references polymorphic.people,
organization_id int references polymorphic.organizations,
gcp_id text
);

To have all of these tables implement the Application interface, we might add the following to our database:

为了让这些表都实现 Application 接口,可以在数据库中添加如下定义:

-- Declare a composite type to detail the common fields
create type polymorphic.applications as (
id int,
name text,
last_deployed timestamptz
);

-- Mark this composite type as an interface named Application
comment on type polymorphic.applications is $$
@interface mode:union
@name Application
$$;

-- Have our tables implement this interface
comment on table polymorphic.aws_applications is $$
@implements Application
$$;
comment on table polymorphic.gcp_applications is $$
@implements Application
$$;
Cannot return mode:union from functions无法从函数中返回 mode:union 类型

You will not be able to return the mode:union type from a PostgreSQL function. Consider the above example - if we receive {id: 1, name: "Foo", last_deployed: null} how can we know if this came from aws_applications or gcp_applications? Instead, consider using extendSchema.

PostgreSQL 函数无法返回 mode:union 类型。以上述示例为例:如果函数返回 {id: 1, name: "Foo", last_deployed: null},系统根本无从判断它究竟来自 aws_applications 还是 gcp_applications。这类场景请改用 extendSchema。

@unionMember@unionMember(联合类型成员)​

For cases where you want multiple tables that don't necessarily share any fields or relations to be part of a GraphQL union, you can give them the @unionMember smart tag.

如果你希望将多张未必拥有共同字段或 relation 的表纳入同一个 GraphQL 联合类型(union),可以为这些表添加 @unionMember smart tag。

For example, consider these independent tables:

例如,考虑以下两张相互独立的表:

create table polymorphic.people (
person_id serial primary key,
username text not null unique
);

create table polymorphic.organizations (
organization_id serial primary key,
name text not null unique
);

We could define a union that contains them both via:

我们可以通过如下注释定义一个同时包含这两者的联合类型:

comment on table polymorphic.people is $$
@unionMember PersonOrOrganization
$$;
comment on table polymorphic.organizations is $$
@unionMember PersonOrOrganization
$$;

And we could reference this type from an @ref smart tag; for example:

随后即可通过 @ref smart tag 引用该类型,例如:

create table polymorphic.log_entries (
id serial primary key,
person_id int references polymorphic.people on delete cascade,
organization_id int references polymorphic.organizations on delete cascade,
text text not null,
constraint owned_by_person_or_organization check ((person_id is null) <> (organization_id is null))
);

comment on table polymorphic.log_entries is $$
@ref author to:PersonOrOrganization singular
@refVia author via:(person_id)->people(person_id)
@refVia author via:(organization_id)->organizations(organization_id)
$$;

Now LogEntry.author will be a PersonOrOrganization by following the given relationships.

这样一来,LogEntry.author 便会沿着指定的关联关系解析为 PersonOrOrganization 类型。

tip提示

Since the log_entries table only has one reference to people and one to organizations we can use a shorthand for the via:s:

由于 log_entries 表各自只包含一个指向 people 和 organizations 的引用,via: 参数还可以简写如下:

comment on table polymorphic.log_entries is $$
@ref author to:PersonOrOrganization singular
@refVia author via:people
@refVia author via:organizations
$$;