Skip to main content

Customization Overview

PostGraphile offers a variety of options, in both JavaScript and SQL, for customizing your API. Of course the main thing is to ensure that you have suitable database objects in place (tables, columns, types, constraints, functions, views, indexes, etc.) — PostGraphile should work fine with many different shapes of database, but we do expect you to not shy away from leveraging the powerful features your database offers.

PostGraphile 提供了丰富的 JavaScript 与 SQL 手段,供你按需定制 API。当然,最核心的前提是数据库里要有设计得当的基础对象(表、列、类型、约束、函数、视图、索引等)——PostGraphile 能适配各种形态的数据库结构,但我们也希望你放开手脚,充分利用数据库本身提供的强大特性。

For customization on top of these, you have three primary tools at your disposal:

在此基础之上,你还可以借助三大核心手段进行进一步定制:

Extending in JavaScript使用 JavaScript 进行扩展

If you want to add fields or types from JavaScript or TypeScript, start by learning extendSchema. It is the go-to plugin factory for schema additions.

如果你想通过 JavaScript 或 TypeScript 添加字段或类型,建议先了解 extendSchema——它是扩展 schema 的首选插件工厂。

This page provides an overview of those topics.

本页将对上述主题做一概览。

Database objects数据库对象​

PostGraphile encourages you to focus on the design of your database, and will do its best to automatically extract a best practices GraphQL API from your well-designed database schema. When designing your database schema it’s critical that you use best practices: primary keys, unique and foreign key constraints, indexes, and so on.

PostGraphile 鼓励你专注于数据库本身的设计,并会尽可能从结构良好的数据库 schema 中自动提炼出符合最佳实践的 GraphQL API。因此,在设计数据库 schema 时,遵循主键、唯一约束、外键约束、索引等最佳实践尤为重要。

When you add new entities to your database, assuming that the relevant permissions are GRANT-ed, PostGraphile will generate related fields and types automatically.

只要在数据库中新增实体并为其授予了相应权限(GRANT),PostGraphile 就会自动生成关联的字段和类型。

Tables, views, materialized views and constraints表、视图、物化视图与约束​

PostGraphile will build some of the following for tables, views, and materialized views that it finds in your database:

对于在数据库中扫描到的表、视图和物化视图,PostGraphile 会按需构建以下部分或全部内容:

  • root query fields to fetch all rows,

    用于查询全部记录的根查询字段;

  • root query fields to fetch individual rows using the primary key and any unique constraints you’ve defined,

    基于主键及已定义唯一约束查询单条记录的根查询字段;

  • fields on both the referencing and referenced types that reflect the foreign key constraints you defined in the database, and

    在引用方和被引用方类型上体现数据库外键约束的关联字段;

  • mutation fields to create, update, and delete these records.

    用于创建、更新和删除这些记录的 mutation 字段。

Which of these are added to your schema will be dependent on the permissions (GRANTs) that you have defined in the database, the constraints you’ve defined on the tables, the indexes (primarily this impacts reverse relationships), and your configuration options including your global default behavior (e.g. whether you prefer connections (default) or lists).

最终哪些字段会被加入到 schema 中,取决于你在数据库中定义的权限(GRANT)、表上设置的约束、索引(主要影响反向关联),以及包括全局默认 behavior 在内的配置选项(例如偏好默认使用的 Connection 还是普通列表)。

You can override these default decisions on a global, per table, or per constraint basis using the behavior system, e.g. via smart tags on the relevant entities, or your preset.schema.defaultBehavior configuration setting.

你可以通过 behavior 系统在全局、单张表或单个约束的粒度上覆盖这些默认行为,例如在相关实体上配置 smart tags,或修改 preset.schema.defaultBehavior 配置项。

Add “virtual” constraints to views为视图添加“虚拟”约束

Views and materialized views don’t natively support constraints, so PostGraphile provides a system whereby you can add “virtual constraints” to your view/materialized view so that it acts as if it had primary keys, unique constraints, and foreign key constraints.

视图和物化视图在数据库原生层面并不支持约束,因此 PostGraphile 提供了一套机制,允许你为视图或物化视图添加“虚拟约束”,使其表现得就像拥有主键、唯一约束和外键约束一样。

Learn more about using tables and views to customize your API, and about how foreign key constraints are used to form relations between types in your GraphQL schema.

进一步了解如何利用表和视图定制 API,以及外键约束如何在 GraphQL schema 中构建类型间的 relation。

Functions函数​

When you add a function to the database, by default PostGraphile uses heuristics to figure out how that function should be exposed in your schema. If your function is volatile (the default for a CREATE FUNCTION statement) then PostGraphile will assume that it changes data and will add it as a mutation (this is known as a “custom mutation” function). If you mark your function as STABLE or IMMUTABLE when you define it in the database, PostGraphile will add it to the query operation, either as a top-level field (aka a “custom query” function) or, if it matches a specific set of criteria, as a field on a table type (known as a “computed column” function).

向数据库添加函数后,PostGraphile 默认会根据启发式规则判断该如何将其暴露到 schema 中。如果函数是 volatile(CREATE FUNCTION 语句的默认属性),PostGraphile 会认为它会修改数据,并将其添加为 mutation(即“自定义 mutation”函数)。如果定义函数时将其标记为 STABLE 或 IMMUTABLE,PostGraphile 则会把它添加到 Query 操作下——要么作为顶层字段(即“自定义查询”函数),要么在满足特定条件时作为表类型上的一个字段(即“计算列”函数)。

“Computed column” functions are a misnomer“计算列”函数其实名不副实

“Computed column” functions were originally intended to enable adding of scalars to types based on other attributes of the type, but they grew into so much more and can now return entire collections of related records... However the name “computed column” has stuck, and a suitable replacement has not yet surfaced (the closest being “custom field”). This may be addressed at a later time, but for now you should keep in mind that computed column functions are not limited to the simple scalars you might expect from a ‘column’.

“计算列”函数最初的设计意图,只是根据类型自身的其他属性为其补充标量字段,但后来它的能力不断演进,如今甚至可以返回整组关联记录……尽管如此,“计算列”这个称呼已经沿用下来,目前也还没找到更合适的替代词(最接近的大概是“自定义字段”)。这一命名问题以后或许会调整,但眼下请记住:计算列函数绝不仅限于传统意义上“列”所能返回的简单标量。

Annotations注解​

Annotations come in the form of “descriptions” and “smart tags”. Descriptions are added to the resulting GraphQL types/fields/arguments/etc as documentation (you will be able to read this in GraphiQL, for example). “Smart tags” are simple values that influence the way that PostGraphile and any plugins you are using handle the given database objects to which they are applied. Smart tags are formed of a name which by convention we always prefix with an @, and a value which is either the boolean true, a string, or a list of these.

注解分为“描述(description)”和“smart tag”两种形式。描述会作为说明文档附加到生成的 GraphQL 类型、字段、参数等对象上(例如你可以在 GraphiQL 中查看)。而“smart tag”则是一些简单的值,用于影响 PostGraphile 及所用插件如何处理对应的数据库对象。每个 smart tag 都由两部分组成:一个按惯例以 @ 开头的名称,以及一个取值(布尔值 true、字符串,或由它们构成的列表)。

For example, a @name smart tag can be used to rename any function, table, or view; an @omit tag can similarly be used to hide any field from the API; while a @resultFieldName tag can be used to rename the result of a mutation. Views (which can’t have constraints) can add constraint-like fields by using @foreignKey, @primaryKey or @unique smart tags; these enable the views to function like more fully-featured tables.

例如,@name smart tag 可用于重命名任意函数、表或视图;@omit 标签可用来在 API 中隐藏指定字段;@resultFieldName 标签则能重命名 mutation 的返回结果字段。而对于本身无法定义约束的视图,还可以通过 @foreignKey、@primaryKey 或 @unique 等 smart tag 添加类似约束的字段,让视图也能具备接近完整数据表的功能。

Annotations can be provided through a combination of sources including PostgreSQL comments, JSON tags files, and plugins.

注解可以通过多种来源组合提供,包括 PostgreSQL 注释、JSON 标签文件以及插件。

Adding documentation添加说明文档​

You can change the description of a type or field in your GraphQL schema through annotations. Descriptions are visible in GraphiQL’s documentation panel and may also be visible in your editor and various other locations. By default, PostGraphile will extract all the smart tags from each database COMMENT and use the remainder of the comment for the description of the resource. You can also provide descriptions through the postgraphile.tags.json5 file or through plugins.

你可以通过注解修改 GraphQL schema 中类型或字段的描述。这些描述会显示在 GraphiQL 的文档面板中,也可能呈现在你的编辑器及其他工具里。默认情况下,PostGraphile 会从每条数据库 COMMENT 中提取出所有 smart tag,并将注释余下的内容用作该 resource 的描述;此外,你也可以通过 postgraphile.tags.json5 文件或插件来提供描述。

COMMENT ON TABLE users IS $$
@name people
Represents the people that can log in to our application.
$$;

Learn more about adding descriptions through “smart comments” and postgraphile.tags.json5.

进一步了解如何通过“smart comments” 和 postgraphile.tags.json5 添加描述。

Configuration配置​

PostGraphile is highly configurable and extensible, enabling you to customize it easily to fit your tastes and expand its capability to fit your needs. The starting point for this is your PostGraphile configuration, typically stored into a graphile.config.ts (or .js, .mts, .cjs, ...) file. This file defines your configuration “preset”, and can outline other presets to extend from, plugins to add, and the configuration options to set for these.

PostGraphile 具备极高的可配置性与可扩展性,能让你轻松按团队偏好定制行为,并随需求增长不断拓展功能。这一切的起点是 PostGraphile 的配置文件,通常保存为 graphile.config.ts(或 .js、.mts、.cjs 等)。该文件定义了你的配置“preset”,在其中可以指定要继承的其他 preset、要启用的插件,以及对应的配置选项。

Learn more about configuring PostGraphile.

进一步了解如何配置 PostGraphile。

The configuration options that are available to you in this file will be dependent on the plugins and presets that it uses, for available options see the documentation of the plugins and presets you are using. You may also wish to use TypeScript to explore the options available, or try out the graphile config options command which attempts to use the TypeScript language server to determine which options are available to you.

该文件中可用的配置项取决于你引入的插件和 preset,具体可选项请查阅对应插件和 preset 的文档。你也可以借助 TypeScript 的类型提示来探索可用配置,或者尝试运行 graphile config options 命令——它会尝试利用 TypeScript 语言服务器来列出当前可用的所有配置项。

PresetsPreset(预设)​

Presets combine other presets, plugins, and options together into a convenient JS object that can be easily shared. PostGraphile offers a number of built in presets (and this will likely grow over time) so that you can choose your base behavior, these include:

Preset 将其他 preset、插件和配置项打包为一个便于复用的 JS 对象。PostGraphile 内置了多个开箱即用的 preset(未来还会陆续增加),方便你选择所需的基础行为,主要包括:

  • postgraphile/presets/amber - the base preset containing most of PostGraphile’s functionality; you’ll need this!

    postgraphile/presets/amber —— 包含 PostGraphile 绝大多数核心功能的基础 preset,基本上必不可少!

  • postgraphile/presets/v4 - a preset that eases the transition from PostGraphile V4 to V5 by converting V4’s configuration options to V5’s equivalents, and also amends the defaults used in the Amber preset and adds some additional plugins so that V5 acts much more like V4

    postgraphile/presets/v4 —— 用于帮助项目从 PostGraphile V4 平滑过渡到 V5 的 preset:它会将 V4 的配置项转换为 V5 等价项,调整 Amber preset 中的部分默认值,并额外引入一些插件,使 V5 的行为更贴近 V4。

  • postgraphile/presets/relay - a preset for people who want a beautiful Relay-centric GraphQL schema; in particular this turns off things like primary keys and tries to make it so the system uses GraphQL global object identifiers everywhere

    postgraphile/presets/relay —— 面向希望构建纯正 Relay 风格 GraphQL schema 的用户的 preset;它会关闭基于主键的字段等特性,并尽量让系统在各处统一使用 GraphQL 全局对象标识符。

  • postgraphile/presets/minify - an experimental preset for schema exporting workflows (particularly those targetting serverless) that destructively strips schema descriptions/deprecations and registry metadata to reduce export size

    postgraphile/presets/minify —— 面向 schema 导出工作流(尤其是 Serverless 场景)的实验性 preset,它会破坏性地剥离 schema 的描述、弃用说明以及 registry 元数据,从而大幅减小导出产物的体积。

As mentioned above, your graphile.config.ts (or similar) file itself defines a preset.

如前所述,你的 graphile.config.ts(或同类)配置文件本身就定义了一个 preset。

Extension扩展​

The basic building block of PostGraphile is a plugin: a simple JavaScript object with a name and the ability to hook into various parts of the PostGraphile, Grafast, Grafserv and other project lifecycles. Plugins are incredibly powerful, in fact almost all of the core functionality of PostGraphile is implemented through plugins, and there’s a rich ecosystem of third party plugins that people have built to extend PostGraphile to their taste.

插件是 PostGraphile 最基础的构建单元:它本质上是一个带有名称的普通 JavaScript 对象,能够挂载到 PostGraphile、Grafast、Grafserv 等生命周期的各个环节中。插件的能力非常强大——事实上 PostGraphile 几乎所有核心功能本身就是通过插件实现的,同时社区也围绕它沉淀出了丰富的第三方插件生态,方便你按需扩展。

Plugin factories插件工厂​

Though some plugins (such as inflection plugins) are straightforward, when it comes to extending and augmenting the GraphQL schema you may want to use one of our plugin factories which abstract away the boilerplate so that you cah achieve your goals more rapidly.

虽然部分插件(如命名推导 inflection 插件)写起来很直接,但在扩展或增强 GraphQL schema 时,使用我们提供的插件工厂往往更高效——它们封装了繁琐的样板代码,能帮你更快实现目标。

extendSchema is the main factory you’ll want for adding fields and types to your GraphQL schema; it allows you to use GraphQL SDL to describe your types (e.g. extend type Query { random: Int }) along with Grafast plans (or even traditional GraphQL resolvers) to provide the execution logic for these new fields.

extendSchema 是向 GraphQL schema 添加字段和类型时最常用的插件工厂:你只需使用 GraphQL SDL 描述类型结构(例如 extend type Query { random: Int }),再配合 Grafast 执行计划(甚至传统的 GraphQL resolver)来编写这些新字段的执行逻辑即可。

If you want to augment something that PostGraphile already does, for example to perform an action after a mutation completes, or automatically filter out certain results from a record set, then wrapPlans is worth investigating.

如果你想在 PostGraphile 已有行为的基础上做增强——例如在某次 mutation 执行完成后触发后续操作,或自动过滤结果集中的特定记录——那么 wrapPlans 非常值得一试。

If the nullability in your schema is coming out wrong, changeNullability lets you change the “nullability” of a field, e.g. marking it as nullable or non-nullable

如果生成的 schema 中字段可空性不符合预期,可以通过 changeNullability 来调整字段的“可空性”(例如将其设为可空或非空)。

There are many others; but if they don’t fit your needs then you can read more about writing your own schema plugins.

除此之外还有许多其他插件工厂;如果它们仍无法满足你的需求,可以进一步阅读如何编写自定义 schema 插件。

General guidance通用建议​

Storing data存储数据​

If you need to store data, then your first choice will generally be a table. Adding a table, assuming it has the correct permissions, will automatically add fields in the relevant places, and you can gain more fields in the ways detailed above (foreign key constraints, unique/primary key constraints, additional columns, functions, plugins, etc).

如果需要持久化存储数据,表(table)通常是首选。只要权限配置得当,新增一张表就会在各相关位置自动生成对应字段;随后你还可以结合前文提到的方式继续丰富字段(如外键约束、唯一/主键约束、新增列、函数、插件等)。

Deriving data派生数据​

If you are deriving data from data that you already have stored then you have more choices: view, database function, or schema extension. In general, you should pick whichever you prefer, but be aware of the following:

如果是基于已存储的数据派生新数据,可选方案则更多:视图、数据库函数或 schema 扩展。通常你可以按个人偏好自由选择,但需要注意以下几点:

  • Views cannot accept parameters and require annotations to make them behave more table-like; only use these where table-like behavior is desired (for example when building a versionless facade to some underlying mutable database resource)

    视图无法接收参数,且需要通过注解才能模拟数据表的行为;因此仅在确实需要类表行为时再选用视图(例如为底层可变的数据库 resource 构建一层无版本号的统一门面)。

  • Functions can accept parameters but have significant performance overhead if implemented poorly, so ensure you’re familiar with inlining of PostgreSQL functions and prefer writing your functions in LANGUAGE sql. Procedural programming constructs such as IF and LOOP should generally be avoided in favour of declarative SQL constructs. Functions can also not be INSERT-ed into, UPDATE-d or DELETE-d, though you can expose additional functions that perform this functionality.

    函数支持接收参数,但如果实现不当会带来明显的性能开销,因此请务必了解 PostgreSQL 函数的内联机制,并尽量使用 LANGUAGE sql 编写函数。通常应避免使用 IF、LOOP 等过程式语法,转而采用声明式 SQL 写法。此外,函数无法直接执行 INSERT、UPDATE 或 DELETE 操作,不过你可以额外暴露专用的函数来承担这些写操作。

  • Schema extensions are more powerful than views and functions and give you stronger control over performance (e.g. forcing inlining, or even moving calculations to JS rather than computing in the database), but to master them you need familiarity with JS, SQL, and the Grafast planning system. Also, since they are not in the database, they can only be used by consumers of GraphQL.

    Schema 扩展比视图和函数更加灵活强大,也让你对性能拥有更强的掌控力(例如强制内联,甚至将部分计算从数据库迁到 JS 层处理);但要熟练运用它,你需要同时熟悉 JS、SQL 以及 Grafast 的执行计划体系。另外,由于这类扩展并不存在于数据库中,它们只能供 GraphQL API 的调用方使用。

Functions vs plugins函数与插件的取舍​

For simple scalars (e.g. deriving fullName by concatenating first_name and last_name) it commonly makes sense to use a database function. Otherwise, we recommend that you start with whatever you are most comfortable with. If you start to face performance issues, or you discover the need for functionality that’s not compatible with your chosen pattern, then you should switch to writing a plugin; and you should be able to do this in a way that does not break your schema. Note that both view and function support are achieved via plugins, so anything they can do can also be achieved via a plugin.

对于简单的标量计算(例如将 first_name 和 last_name 拼接为 fullName),使用数据库函数通常就很合适。其他场景下,建议先从自己最顺手的方案入手;一旦后续遇到性能瓶颈,或者发现所选方案无法支持某些需求,再切换为编写插件即可——而且整个迁移过程完全可以做到不破坏对外暴露的 schema。值得一提的是,PostGraphile 对视图和函数的支持本身也是通过插件实现的,因此它们能做的事情,插件全都能做到。

Common tasks常见任务​

Adding a query root field添加 Query 根字段​

Options for creating new root-level query fields include:

创建新的顶层查询字段有以下几种方式:

Adding a field to a table-like type为类表类型添加字段​

(Table-like types are GraphQL types that represent database tables, views, materialized views, or even composite types. Some of the suggestions will only work with certain subsets of these types though.)

(所谓“类表类型”,是指对应数据库表、视图、物化视图乃至复合类型的 GraphQL 类型。不过下面某些做法仅适用于其中的部分类型。)

Adding a field to a function-derived type为函数派生类型添加字段​

We generally recommend against using “anonymous” types in your database — it’s better for functions to returns setof named_type than returns table(...) — but should you choose to use anonymous types anyway, adding a field to these can be achieved by:

我们通常不建议在数据库中使用“匿名”类型——让函数 returns setof named_type 一般比 returns table(...) 更合适——但如果你仍然决定使用匿名类型,可以通过以下方式为其添加字段:

Adding a mutation field添加 Mutation 字段​

Options for adding new mutations include:

新增 mutation 的常见方式包括:

Renaming a field重命名字段​

To rename any field, you can either rename the database object that it is based on, annotate it with a @name smart tag or similar, or use an inflection plugin.

要重命名任意字段,你可以直接重命名它所对应的数据库对象、为其添加 @name 等 smart tag,或者编写一个 inflection 插件。

Removing fields移除字段​

In general it’s better to prevent a field being added in the first place than to remove it after it has been added to the schema. To avoid a field being added to the schema, either remove the corresponding object from your database, revoke the permissions granted on it, or add a @behavior -* smart tag. (Note you can also remove specific behaviors (e.g. @behavior -update).)

通常来说,从一开始就阻止字段生成,比等它进入 schema 后再去移除要好得多。要避免字段被添加到 schema 中,可以删除对应的数据库对象、回收已授予的权限,或者添加 @behavior -* smart tag。(注意:你也可以只移除特定 behavior,例如 @behavior -update。)

Should this not work, you can also explicitly delete fields from your schema.

如果这些方法不适用,你也可以从 schema 中显式删除字段。

Adding documentation添加说明文档​

Database tables, views, materialized views, constraints and more can be commented on using the COMMENT SQL command. Note that each time you issue this command on a given entity it will overwrite the previous comments, so care must be exercised.

你可以使用 SQL 的 COMMENT 命令为数据库表、视图、物化视图、约束等对象添加注释。需要注意,每次对同一个实体执行该命令都会覆盖其原有注释,操作时务必谨慎。

You can also use the smart tags system to load descriptions from a file or plugin to apply to database-derived GraphQL entities.

你也可以借助 smart tags 系统,从外部文件或插件中加载描述信息,并应用到由数据库生成的 GraphQL 实体上。

You can also use a plugin to set descriptions, which is generally useful if you need to set a lot of similar descriptions across your schema. Most entities have a description field that you can overwrite via a graphile-build plugin hook.

此外,还可以通过插件批量设置描述——当你需要为 schema 中的大量实体统一添加相似描述时,这种方式尤为实用。绝大多数实体都带有 description 字段,你可以通过 graphile-build 插件 hook 将其覆盖。

Thanks致谢​

This page exists thanks to the significant effort invested by Jeremy Walker, including much back and forth and iteration. We thank Jeremy for his work on this!

本页面得以成稿,离不开 Jeremy Walker 投入的大量心血与反复打磨。在此对 Jeremy 的贡献表示衷心感谢!