Registry
As you know: PostGraphile builds a GraphQL schema for you by introspecting your
database. What you may not know is that it does this through multiple phases
using the Graphile Build library.
In the gather phase, PostGraphile introspects your database, and builds up a
"registry" of all of the "codecs", "resources" and "relations" that it finds.
Then during the schema phase, it inspects this registry and uses it to decide
what your GraphQL schema should contain.
如你所知,PostGraphile 会通过 introspection 检视你的数据库来构建 GraphQL schema。但你可能不知道的是,它借助 Graphile Build 库分多个阶段完成这一过程。在 gather 阶段,PostGraphile 会对数据库执行 introspection,并将发现的所有“codec”、“resource”和“relation”汇总构建为一个“registry”(注册表);随后在 schema 阶段,它会读取该 registry,据此决定你的 GraphQL schema 中应当包含哪些内容。
When you're just getting started with PostGraphile, it's not very important to understand the registry, you can get away with these basic concepts to help you to understand error messages:
刚上手 PostGraphile 时,你并不需要深入理解 registry,只要掌握以下基本概念就足以看懂报错信息:
-
A
codecrepresents a database type (a scalar, composite, list, domain or range type)codec表示一种数据库类型(标量、复合类型、列表、域类型或范围类型) -
A
resourcerepresents something in the database from which you can pull data (a table, view, materialized view or function)resource表示数据库中能够从中读取数据的对象(表、视图、物化视图或函数) -
A
relationis a uni-directional link from a codec (e.g. a table type) to a resource (e.g. a table itself)relation是从某个 codec(例如表的类型)指向某个 resource(例如表本身)的单向关联
However, once you want to start writing your own plans, for example via
extendSchema, understanding the
registry becomes more important.
不过,一旦你开始编写自己的执行计划(plan),例如通过 extendSchema 扩展 schema,理解 registry 就会变得尤为重要。
CodecsCodec(编解码器)
A "codec" describes a type in your PostgreSQL database. There are built-in codecs for the basic scalars:
“codec”用于描述 PostgreSQL 数据库中的某种类型。系统已为常见的基础标量类型内置了对应的 codec:
import { TYPES } from "postgraphile/@dataplan/pg";
const { int, bool, text /* ... */ } = TYPES;
PostGraphile will automatically generate codecs for all of the types in your database, whether they are scalar, composite (including the underlying type that each of your tables/views/etc have), list, domain, or range types.
PostGraphile 会自动为数据库中的所有类型生成 codec,包括标量类型、复合类型(含每张表、视图等对象自身对应的底层类型)、列表类型、域类型以及范围类型。
PostGraphile automatically names these types after their name in the database
via an inflector. For example, composite types use the classCodecName
inflector.
PostGraphile 会通过 inflector,根据这些类型在数据库中的名称自动为其命名。例如,复合类型使用的就是 classCodecName inflector。
You can read more about codecs (including how to make your own, and what the
built-in scalar codecs are) in the @dataplan/pg documentation:
codecs.
关于 codec 的更多信息(包括如何自定义 codec,以及内置标量 codec 列表),请参阅 @dataplan/pg 文档中的 codecs 章节。
Custom codecs in PostGraphile在 PostGraphile 中自定义 codec
When PostGraphile cannot build a codec for a database type, you can supply one
via the gather phase hook pgCodecs_findPgCodec, then wire it into your
GraphQL schema during the schema phase. Create a plugin, export it, and load
it from your graphile.config.ts preset. The core PgLtreePlugin is a tested
example of this pattern; the following sample embeds its source (renamed to
avoid conflicts).
当 PostGraphile 无法为某种数据库类型自动构建 codec 时,你可以通过 gather 阶段的 hook pgCodecs_findPgCodec 提供一个自定义 codec,然后在 schema 阶段将其接入 GraphQL schema。编写一个插件并导出,再在 graphile.config.ts 的 preset 中加载即可。核心内置的 PgLtreePlugin 就是一个经过验证的范例;以下示例嵌入了它的源码(为避免命名冲突已重命名)。
Click to reveal MyPgLtreePlugin点击展开 MyPgLtreePlugin 源码
import assert from "node:assert";
import type { PgCodec } from "@dataplan/pg";
import { gatherConfig } from "graphile-build";
interface State {
ltreeCodec: PgCodec<string, any, any, any, undefined, any, any>;
ltreeArrayCodec: PgCodec;
}
interface Cache {}
// Optional: declaration merge the plugin name so users get autocomplete in `disablePlugins: [...]`
declare global {
namespace GraphileConfig {
interface Plugins {
MyPgLtreePlugin: true;
}
}
}
export const MyPgLtreePlugin: GraphileConfig.Plugin = {
name: "MyPgLtreePlugin",
// !Hide
version,
gather: gatherConfig<never, State, Cache>({
initialState(cache, { lib }) {
const {
dataplanPg: { listOfCodec },
graphileBuild: { EXPORTABLE },
sql,
} = lib;
const ltreeCodec: PgCodec<string, any, any, any, undefined, any, any> =
EXPORTABLE(
(sql) => ({
name: "ltree",
sqlType: sql`ltree`,
toPg(str) {
return str;
},
fromPg(str) {
return str;
},
executor: null,
attributes: undefined,
}),
[sql],
);
const ltreeArrayCodec = EXPORTABLE(
(listOfCodec, ltreeCodec) => listOfCodec(ltreeCodec),
[listOfCodec, ltreeCodec],
);
return { ltreeCodec, ltreeArrayCodec };
},
hooks: {
async pgCodecs_findPgCodec(info, event) {
// If another plugin has already supplied a codec; skip
if (event.pgCodec) return;
const { serviceName, pgType } = event;
const typname = pgType.typname;
if (typname !== "ltree" && typname !== "_ltree") return;
const ltreeExt = await info.helpers.pgIntrospection.getExtensionByName(
serviceName,
"ltree",
);
if (!ltreeExt || pgType.typnamespace !== ltreeExt.extnamespace) {
return;
} else if (typname === "ltree") {
event.pgCodec = info.state.ltreeCodec;
} else {
assert(typname === "_ltree");
event.pgCodec = info.state.ltreeArrayCodec;
}
},
},
}),
schema: {
hooks: {
init(_, build) {
const codec = build.pgCodecs.ltree;
if (codec) {
// Highly recommended you use your own inflector here, choosing
// `builtin` will mean your users may get conflicts which they cannot
// then resolve through inflection.
const ltreeTypeName = build.inflection.builtin("LTree");
build.registerScalarType(
ltreeTypeName,
{ pgCodec: codec },
() => ({
description: build.wrapDescription(
"Represents an `ltree` hierarchical label tree as outlined in https://www.postgresql.org/docs/current/ltree.html",
"type",
),
// !Hide
// TODO: specifiedByURL: https://postgraphile.org/scalars/ltree
}),
'Adding "LTree" scalar type from MyPgLtreePlugin.',
);
build.setGraphQLTypeForPgCodec(codec, "output", ltreeTypeName);
build.setGraphQLTypeForPgCodec(codec, "input", ltreeTypeName);
}
return _;
},
},
},
};
import { PostGraphileAmberPreset } from "postgraphile/presets/amber";
import { MyPgLtreePlugin } from "./plugins/MyPgLtreePlugin.ts";
const preset: GraphileConfig.Preset = {
extends: [PostGraphileAmberPreset],
plugins: [MyPgLtreePlugin],
};
export default preset;
If you are mapping a list-like database type to a GraphQL scalar, consider whether a dedicated object type (and input object type) provides a clearer schema. Scalars are best for opaque values.
如果你正打算将一个类似列表的数据库类型映射为 GraphQL 标量,不妨考虑改用专门的对象类型(以及 input 对象类型),这样通常能让 schema 结构更清晰。标量类型最适合用来表示无需拆解的不透明值。
For more details on codecs, see the @dataplan/pg codec reference above.
关于 codec 的更多细节,请参阅上文提到的 @dataplan/pg codec 参考文档。
ResourcesResource(数据源)
A "resource" represents something that you can pull data from in your database. Most commonly this is a table, but it also includes views, materialized views and functions. You can even build resources for custom SQL expressions should you wish.
“resource”表示数据库中可用于读取数据的对象。最常见的就是表,此外也涵盖视图、物化视图和函数。如有需要,你甚至还可以基于自定义 SQL 表达式来构建 resource。
PostGraphile automatically builds resources for you based on all your tables, views, materialized views and functions.
PostGraphile 会根据数据库中的所有表、视图、物化视图和函数,自动为你构建对应的 resource。
There are two main classes of resources. "Table-like" resources don't accept
any parameters, you can get resources from them directly using
resource.find(spec)
or
resource.get(spec).
"Function-like" resources require a list of parameters (even an empty list),
and for these you would use
resource.execute(args).
resource 主要分为两大类。“表类型(table-like)”resource 不接受任何参数,可以直接通过 resource.find(spec) 或 resource.get(spec) 从中获取数据;而“函数类型(function-like)”resource 则需要传入参数列表(哪怕是空列表),此时应调用 resource.execute(args)。
You can read more about resources in the @dataplan/pg documentation: resources.
关于 resource 的更多信息,请参阅 @dataplan/pg 文档中的 resources 章节。
RelationsRelation(表间关联)
A "relation" is a uni-directional (one way) relationship from a codec (i.e. type) to a table-like resource (i.e. table). Assuming you have some data for the given codec (whether you got that data from a table, function, or even read it from a file), a relation describes how to get from that to the related records (or record) in the given resource.
“relation”是指从某个 codec(即类型)指向某个表类型 resource(即表)的单向关系。只要你手头拥有该 codec 的数据(无论这些数据来自表、函数,甚至是从文件中读取的),relation 就能描述如何从这份数据出发,查找目标 resource 中与之关联的一条或多条记录。
In general, foreign key constraints will register two relations, one for the referring table (the table on which the foreign key is defined) to the referenced table (this is the "forward" relation, and is always unique) and one from the referenced table back to the referring table (this is the "backward" or "referencee" relation, and may or may not be unique depending on the unique constraints on the referring table).
通常情况下,外键约束会注册两条 relation:一条是从引用表(即定义外键的表)指向被引用表(称为“正向”relation,且始终唯一);另一条则是从被引用表反向指向引用表(称为“反向”或“被引用方”relation,其是否唯一取决于引用表上是否存在唯一约束)。
You can read more about relations in the @dataplan/pg documentation:
relations.
关于 relation 的更多信息,请参阅 @dataplan/pg 文档中的 relations 章节。
RegistryRegistry(注册表)
The registry is the container for codecs, resources, and relations. When you're
writing a plugin, if you have a reference to the build object then you can
access the registry via build.input.pgRegistry. It contains the properties
pgExecutor, pgCodecs, pgResources and pgRelations.
registry 是用于存放 codec、resource 和 relation 的容器。在编写插件时,如果你拿到了 build 对象,就可以通过 build.input.pgRegistry 访问 registry。它包含 pgExecutor、pgCodecs、pgResources 和 pgRelations 这几个属性。
For improved DX, some shortcuts are added to the build object:
build.pgExecutor (the primary executor; most schemas only have one),
build.pgCodecs, build.pgResources, and build.pgRelations.
为了提升开发体验,build 对象上还直接挂载了一些快捷方式:build.pgExecutor(主执行器;大多数 schema 只会有一个)、build.pgCodecs、build.pgResources 以及 build.pgRelations。
If you had a users table then, depending on the inflectors you're using, it's
codec might be build.pgCodecs.users, its resource build.pgResources.users
and its relations a keyed object (hash/map/record) stored at
build.pgRelations.users.
假设你有一张 users 表,根据你所使用的 inflector,它对应的 codec 可能是 build.pgCodecs.users,对应的 resource 是 build.pgResources.users,而它的 relation 则是一个以键索引的对象(hash/map/record),存放在 build.pgRelations.users 中。
You can read more about the registry in the @dataplan/pg documentation:
registry.
关于 registry 的更多信息,请参阅 @dataplan/pg 文档中的 registry 章节。