Migrating from V4从 V4 迁移
One of the main aims for PostGraphile V5 was to replace the "lookahead engine"
with something better: easier to reason about, easier to maintain and extend,
easier for users to interact with, and more capable of handling GraphQL's
present and future feature set (V4's lookahead doesn't even support interfaces
and unions, let alone @stream, @defer, client controlled nullability, and
everything else that's coming down the GraphQL pipeline).
PostGraphile V5 的核心目标之一,就是用一套更优秀的方案取代原有的“lookahead 引擎”:新引擎需要更易于理解和推理、更便于维护与扩展、对开发者更友好,并能从容应对 GraphQL 当前及未来的各项特性(V4 的 lookahead 机制甚至不支持接口(interface)和联合类型(union),更不用说 @stream、@defer、客户端可控可空性(client-controlled nullability)以及 GraphQL 规范后续演进中的诸多新特性)。
We didn't set out to do so, but ultimately this ended up with us writing our own GraphQL runtime, called Grafast. This runtime is built around a carefully engineered planning phase followed by an highly optimized execution phase. This much more powerful system allowed us to generate much more efficient SQL queries, and to execute requests much faster than in V4, which was already pretty fast!
最初我们并未打算另起炉灶,但最终还是打造了一套自研的 GraphQL 运行时——Grafast。这套运行时围绕“精心设计的规划(planning)阶段 + 高度优化的执行(execution)阶段”构建。得益于这一更加强大的体系,我们不仅能生成高效得多的 SQL 查询,请求执行速度也比本就很快的 V4 更上一层楼!
However, Grafast was completely different (not similar in the slightest) to V4's lookahead engine, and that lookahead engine was the beating heart of V4. Replacing it required us to rebuild the entire stack from scratch on top of these new foundations.
然而,Grafast 与 V4 的 lookahead 引擎截然不同(可以说是毫无相似之处),而 lookahead 引擎恰恰是 V4 的核心心脏。替换掉它,意味着我们必须基于这套全新底座,从零重构整个技术栈。
Since we had to rebuild everything anyway, we decided to fix a large number of
issues that had been bugging us for a while... The plugin system has been
consolidated and transformed, the configuration system has been consolidated
and transformed, some of the smart tags (@omit, @simpleCollections, etc)
have been replaced with behaviors (@behavior), all the plugins have been
rewritten or replaced, the defaults have evolved, ... but I'm getting ahead of
myself.
既然一切都要推倒重来,我们也顺势解决了长久以来困扰团队的诸多积弊:插件系统经过整合与彻底革新,配置体系也统一并重构,部分 smart tag(如 @omit、@simpleCollections 等)被替换为更细粒度的 behavior(@behavior),所有插件均已重写或替代,默认行为也随之演进……不过话说远了,我们言归正传。
If you're reading this, you probably want to know how to take your PostGraphile V4 project and run it in PostGraphile V5 instead with the minimal of fuss. One of the reasons that V5 took so long, other than that we invented an entirely new set of technologies and then rebuilt the entire Graphile GraphQL ecosystem from scratch on top of them, was the amount of effort that we put into trying to minimize the amount of effort it will take you to move to V5.
既然你正在读这篇文档,多半是想了解如何以最小的成本,把现有的 PostGraphile V4 项目迁移到 PostGraphile V5 上运行。V5 之所以开发了这么久,除了我们发明了一整套全新技术并在其上重构了整个 Graphile GraphQL 生态之外,另一个重要原因就是我们投入了大量精力,力求把你迁移到 V5 的工作量降到最低。
Note that there are subpages dedicated to particular plugin/plugin generators that need their own V5 migration strategy.
请注意,针对部分需要独立迁移策略的特定插件或插件生成器,我们还单独准备了专门的子页面。
Let's get started.
下面正式开始。
Upgrade to V5 dependencies升级到 V5 依赖
Many users had package-mismatches and duplicate package issues with PostGraphile
V4, so with V5 most of the core packages are available via
exports - so you can typically
get away with just installing postgraphile and any plugins you need.
在 PostGraphile V4 时期,许多用户都遇到过依赖版本不匹配或重复安装同一包的问题。为此,V5 通过 Node.js 的 exports 机制统一暴露了绝大多数核心包——通常情况下,你只需安装 postgraphile 以及所需的扩展插件即可。
Instead of import ...原写法(import ...) | Use import ...V5 新写法(import ...) |
|---|---|
from 'graphile-build' | `from 'postgraphile/graphile-build'改为 from 'postgraphile/graphile-build' |
from 'graphile-build-pg' | `from 'postgraphile/graphile-build-pg'改为 from 'postgraphile/graphile-build-pg' |
from 'graphql' | `from 'postgraphile/graphql'改为 from 'postgraphile/graphql' |
from 'pg-sql2' | `from 'postgraphile/pg-sql2'改为 from 'postgraphile/pg-sql2' |
from 'graphile-utils' | `from 'postgraphile/utils'改为 from 'postgraphile/utils' |
The same is true for builtins in the new system as well:
新体系中的内置模块同样适用这一规则:
Instead of import ...原写法(import ...) | Use import ...V5 新写法(import ...) |
|---|---|
from 'grafast' | `from 'postgraphile/grafast'改为 from 'postgraphile/grafast' |
from 'grafserv' | `from 'postgraphile/grafserv'改为 from 'postgraphile/grafserv' |
from 'grafserv/express/v4' | `from 'postgraphile/grafserv/express/v4'改为 from 'postgraphile/grafserv/express/v4' |
from '@dataplan/json' | `from 'postgraphile/@dataplan/json'改为 from 'postgraphile/@dataplan/json' |
from '@dataplan/pg' | `from 'postgraphile/@dataplan/pg'改为 from 'postgraphile/@dataplan/pg' |
from '@dataplan/pg/adaptors/pg' | `from 'postgraphile/adaptors/pg'改为 from 'postgraphile/adaptors/pg' |
So if your previous package.json looked like:
因此,如果你的 package.json 原本是这样:
{
"devDependencies": {
"graphql": "^15.0.0",
"graphile-build": "^4.14.1",
"graphile-build-pg": "^4.14.1",
"graphile-utils": "^4.14.1",
"postgraphile": "^4.14.1",
"postgraphile-plugin-connection-filter": "^2.3.0"
}
}
You can remove the extra packages and simply run:
现在可以删掉那些多余的依赖包,只需运行:
yarn add --dev \
postgraphile \
postgraphile-plugin-connection-filter
To get:
最终得到如下精简后的配置:
{
"devDependencies": {
"postgraphile": "^5.0.0",
"postgraphile-plugin-connection-filter": "^3.0.0"
}
}
Basic configuration基础配置
PostGraphile V5 requires a "preset" to be specified; this allows users to start with the best settings for their intended use case without having to read pages of documentation first. It also allows us to evolve the defaults over time without breaking existing users schemas — ultimately meaning we no longer need a "recommended options" section in the docs.
PostGraphile V5 要求必须指定一个 preset(预设配置)。这样用户无需先通读大篇幅文档,就能直接以贴合自身场景的最佳默认配置起步;同时这也让我们得以在不破坏现有用户 schema 的前提下持续演进默认值——也就是说,文档里再也不需要专门列出一节“推荐选项”了。
To achieve this, we've introduced a new module: graphile-config. This module
takes care of the common concerns relating to configuration, in particular:
presets, plugins and options. You store your config into a graphile.config.js
(or .ts, .mjs, .mts) file and this can then be used from the command
line, library mode, or even schema-only mode — they all share the same
configuration.
为此,我们引入了一个新模块:graphile-config。它统一负责配置相关的通用机制,特别是 preset、插件以及各项配置选项。你可以将配置保存在 graphile.config.js(或 .ts、.mjs、.mts)文件中,无论是命令行模式、库集成模式,还是纯 schema 模式,都能直接复用同一份配置。
makeV4PresetmakeV4Preset 兼容预设
To make the transition to this new system easier, we've built a makeV4Preset
preset factory for you that converts a number of the options that you are
familiar with from V4 into their V5 equivalents. To use it, feed your options
into its first argument, and combine it with postgraphile/presets/amber (our
initial preset) to get a completed config:
为了让你更轻松地过渡到这套新配置体系,我们提供了 makeV4Preset preset 工厂函数,能够将你熟悉的许多 V4 选项自动转换为对应的 V5 等效配置。使用时,只需把原来的 V4 选项作为第一个参数传入,再与 postgraphile/presets/amber(我们的基础初始 preset)组合,即可得到一份完整的配置:
import { PostGraphileAmberPreset } from "postgraphile/presets/amber";
import { makeV4Preset } from "postgraphile/presets/v4";
import { makePgService } from "postgraphile/adaptors/pg";
/** @type {GraphileConfig.Preset} */
const preset = {
extends: [
PostGraphileAmberPreset,
makeV4Preset({
/* PUT YOUR V4 OPTIONS HERE, e.g.: */
simpleCollections: "both",
jwtPgTypeIdentifier: '"b"."jwt_token"',
}),
],
pgServices: [
makePgService({
connectionString: process.env.DATABASE_URL,
schemas: ["app_public"],
}),
],
};
export default preset;
Common plugins常用插件
Many of the V5 extension modules are now technically "presets" rather than
"plugins" - plugins go into the plugins list in your configuration, but
presets go into the extends list:
在 V5 中,许多扩展模块从严格意义上讲已经变成了“preset”,而非单纯的“插件”——插件需要放入配置中的 plugins 列表,而 preset 则应放入 extends 列表:
const preset: GraphileConfig.Preset = {
extends: [
makeV4Preset({
/* ... */
}),
SomePreset,
],
plugins: [SomePlugin],
};
export default preset;
Ported:
已完成 V5 移植:
import { PgAggregatesPreset } from '@graphile/pg-aggregates';import { PgManyToManyPreset } from '@graphile-contrib/pg-many-to-many';import { PgOmitArchivedPlugin } from '@graphile-contrib/pg-omit-archived';import { PgOrderByRelatedPlugin } from '@graphile-contrib/pg-order-by-related';import { PostGraphileConnectionFilterPreset } from 'postgraphile-plugin-connection-filter';import { PostGraphileFulltextFilterPlugin } from '@graphile-contrib/postgraphile-plugin-fulltext-filter';
Changed:
包名或用法有调整:
-
is now built in; see the subscriptions docs for more details. Users of the V4 preset can use@graphile/pg-pubsubsimpleSubscriptions: trueas before; those not using it can use the PgV4SimpleSubscriptionsPlugin.现已内置;详情请参阅订阅文档。使用 V4 preset 的用户仍可像以前一样配置@graphile/pg-pubsubsimpleSubscriptions: true;未使用的用户则可以直接启用 PgV4SimpleSubscriptionsPlugin。 -
is renamed:@graphile-contrib/pg-simplify-inflector
import { PgSimplifyInflectionPreset } from '@graphile/simplify-inflection';已更名为:@graphile-contrib/pg-simplify-inflector
import { PgSimplifyInflectionPreset } from '@graphile/simplify-inflection';
Not yet ported:
尚未移植:
@graphile/postgis@graphile/operation-hooks
Need more plugins ported? We need financial support! I'm sure there's a mutually beneficial agreement to be found...
希望加快更多插件的移植进度吗?这离不开资金赞助的支持!相信我们总能找到双赢的合作方式……
Larger example完整配置示例
Here's a larger documented preset with more details:
下面是一个带有详细注释的完整 preset 配置示例:
import { PostGraphileAmberPreset } from "postgraphile/presets/amber";
import { makeV4Preset } from "postgraphile/presets/v4";
// Use the 'pg' module to connect to the database
import { makePgService } from "postgraphile/adaptors/pg";
/** @type {GraphileConfig.Preset} */
const preset = {
extends: [
// The initial PostGraphile V5 preset
PostGraphileAmberPreset,
// Change the options and add/remove plugins based on your V4 configuration:
makeV4Preset({
/* PUT YOUR V4 OPTIONS HERE, e.g.: */
simpleCollections: "both",
jwtPgTypeIdentifier: '"b"."jwt_token"',
appendPlugins: [
/*...*/
],
}),
// Note some plugins are now "presets", e.g.
// `@graphile/simplify-inflection`, those should be listed here instead of `appendPlugins`
],
plugins: [
/*
* If you were using `pluginHook` before, the relevant plugins will need
* listing here instead. You can also move the `appendPlugins` list here
* for consistency if you like.
*/
],
/*
* PostgreSQL database configuration.
*
* If you're using the CLI you can skip this and use the `-c` and `-s`
* options instead, but we advise configuring it here so all the modes of
* running PostGraphile can share it.
*/
pgServices: [
makePgService({
// Database connection string:
connectionString: process.env.DATABASE_URL,
// List of schemas to expose:
schemas: ["app_public"],
// Superuser connection string, only needed if you're using watch mode:
// superuserConnectionString: process.env.SUPERUSER_DATABASE_URL,
}),
],
};
export default preset;
Note that the appendPlugins/prependPlugins/skipPlugins options require
V5-compatible plugins, and pluginHook is no longer supported — please use the
plugins configuration key instead.
请注意,appendPlugins、prependPlugins 和 skipPlugins 选项都要求传入兼容 V5 的插件;同时 pluginHook 已不再支持,请改用配置项中的 plugins 键。
Note also that PgNodeAliasPostGraphile (plugin) no longer exists, so instead
of skipping it with skipPlugins you should add the following to your preset:
另外,PgNodeAliasPostGraphile 插件也已不复存在。如果以前是通过 skipPlugins 跳过它,现在请在你的 preset 中改为添加如下配置:
const preset = {
// ...
schema: {
// ...
pgV4UseTableNameForNodeIdentifier: false,
},
};
Not all of the community's V4 plugins have been ported to V5 at time of writing, but with your help hopefully we can fix that! See the community plugins page for details of which plugins have been ported.
截至撰写本文时,并非所有 V4 社区插件都已完成向 V5 的移植,但如果有大家的参与和贡献,这一现状很快就能改善!各插件的移植进度详情请参阅社区插件页面。
additionalGraphQLContextFromRequestadditionalGraphQLContextFromRequest
You can provide this to makeV4Preset({ additionalGraphQLContextFromRequest }), so no specific action is required.
你可以直接将该选项传给 makeV4Preset({ additionalGraphQLContextFromRequest }),因此无需额外改造。
If you want to do this the V5 way then the replacement is the 'grafast.context' option; please see configuration - context.
如果想改用原生的 V5 写法,可以使用 grafast.context 选项替代;详情请参阅配置参考 - context。
const preset = {
//...
grafast: {
context(ctx) {
// Other servers/transports add different details to `ctx`.
const { req, res } = ctx.node ?? {};
return additionalGraphQLContextFromRequest(req, res);
},
},
};
pgSettingspgSettings
You can provide this to makeV4Preset({ pgSettings }), so no specific action is required.
你可以直接将该选项传给 makeV4Preset({ pgSettings }),因此无需额外改造。
If you want to do this the V5 way then the replacement is to
return a pgSettings key from the GraphQL context returned from your
'grafast.context' configuration, for more details see configuration -
context.
如果想改用原生的 V5 写法,只需在 grafast.context 配置函数返回的 GraphQL 上下文中包含一个 pgSettings 字段即可,详情请参阅配置参考 - context。
const preset = {
//...
grafast: {
context(ctx) {
// Other servers/transports add different details to `ctx`.
const { req } = ctx.node ?? {};
return {
pgSettings: pgSettings(req);
};
},
},
};
V4 options not (yet) supported暂不支持(或已移除)的 V4 选项
TODO: this isn't fully documented, please send PRs with any other options you notice aren't supported!
待完善:目前尚未完整统计所有不受支持的选项,如果你在迁移时发现还有其他未列出的选项,欢迎提交 PR 补充!
-
legacyRelations - this has explicitly been removed from V5, see the Breaking GraphQL schema changes section below.
legacyRelations —— V5 已明确移除该选项,详见下方的GraphQL schema 破坏性变更一节。
-
disableQueryLog - V5 will integrate
@graphile/loggerbut this work hasn't started yetdisableQueryLog —— V5 计划集成
@graphile/logger,但该工作尚未启动 -
operationMessages - this originates from the @graphile/operation-hooks plugin which has not yet been ported to V5
operationMessages —— 该选项来自 @graphile/operation-hooks 插件,该插件目前尚未移植到 V5
Breaking GraphQL schema changesGraphQL schema 破坏性变更
We've done our best to maintain as much compatibility with a V4 GraphQL schema
as possible when you use makeV4Preset(), but some breaking changes persist
(we'd argue they're for the better!). Of course if any of these are critical
issues to you they can all be solved by writing a plugin to shape the GraphQL
API how you need, but we suggest that if possible you accept these new changes.
在使用 makeV4Preset() 时,我们已经尽最大努力保持与 V4 GraphQL schema 的兼容性,但仍保留了少量破坏性变更(我们认为这些改动都是朝着更好的方向演进)。当然,如果其中某项改动对你的业务造成了严重阻碍,你依然可以通过编写插件按需调整 GraphQL API 的形态;不过只要条件允许,我们还是建议接纳这些新变化。
-
The long deprecated "legacy relations" are no longer generated (so the
legacyRelationsconfiguration parameter has been deleted)早已废弃的“旧式 relation(legacy relations)”不再生成(因此
legacyRelations配置参数也已删除) -
Node IDs for bigint columns have changed (specifically numbers under
MAX_SAFE_INTnow have quote marks inside the encoding too)bigint列的 Node ID 编码格式有所变化(具体来说,小于MAX_SAFE_INT的数值在编码内部现在也会带有引号) -
In alignment with the Cursor connections specification, connection edges are nullable and cursors are not. It seems we implemented this the wrong way around in V4.
为了与 Cursor Connections 规范保持一致,Connection 中的 Edge 现改为可空(nullable),而
cursor改为非空(non-nullable)。V4 当年似乎把这两者弄反了。 -
For
fooEdgefields on mutation payloads, theorderByargument is now non-nullable. It still has a default, so this will only affect you if you were explicitly passingnull(which seems unlikely since it's not useful).对于 mutation payload 上的
fooEdge字段,其orderBy参数现改为非空。该参数依然带有默认值,因此只有当你显式传入null时才会受影响(而这本来也没有实际意义,通常不太可能遇到)。 -
The
fooEdgefields on mutation payloads now only exist if the table has a primary key.mutation payload 上的
fooEdge字段现在仅当表拥有主键时才会生成。 -
If you disable
NodePluginthen thedeletedFooIdfield on mutation payloads now will not be added to the schema (it never should have been).如果禁用了
NodePlugin,mutation payload 上的deletedFooId字段现在不会再添加到 schema 中(它本来就不应该在此时出现)。 -
The
byteatype is now natively supported, exposed asBase64EncodedBinary原生支持
bytea类型,在 GraphQL 中映射为Base64EncodedBinary
Many of the above issues will not cause any problems for the vast majority of your operations — an engineer from our sponsor Netflix reported all 4,000 unique queries that their very large and complex V4 internal schema received in Feb 2023 validated successfully against their V5 schema — zero breakage! Despite the query compatibility, you may still need to migrate some types on the client side.
上述绝大多数变化对常见操作都不会造成影响——来自我们赞助商 Netflix 的一位工程师曾反馈,他们那套极其庞大复杂的内部 V4 schema 在 2023 年 2 月收到的全部 4,000 条独立查询,均在 V5 schema 上一次性通过校验,实现了零破坏性迁移!不过尽管查询本身保持兼容,客户端代码中的部分类型定义可能仍需相应调整。
Other changes:
其他变更:
-
The values generated for
cursordiffer. This is not deemed to be a breaking change, as these may change from one release to the next (even patch versions).cursor生成的具体字符串值有所变化。这并不算作破坏性变更,因为cursor的内部格式在任意版本更新(甚至补丁版本)之间都可能发生变动。 -
The behavior of
PageInfo'shasPreviousPageandhasNextPagediffers from V4. In V4 when paginating forwards (viafirstandafterarguments) thehasPreviousPagefield would run an additional subquery to determine if a previous page existed. The Cursor Connections Specification explicitly states you may do this if it's efficient to do so. Since adding a subquery isn't efficient, in V5 we follow the specification and always returnfalseforhasPreviousPagewhen paginating forwards. In general, if you have anaftercursor then you can imply there's probably a previous page, so no need for the system to check. (The same applies tohasNextPagewhen paginating backwards vialastandbeforearguments.) For clarity; when paginating forwards you can usehasNextPageto determine if there is a next page (and should not requesthasPreviousPage); when paginating backwards you should usehasPreviousPageto determine if there is a previous page (and should not requesthasNextPage).PageInfo的hasPreviousPage和hasNextPage行为与 V4 不同。在 V4 中,当向前翻页(通过first和after参数)时,查询hasPreviousPage字段会额外执行一条子查询来判断是否存在上一页。而 Cursor Connections 规范明确指出,在确保高效的前提下才可以这么做。由于额外增加子查询并不高效,V5 选择严格遵循规范:向前翻页时hasPreviousPage始终返回false。通常来说,既然你手中已经有了aftercursor,本身就能推断前面大概率还有数据,无需系统再专门查询验证。(同理,通过last和before参数向后翻页时,hasNextPage也始终返回false。)简单总结:向前翻页时应使用hasNextPage判断是否有下一页(不要再请求hasPreviousPage);向后翻页时则应使用hasPreviousPage判断是否有上一页(不要再请求hasNextPage)。 -
In some circumstances the location where a
nullis returned or an error is thrown may differ slightly between V4 and V5; this will still respect the GraphQL schema though, of course.在某些情况下,V4 与 V5 返回
null或抛出错误的具体字段位置可能略有差异;不过当然,一切行为依然严格符合 GraphQL schema 约束。 -
PgIndexBehaviorsPlugin(the V5 equivalent of--no-ignore-indexes) now only removes the backwards ("has many") relation when a relation is unindexed, since the forwards ("belongs to") relation is always indexedPgIndexBehaviorsPlugin(V5 中对应--no-ignore-indexes的插件)现在在 relation 缺少索引时,只会移除反向(“has many”)relation,因为正向(“belongs to”)relation 总是存在索引的
Smart tag changesSmart tag 变更
Despite the following changes, if you're using makeV4Preset then you should
not need to take any action — the established V4 behavior should be
automatically emulated.
尽管有如下调整,但如果你使用了 makeV4Preset,通常无需手动修改任何内容——原有的 V4 行为会被自动模拟兼容。
-
The
@uniqueKeysmart tag is no more; the V4 preset converts it to@unique ...|@behavior -single -update -deletefor you.@uniqueKeysmart tag 已被移除;V4 preset 会自动将其转换为@unique ...|@behavior -single -update -delete。 -
The
@foreignKeysmart tag must reference a unique constraint or primary key; the V4 preset automatically setspgFakeConstraintsAutofixForeignKeyUniqueness: truewhich creates thisuniquefor you (via a smart tag) and gives it the relevant behaviors so that it doesn't turn into more fields/arguments/etc.@foreignKeysmart tag 现在必须指向唯一约束或主键;V4 preset 会自动启用pgFakeConstraintsAutofixForeignKeyUniqueness: true,通过 smart tag 为你补全所需的unique声明,并附带相应的 behavior 设置,从而避免额外生成多余的字段、参数等。
The behavior system gives much finer grained control over which things should/should not be exposed in the schema, and how. If you use the V4 preset then we'll automatically translate the old smart tags into their behavior equivalents, so you shouldn't need to worry too much about this right now. We do advise that you migrate to the behavior system though, it's much more powerful.
behavior 系统能够对 schema 中哪些内容该暴露、哪些不该暴露以及如何暴露提供精细得多的控制。只要你使用了 V4 preset,系统就会自动把旧版 smart tag 翻译成等效的 behavior,因此目前不必为此过多操心。不过我们仍建议尽快迁移到原生的 behavior 系统,它的能力要强大得多。
Running运行方式
CLICLI 命令行
You can run V5 with the postgraphile (or pgl) command. This command
automatically reads the graphile.config.js file; you should use that for
advanced configuration of the PostGraphile CLI rather than sending loads of CLI
flags — this enables us to keep the documentation tighter (documenting just one
set of options rather than 4), gives you auto-complete (if your editor supports
it) on the options, allows you to easily add comments on why the various
options are enabled, and makes it easier to transition between CLI, library and
schema-only modes.
在 V5 中可以通过 postgraphile(或简写 pgl)命令直接启动服务。该命令会自动读取 graphile.config.js 配置文件;建议将高级配置写入此文件,而非在命令行堆砌大量参数。这样做有多重好处:文档可以更加精简统一(只需维护一套配置说明,而不必分成 4 套),在支持类型的编辑器中还能获得配置项自动补全,方便在配置中写明启用各选项的原因注释,同时也能让 CLI 模式、库集成模式与纯 schema 模式之间的切换变得更加顺畅。
Currently the main options are:
目前主要的命令行参数如下:
-
-P- the preset to use, e.g.-P postgraphile/presets/amber(or-P pgl/amberif you're usingpgl)-P—— 指定使用的 preset,例如-P postgraphile/presets/amber(使用pgl命令时也可简写为-P pgl/amber) -
-p- the port to listen on; if not set then it will try and use5678but will fallback to a system-assigned port so be sure to set this in production!-p—— 指定监听端口;若未设置,默认会尝试使用5678,但如果端口被占用会自动回退到系统分配的随机端口,因此生产环境务必显式指定! -
-n- the host to listen on; defaults to 'localhost' (you may want to change to '0.0.0.0' in Docker or similar environments)-n—— 指定监听主机地址,默认为 'localhost'(在 Docker 等容器环境中通常需要改为 '0.0.0.0') -
-c postgres://...- your connection string (same as in V4)-c postgres://...—— 数据库连接字符串(与 V4 相同) -
-S postgres://...- your superuser connection string (replaces V4's-C/--owner-connectionflag)-S postgres://...—— 超级用户连接字符串(替代 V4 中的-C/--owner-connection参数) -
-s app_public- your list of PostgreSQL schemas (same as in V4)-s app_public—— 要暴露的 PostgreSQL schema 列表(与 V4 相同) -
-e- enable "explain" - this allows Ruru (formerly called PostGraphiQL) to render the operation plan and SQL queries that were executed-e—— 启用“explain”模式,让 Ruru(原 PostGraphiQL)能够展示操作执行计划以及实际执行的 SQL 查询 -
-C- the config file to load; if not set we'll try and loadgraphile.config.js(or similar with different extensions) but won't raise an error if it doesn't exist-C—— 指定要加载的配置文件路径;若未指定,默认会尝试加载graphile.config.js(或其他支持的扩展名),即使文件不存在也不会报错
Example:
示例:
postgraphile -P postgraphile/presets/amber -c postgres:///my_db_name -s public -e
# or: pgl -P pgl/amber -c postgres:///my_db_name -s public -e
Library mode库集成模式(Library mode)
Load your config from your graphile.config.js file:
首先从 graphile.config.js 文件中加载配置:
import preset from "./graphile.config.js";
Then feed your preset into the
postgraphile function to get a PostGraphile instance (pgl):
然后将 preset 传入 postgraphile 函数,创建一个 PostGraphile 实例(pgl):
const pgl = postgraphile(preset);
In V4 this would have been a middleware, but in V5 we let Grafserv handle
the webserver portions (rather than PostGraphile having its own internal
server), this allows us to provide deep integration with the various JS
webservers (much better than we had in V4!). This has, however, necessitated a
different approach, so instead of a middleware the result of calling
postgraphile() is a PostGraphile instance which provides a collection of
helper methods.
在 V4 中这一步会直接返回一个中间件,但在 V5 中,Web 服务相关的职责已交由 Grafserv 处理(不再由 PostGraphile 内置服务器),从而能够与各类 JS Web 框架实现深度集成(远胜于 V4 时的支持)。这也带来了使用方式的变化:调用 postgraphile() 不再返回中间件,而是返回一个提供了一系列辅助方法的 PostGraphile 实例。
We'll be using the pgl.createServ() helper in a moment, but first load the
correct Grafserv adaptor for the JS server that you're using:
接下来我们会用到 pgl.createServ() 辅助方法;但在此之前,请先加载与你所用的 JS 服务器对应的 Grafserv 适配器:
import { grafserv } from "grafserv/node";
// OR: import { grafserv } from "grafserv/express/v4";
// OR: import { grafserv } from "grafserv/koa/v2";
// OR: import { grafserv } from "grafserv/fastify/v4";
// etc
Then feed this into pgl.createServ to get a serv Grafserv instance:
然后将其传入 pgl.createServ,获取 Grafserv 实例 serv:
const serv = pgl.createServ(grafserv);
Finally mount the serv instance into your server of choice using the API your
chosen Grafserv adaptor recommends (typically serv.addTo(...)):
最后,按照所选 Grafserv 适配器推荐的 API(通常是 serv.addTo(...))将 serv 实例挂载到你的服务器中:
import { createServer } from "node:http";
const server = createServer();
server.on("error", (e) => console.error(e));
serv.addTo(server);
server.listen(preset.grafserv?.port ?? 5678);
Let's pull this all together to see an example using the Node built-in HTTP server:
下面把这些步骤串联起来,看一个使用 Node 内置 HTTP 服务器的完整示例:
import preset from "./graphile.config.js";
import { postgraphile } from "postgraphile";
import { grafserv } from "grafserv/node"; // Adaptor for Node's HTTP server
import { createServer } from "node:http";
// Create an HTTP server (with error handler)
const server = createServer();
server.on("error", (e) => console.error(e));
// Create a PostGraphile instance (pgl)
const pgl = postgraphile(preset);
// Create a Grafserv (server adaptor) instance for this PostGraphile instance
const serv = pgl.createServ(grafserv);
// Attach a request handler to the server
serv.addTo(server);
// Start the server
server.listen(preset.grafserv?.port ?? 5678);
Node.js' http.createServer() does not need to be passed a request handler -
you can attach one later via server.on('request', handler) which is exactly
what we do behind the scenes in the example above. The reason for this approach
is that it gives us a chance to also add a server.on('upgrade', ...) handler
for dealing with websockets if preset.grafserv.websockets is true.
Node.js 的 http.createServer() 并不需要在创建时传入请求处理函数——你完全可以在之后通过 server.on('request', handler) 挂载处理器,上面示例的底层正是这样做的。采用这种方式的原因在于,当 preset.grafserv.websockets 为 true 时,我们还能借此挂载 server.on('upgrade', ...) 处理器来接管 WebSocket 连接。
The above code might differ significantly depending on which webserver
framework you're using. In V4 we tried to support as many servers as possible
by reducing everything to the lowest common denominator: the Node HTTP req
and res objects. This made it easy to add the middleware, but made it
challenging for you to deeply integrate with the various middleware and
capabilities in your webserver of choice. In V5, we have created an independent
abstraction over HTTP requests which Grafserv handles, and then we provide
different adaptors (or you can write your own!) to convert back and forth
between your webserver framework and our internal request abstractions.
根据你使用的 Web 框架不同,上述接入代码可能会有较大差异。在 V4 中,我们曾试图通过“求最小公约数”的方式(即统一基于 Node HTTP 的 req 和 res 对象)来兼容尽可能多的服务器;这种方式虽然挂载中间件很简单,却很难让你与所选框架自身的中间件及特性进行深度集成。而在 V5 中,我们面向 HTTP 请求打造了一层由 Grafserv 处理的独立抽象,并提供各类适配器(你也可以自行编写!)负责在你的 Web 框架与这套内部请求抽象之间完成双向转换。
Schema only mode纯 schema 模式(Schema-only mode)
createPostGraphileSchema is now just makeSchema (and can be imported from
postgraphile or graphile-build — your choice). It only accepts one argument
now — the preset that you'd load from your graphile.config.js (or similar)
file:
createPostGraphileSchema 现在更名为简洁的 makeSchema(可从 postgraphile 或 graphile-build 导入,任选其一)。它现在只接受一个参数,即你从 graphile.config.js(或同类配置文件)中加载的 preset:
import { makeSchema } from "postgraphile";
import preset from "./graphile.config.js";
const { schema, resolvedPreset } = await makeSchema(preset);
There is no need for withPostGraphileContext any more; the context no longer
has a lifecycle that needs to be carefully managed. Just run the query through
grafast as you normally would through graphql.
不再需要 withPostGraphileContext 了;上下文不再拥有需要小心翼翼管理的生命周期。只需像平时调用 graphql 一样,直接通过 grafast 执行查询即可。
The context will still need to be generated however. The easy option is to
have this done automatically by passing the resolvedPreset and a
requestContext object as part of the args to your grafast call:
不过 context 仍然需要生成。最省事的做法是在调用 grafast 时,把 resolvedPreset 和一个 requestContext 对象一并传入参数中,由系统自动完成构建:
import { grafast } from "grafast";
import { makeSchema } from "postgraphile";
import preset from "./graphile.config.js";
const { schema, resolvedPreset } = await makeSchema(preset);
const args = {
schema,
resolvedPreset,
requestContext: {},
source: /* GraphQL */ `
query MyQuery {
__typename
}
`,
};
const result = await grafast(args);
console.dir(result);
Alternatively, you can use the hookArgs method to hook the execution args and
attach all the relevant context data to it based on your preset and its
plugins. This is somewhat more involved, please see the schema only
usage documentation for that.
或者,你也可以使用 hookArgs 方法对执行参数进行 hook,根据你的 preset 及其插件将所有相关的上下文数据挂载上去。这种方式相对复杂一些,具体请参阅纯 schema 用法文档。
Server服务端(Server)
PostGraphile's HTTP server has been replaced with Grafserv, our new ultra-fast general purpose Grafast-powered GraphQL server. Currently this doesn't support the same hooks that V4's server did, but we can certainly extend the hooks support over time. If there's a particular hook you need, please reach out.
PostGraphile 原有的 HTTP 服务器已被替换为 Grafserv——我们全新打造、基于 Grafast 的超快通用 GraphQL 服务器。目前它尚未支持 V4 服务器曾提供的全部 hook,但我们后续可以逐步扩展完善。如果你急需某个特定的 hook,欢迎随时联系我们。
GraphiQLGraphiQL 调试界面
Our beloved PostGraphiQL has been transformed into a more modern general purpose GraphiQL called Ruru. This still integrates into the server, but you can also run it directly from the command line now too! It doesn't have a plugin system yet, but it will 😁
大家熟悉的 PostGraphiQL 如今已蜕变为更现代化的通用 GraphiQL 工具,名为 Ruru。它依然内置集成在服务端中,但现在也可以直接从命令行独立启动!目前它还暂不支持插件系统,不过很快就会有的 😁
You can try ruru out against any GraphQL API (not only those made by PostGraphile) via:
你可以用如下命令对任意 GraphQL API(不限于 PostGraphile 构建的服务)体验 Ruru:
npx ruru -PSe http://localhost:5678/graphql
Plugins插件机制(Plugins)
The plugin architecture has been transformed: whereas plugins previously were
functions, they are now declarative objects. For example a plugin that adds the
Query.four field might have looked like this in V4:
插件架构已发生根本变革:过去插件是函数形式,如今则改为声明式对象。例如,下面这个用于添加 Query.four 字段的插件在 V4 中可能长这样:
// Version 4 example; will not work with V5!
module.exports = (builder) => {
builder.hook("GraphQLObjectType:fields", (fields, build, context) => {
const {
graphql: { GraphQLInt },
} = build;
const { Self } = context;
if (Self.name !== "Query") return fields;
return build.extend(
fields,
{
four: {
type: GraphQLInt,
resolve() {
return 4;
},
},
},
"Adding Query.four",
);
});
};
In V5 the equivalent would be:
而在 V5 中,对应的写法则是:
const { constant } = require("grafast");
module.exports = {
name: "AddQueryFourFieldPlugin",
version: "0.0.0",
schema: {
hooks: {
GraphQLObjectType_fields(fields, build, context) {
const {
graphql: { GraphQLInt },
} = build;
const { Self } = context;
if (Self.name !== "Query") return fields;
return build.extend(
fields,
{
four: {
type: GraphQLInt,
plan() {
return constant(4);
},
},
},
"Adding Query.four",
);
},
},
},
};
The callback itself is very similar, the hook name has been renamed to use
underscores instead of colons (GraphQLObjectType:fields ->
GraphQLObjectType_fields), and rather than explicitly calling a hook
function to register it, it's implicitly registered by being part of the plugin
object.
回调函数本身非常相似,变化在于 hook 名称从冒号分隔改为了下划线分隔(GraphQLObjectType:fields -> GraphQLObjectType_fields),并且不再需要显式调用 hook 函数来注册——只需将其作为插件对象的一部分,即可隐式完成注册。
This new structure allows the system to learn more about the plugin before actually running it, and can improve the debugging messages when things go wrong.
这种新结构让系统能够在真正执行插件之前获取更多元信息,从而在出错时提供更清晰的调试提示。
Keep in mind that we no longer have the lookahead system so
addArgDataGenerator and its ilk no longer exist, instead we declare
Grafast plan resolvers.
请记住,V5 已不再使用 lookahead 机制,因此 addArgDataGenerator 及其相关 API 均已不复存在,取而代之的是声明 Grafast plan resolver。
Plans, not resolvers使用 Plan,而非 resolver
The new system uses Grafast which has a plan based system, so
rather than writing traditional GraphQL resolvers for each field, you will write
Grafast plan resolvers. This makes the system a lot more powerful and is a
lot more intuitive than our lookahead system once you've spent a little time
learning it. It also completely removes the need for old awkward-to-use
directives such as @pgQuery and @requires! (See
extendSchema migration for details on
migrating these directives.)
新体系底层基于 Grafast 的执行计划模型,因此你不再需要为每个字段编写传统的 GraphQL resolver,而是编写 Grafast plan resolver。这不仅让整套系统强大得多,而且只要花一点时间上手,就会发现它比之前的 lookahead 机制直观得多。同时,它也彻底消除了过去像 @pgQuery 和 @requires 这类用起来颇为别扭的指令!(关于迁移这些指令的详情,请参阅 extendSchema 迁移指南。)
IntrospectionIntrospection(数据库内省)
build.pgIntrospectionResultsByKind is no more; instead we have a new library
pg-introspection that takes care of introspection and has parts of the
PostgreSQL documentation built in via TypeScript hints.
build.pgIntrospectionResultsByKind 已被移除;取而代之的是全新推出的 pg-introspection 库,专门负责数据库 introspection,并通过 TypeScript 提示信息内嵌了部分 PostgreSQL 官方文档说明。
The schema build process has been split into two phases:
schema 的构建过程现已拆分为两个阶段:
-
gather: looks at the introspection results and uses them to generate resources, codecs, relations and behaviors (the four building blocks)gather:读取 introspection 结果,并据此生成 resource、codec、relation 和 behavior(这四大基础构建块) -
schema: looks at these resources, codecs, relations and behaviors and generates a GraphQL schema from themschema:根据上述 resource、codec、relation 和 behavior,自动生成最终的 GraphQL schema
Generally introspection data is not available during the schema phase; which
also means that you can manually write your own
resources/codecs/relations/behaviors and have a GraphQL schema autogenerated by
them independent of what your PostgreSQL schema actually is!
通常情况下,schema 阶段是无法访问 introspection 数据的;这也意味着你可以完全脱离实际的 PostgreSQL schema,手动编写自己的 resource、codec、relation 和 behavior,由系统自动生成对应的 GraphQL schema!
Introspection cacheIntrospection 缓存
There is no introspection cache any more, so no --read-cache, --write-cache,
readCache or writeCache. Instead you can build the GraphQL schema and then
export it as executable code using
graphile-export. In production you simply run this exported
code — there's no need for database introspection, schema building plugins,
etc — and you instantly get your schema without the complexities (or
dependencies!) required in building it dynamically.
V5 不再提供 introspection 缓存功能,因此 --read-cache、--write-cache、readCache 和 writeCache 均已取消。作为替代方案,你可以先构建好 GraphQL schema,再使用 graphile-export 将其导出为可执行代码。在生产环境中只需直接运行这份导出的代码——无需数据库 introspection,也无需加载构建 schema 的各类插件——即可瞬间拿到完整的 schema,彻底省去动态构建带来的复杂度与依赖开销。
buildSchema
buildSchema is now synchronous — you need to run the asynchronous gather phase
first. The arguments have also changed: first is the preset (this encompasses
the list of plugins which was previously the first argument, and any settings
which were previously the second argument), second comes the result of gather
and finally comes the shared object which contains inflection.
buildSchema 现已变为同步函数——你需要先执行异步的 gather 阶段。它的参数也发生了变化:第一个参数是 preset(涵盖了过去作为第一参数的插件列表以及作为第二参数的各项配置),第二个参数是 gather 的输出结果,最后一个参数是包含 inflection 的共享对象。
import { resolvePreset } from "graphile-config";
import { buildInflection, gather, buildSchema } from "graphile-build";
import preset from "./graphile.config.js";
const resolvedPreset = resolvePreset(preset);
const shared = { inflection: buildInflection(resolvedPreset) };
const input = await gather(resolvedPreset, shared);
const schema = buildSchema(resolvedPreset, input, shared);
postgraphile-core
postgraphile-core is no more (look ma, I'm a poet!); here's how to replace
createPostGraphileSchema:
postgraphile-core 现已不复存在(英文原文还押上了韵!);下面展示如何替代原有的 createPostGraphileSchema:
Before:
迁移前:
import { createPostGraphileSchema } from "postgraphile-core";
// ...
const schema = await createPostGraphileSchema(DATABASE_URL, "public", {
// options
});
After:
迁移后:
import { makeSchema } from "postgraphile";
import preset from "./graphile.config.js";
const { schema, resolvedPreset } = await makeSchema(preset);
Module landscape模块全景
In PostGraphile V4 the main modules you'd deal with were:
在 PostGraphile V4 中,日常开发主要会接触到以下模块:
-
postgraphile- orchestration layer and CLI/server/middleware for our GraphQL schema, pluspluginHook"server plugins" functionality, and the home of "PostGraphiQL" our embedded PostGraphile-flavoured GraphiQL.postgraphile—— 负责 GraphQL schema 的编排层以及 CLI、服务器与中间件功能,还包含pluginHook的“服务端插件”机制,并内置了 PostGraphile 定制版 GraphiQL(即“PostGraphiQL”)。 -
postgraphile-core- integration layer between thepostgraphilemodule and thegraphile-buildsystem that builds our GraphQL schema.postgraphile-core—— 连接postgraphile模块与负责构建 GraphQL schema 的graphile-build系统的集成层。 -
graphile-build- contains the schema plugin system, ability to build a GraphQL schema from plugins, basic plugins for all GraphQL schemas, and of course the complex lookahead system. Nothing specific to databases at all.graphile-build—— 提供 schema 插件系统、基于插件构建 GraphQL schema 的能力、通用于所有 GraphQL schema 的基础插件,以及那套复杂的 lookahead 机制;本身完全不涉及数据库。 -
graphile-build-pg- a collection of plugins forgraphile-buildthat teach it about PostgreSQL databases, including introspecting the database and generating all the GraphQL types/fields/etc and their resolvers and look-ahead informationgraphile-build-pg—— 一组为graphile-build赋能的 PostgreSQL 插件集合,负责执行数据库 introspection,并生成对应的 GraphQL 类型、字段及其 resolver 和 lookahead 信息。 -
pg-sql2- build SQL via template literals.pg-sql2—— 通过模板字符串安全地构建 SQL 语句。 -
graphile-utils- a collection of plugin generators to help you extend yourgraphile-engine-based schemagraphile-utils—— 一组插件生成器集合,帮助你便捷地扩展基于graphile-engine构建的 schema。
In PostGraphile V5, we have split things up into more packages that each have a specific focus:
在 PostGraphile V5 中,我们将体系拆分为更多职责单一的独立包:
-
postgraphile- much thinner now, acts as just the orchestration layer and CLIpostgraphile—— 如今变得轻量许多,仅作为上层编排与 CLI 入口 -
graphile-config- system for managing presets and pluginsgraphile-config—— 统一管理 preset 与插件的配置系统 -
grafserv- our Grafast optimized Node.js webserver interface layer - replaces the server/middleware that was previously inpostgraphilegrafserv—— 专为 Grafast 优化的 Node.js Web 服务器适配层,取代了此前内置在postgraphile中的服务器与中间件 -
grafast- the runtime for our GraphQL schemas - performs planning and execution of GraphQL requests - replaces the "lookahead" system that was previously ingraphile-build; not related to automatically building a GraphQL schema; completely generic - has no knowledge of databasesgrafast—— GraphQL schema 的运行时引擎,负责 GraphQL 请求的执行规划(planning)与运行(execution);它取代了此前位于graphile-build中的 lookahead 系统,本身与自动构建 schema 无关,且完全通用、对数据库一无所知 -
@dataplan/pg- "step classes" for Grafast to use to communicate with PostgreSQL databases; not related to automatically building a GraphQL schema@dataplan/pg—— 供 Grafast 与 PostgreSQL 数据库交互的“step 类”;本身不涉及自动构建 GraphQL schema -
@dataplan/json- "step classes" for Grafast to use to parse/stringify JSON@dataplan/json—— 供 Grafast 用于解析和序列化 JSON 的“step 类” -
ruru- our Grafast enhanced GraphiQL distribution that can either be served bygrafservdirectly or used standalone on the CLIruru—— 基于 Grafast 增强的 GraphiQL 发行版,既可由grafserv直接托管,也能通过命令行独立运行 -
ruru-components- the underlying React components used inrurururu-components——ruru底层所依赖的 React 组件库 -
graphile-build- ability to build a GraphQL schema fromgraphile-configplugins via thegatherandschemaphases, basic plugins for all GraphQL schemasgraphile-build—— 支持通过gather和schema两个阶段,基于graphile-config插件构建 GraphQL schema,并提供面向所有 GraphQL schema 的基础插件 -
graphile-build-pg- a collection of plugins forgraphile-buildthat teach it about PostgreSQL databases, including introspecting the database and generating all the GraphQL types/fields/etc and their plans.graphile-build-pg—— 一组为graphile-build赋能的 PostgreSQL 插件集合,负责数据库 introspection,并生成各类 GraphQL 类型、字段及其 plan。 -
pg-introspection- a strongly typed PostgreSQL introspection librarypg-introspection—— 一个强类型的 PostgreSQL introspection 库 -
pg-sql2- build SQL via template literals.pg-sql2—— 通过模板字符串安全地构建 SQL 语句。 -
graphile-export- ability to export an in-memory PostGraphile GraphQL schema to executable code that can be written to a filegraphile-export—— 能够将内存中的 PostGraphile GraphQL schema 导出为可写入文件的可执行代码 -
graphile- swiss army knife CLI with utilities for dealing with everything elsegraphile—— 瑞士军刀式的通用 CLI,内置处理其余各类任务的实用工具 -
graphile-utils- a collection of plugin generators to help you extend yourgraphile-build-based schemagraphile-utils—— 一组插件生成器集合,帮助你便捷地扩展基于graphile-build构建的 schema -
eslint-plugin-graphile-export- ESLint plugin to help ensure your code is compatible with being exported viagraphile-exporteslint-plugin-graphile-export—— ESLint 插件,用于检查并确保你的代码兼容graphile-export导出机制
One major advantage of this approach is that when you export your GraphQL schema as executable code, very few of these dependencies will be needed, making your runtime dependencies much smaller. Another advantage is that it increases the audience for a lot of these modules, for example grafast contains a drop-in replacement for graphql's execute method and can result in much faster GraphQL schemas even without going anywhere near schema autogeneration. A larger audience means more eyes on the code and ultimately higher quality software for everyone.
采用这种拆分设计的一大优势在于:当你把 GraphQL schema 导出为可执行代码后,运行时真正需要的依赖包会非常少,从而大幅缩减生产环境依赖体积。另一大优势则是扩大了诸多底层模块的适用受众——例如 grafast 提供了可直接替换 graphql 原生 execute 方法的入口,即便完全不使用自动生成 schema 的功能,也能让手写的 GraphQL schema 获得大幅性能提升。更广泛的使用群体意味着更多人共同审视和打磨代码,最终让所有人都受益于更高质量的软件。