Skip to main content

New makeExtendSchemaPlugin新版 makeExtendSchemaPlugin

The move from PostGraphile V4 to V5 sees the transition from the hacky and chaotic lookahead system to our new clean and performant Grafast planning and execution engine. This means that many of the workarounds of the past are no longer needed, including:

从 PostGraphile V4 升级到 V5,底层架构从过去零散且充满变通的 lookahead 系统,全面转向了简洁高效的全新规划与执行引擎 Grafast。这意味着过去许多权宜之计如今都不再需要了,包括:

  • Directives: @requires, @pgField, @pgQuery

    指令(Directive):@requires、@pgField、@pgQuery

  • Helper functions: selectGraphQLResultFromTable, embed

    辅助函数:selectGraphQLResultFromTable、embed

  • Savepoints

    保存点(Savepoint)

  • context.pgClient.query
  • QueryBuilder "named children"

    QueryBuilder 的“命名子节点(named children)”

  • QueryBuilder itself

    QueryBuilder 本身

  • build.getTypeAndIdentifiersFromNodeId
  • hacks to ensure the type is loaded before we reference it by name

    为了确保类型在按名称引用前已加载而采取的各种变通写法

TODO: find an alternative to the @scope directive.

待办(TODO):寻找 @scope 指令的替代方案。

The reason for the above changes is that instead of using resolvers, Version 5 uses plans. Technically you can continue to use resolvers when dealing with external systems, but you will need to use plans to replace the above directive behavior so you might as well adopt plans, right? 😉

上述变化的核心原因在于:V5 不再使用 resolver,而是全面改用执行计划(plan)。从技术上讲,与外部系统交互时你依然可以继续使用 resolver;但既然要替代上述指令的能力就必须用到 plan,不如干脆全面拥抱 plan,对吧?😉

@requires​

In V4 we had @requires(columns: [...]) which would ensure the parent object passed into your resolver had the given columns (though they might have different capitalization 😬).

在 V4 中,我们需要通过 @requires(columns: [...]) 来确保传入 resolver 的父对象包含指定列的数据(而且传入时的列名大小写还可能被改写过 😬)。

In a V5 plan you can simply .get(...) each of the columns from the parent plan.

而在 V5 的 plan 中,只需直接调用父 plan 的 .get(...) 方法即可获取所需的列。

Here's an example from the V4 documentation converted to V5. It uses a lambda step to convert the price_in_us_cents to AUD via the convertUsdToAud function.

下面将 V4 文档中的一个示例迁移到 V5:通过 lambda step 调用 convertUsdToAud 函数,把 price_in_us_cents 转换为澳元(AUD)。

V4 -> V5 conversion
-const { makeExtendSchemaPlugin, gql } = require("graphile-utils");
+const { extendSchema, gql } = require("postgraphile/utils");
const { convertUsdToAud } = require("ficticious-npm-library");
+const { lambda } = require('postgraphile/grafast');

-const MyForeignExchangePlugin = makeExtendSchemaPlugin((build, options) => {
+const MyForeignExchangePlugin = extendSchema((build) => {
+ const { options } = build;
return {
typeDefs: gql`
extend type Product {
- priceInAuCents: Int! @requires(columns: ["price_in_us_cents"])
+ priceInAuCents: Int!
}
`,
- resolvers: {
+ plans: {
Product: {
- priceInAuCents: async (product) => {
- // Note that the columns are converted to fields, so the case changes
- // from `price_in_us_cents` to `priceInUsCents`
- const { priceInUsCents } = product;
- return await convertUsdToAud(priceInUsCents);
- },
+ priceInAuCents($product) {
+ const $cents = $product.get('price_in_us_cents');
+ return lambda($cents, cents => convertUsdToAud(cents));
+ },
},
},
};
});
tip提示

We've used lambda because the convertUsdToAud function converts one value at a time; however if we had a function capable of bulk converting many currency values at the same time it would be more efficient to call that function (once) via loadOne rather than once-per-value as with lambda.

这里选用 lambda 是因为 convertUsdToAud 每次只能转换单个数值;如果你手头有一个支持批量转换多种货币金额的函数,改用 loadOne 一次性批量调用会更高效,避免像 lambda 那样对每个值逐一调用。

@pgField​

This directive was always a workaround and is no longer meaningful in V5 — just make sure you add the right plans to the right fields and everything should work how you desire, and in a much more efficient and straightforward way than many patterns (particularly around mutation payloads) in V4.

这个指令本质上一直是个权宜之计,在 V5 中已无实际意义——只要为各个字段配上正确的 plan,一切就会按预期运行,而且比 V4 中的诸多写法(尤其是围绕 mutation payload 的各种处理方式)更高效、更直观。

tip提示

Don't always try to do everything in one field. It's better to give the subfields plans so that the related logic only needs to be executed if the field is actually requested, and it can also simplify the code.

不要总想着在单个字段里把所有事情做完。更好的做法是为子字段各自编写 plan:这样一来,只有当客户端实际请求了某个子字段时,相关逻辑才会执行,代码结构也会随之更简洁。

@pgQuery​

In V4, @pgQuery existed to inline SQL into your GraphQL operation, often as a performance optimization to work around computed column functions or similar that were not being inlined by PostgreSQL.

在 V4 中,@pgQuery 用于将 SQL 片段直接内联到 GraphQL 操作中,通常作为一种性能优化手段,用来绕开 PostgreSQL 无法自动内联计算列函数等问题。

In V5, this concern should be handled via a plan. You have a number of choices of what plan you need, depending on what you're trying to achieve.

在 V5 中,这类需求同样通过 plan 来解决。根据具体场景的不同,你有多种 plan 实现方式可供选择。

For leaf fields, if you need to do the calculation in the database rather than in JS, you might use an SQL expression:

对于叶子字段(leaf field),如果必须在数据库而非 JS 中完成计算,可以使用 SQL 表达式:

-module.exports = makeExtendSchemaPlugin(build => {
+module.exports = extendSchema(build => {
const { pgSql: sql } = build;
return {
typeDefs: gql`
extend type User {
- nameWithSuffix(suffix: String!): String! @pgQuery(
- fragment: ${embed(
- (queryBuilder, args) =>
- sql.fragment`(${queryBuilder.getTableAlias()}.name || ' ' || ${sql.value(
- args.suffix
- )}::text)`
- )}
- )
+ nameWithSuffix(suffix: String!): String!
}
`,
+ objects: {
+ User: {
+ plans: {
+ nameWithSuffix($user, { $suffix }) {
+ return $user.select(
+ sql`${$user.getClassStep().alias}.name || ' ' || ${$user.placeholder($suffix, TYPES.text)}`,
+ TYPES.text,
+ );
+ }
+ }
+ }
+ }
};
});
note注意

The above is not an example of an SQL injection attack, the code uses the sql tagged template literal function from the pg-sql2 module to ensure that all parameters are correctly handled.

上述写法并不存在 SQL 注入风险,因为它使用了 pg-sql2 模块提供的 sql 标签模板函数,确保所有参数都会被安全地参数化处理。

tip提示

A more performant (and simpler) solution to this would have been to do it in JS:

不过,性能更好(也更简单)的做法是直接在 JS 中完成拼接:

+ plans: {
+ User: {
+ nameWithSuffix($user, { $suffix }) {
+ return lambda(
+ [$user.get("name"), $suffix],
+ ([name, suffix]) => `${name} ${suffix}`,
+ );
+ },
+ },
+ },

Please refer to the @dataplan/pg documentation for additional details.

更多细节请参阅 @dataplan/pg 文档。

@pgSubscription​

In V4, @pgSubscription (from @graphile/pg-pubsub) let you embed a topic generator in SDL. In V5, you should remove this directive and instead place the logic into a Grafast subscribePlan using listen(...).

在 V4 中,你可以借助 @graphile/pg-pubsub 提供的 @pgSubscription 在 SDL 中嵌入主题(topic)生成逻辑;而在 V5 中,只需移除该指令,改在 Grafast 的 subscribePlan 里调用 listen(...) 即可。

V4:

import { makeExtendSchemaPlugin, gql, embed } from "graphile-utils";

const currentUserTopicFromContext = async (_args, context) => {
if (!context.jwtClaims?.user_id) throw new Error("You're not logged in");
return `graphql:user:${context.jwtClaims.user_id}`;
};

export default makeExtendSchemaPlugin(() => ({
typeDefs: gql`
extend type Subscription {
currentUserUpdated: UserSubscriptionPayload
@pgSubscription(topic: ${embed(currentUserTopicFromContext)})
}

type UserSubscriptionPayload {
user: User
event: String
}

`,
resolvers: {
UserSubscriptionPayload: {
user(event) {
/* ... */
},
},
},
}));

V5:

import { extendSchema } from "postgraphile/utils";

export default extendSchema((build) => {
const {
grafast: { context, get, listen, lambda },
dataplanJson: { jsonParse },
pgResources: { users },
} = build;

return {
typeDefs: /* GraphQL */ `
extend type Subscription {
currentUserUpdated: UserSubscriptionPayload
}

type UserSubscriptionPayload {
user: User
event: String
}
`,
objects: {
Subscription: {
plans: {
currentUserUpdated: {
subscribePlan(_$root, _args) {
const $pgSubscriber = context().get("pgSubscriber");
const $userId = get(context().get("jwtClaims"), "user_id");
const $topic = lambda($id, (id) => `graphql:user:${id}`);
return listen($pgSubscriber, $topic, jsonParse);
},
plan($event) {
return $event;
},
},
},
},
UserSubscriptionPayload: {
plans: {
user($payload) {
const $id = get($payload, "subject");
return users.get({ id: $id });
},
},
},
},
};
});

The key migration point is that topic selection is now plain code in subscribePlan, rather than directive metadata.

迁移的关键在于:订阅主题的选择逻辑现在直接作为普通代码写在 subscribePlan 中,而不再是指令元数据。

If your V4 topic came from field arguments, use fieldArgs.getRaw(...) in subscribePlan:

如果 V4 中的主题名称来自字段参数,可以在 subscribePlan 中使用 fieldArgs.getRaw(...) 获取:

const $forumId = fieldArgs.getRaw("forumId");

Then use that step when constructing your $topic.

接着在构建 $topic 时使用该 step 即可。

For more subscription guidance, see Realtime and Subscriptions.

关于订阅的更多指南,请参阅 Realtime 实时能力 与 Subscriptions 订阅。

selectGraphQLResultFromTable​

In Version 4, this method was needed to kick off a "look-ahead" enhanced data fetch from a GraphQL resolver, but was always at risk of introducing the N+1 problem. Many users found it confusing, and would often try and use it to retrieve data for themselves to use inside a resolver, which did not align with its intent at all.

在 V4 中,我们需要在 GraphQL resolver 内调用该方法来发起基于“lookahead”的数据获取,但这始终伴随引入 N+1 查询问题的风险。此外,许多开发者觉得它很难理解,常常尝试用它拉取数据供 resolver 内部自行使用——这完全背离了它原本的设计初衷。

In Version 5 there is no need for this helper any more — every plan step is opted into the planning system without any ceremony, and the N+1 problem is automatically solved by Grafast. The method to retrieve the data to use in the plan, and the method to populate the data are now the same so there's no more confusion between the two methods.

在 V5 中不再需要这个辅助方法了——每个 step 都天然接入规划系统,无需额外模板代码,N+1 问题也会由 Grafast 自动消除。在 plan 中读取所需数据的方式与填充返回数据的方式已经完全统一,再也不会出现两者混淆的情况。

Here's an example of porting an example from the Version 4 documentation to Version 5. First we find the pgResource that represents the match_user function then we add a plan for the Query.matchingUser field that executes the function, passing through the searchText argument.

下面演示如何将 V4 文档中的一个示例迁移至 V5:首先获取代表 match_user 函数的 pgResource,然后为 Query.matchingUser 字段添加一个 plan,将 searchText 参数透传给该函数并执行。

-module.exports = makeExtendSchemaPlugin((build) => {
+module.exports = extendSchema((build) => {
+ const matchUser = build.pgResources.match_user;
return {
typeDefs: /* GraphQL */ `
type Query {
matchingUser(searchText: String!): User
}
`,
- resolvers: {
+ plans: {
Query: {
- matchingUser: async (parent, args, context, resolveInfo) => {
- const [row] = await resolveInfo.graphile.selectGraphQLResultFromTable(
- sql.fragment`(select * from match_user(${sql.value(
- args.searchText,
- )}))`,
- () => {}, // no-op
- );
- return row;
- },
+ matchingUser($parent, { $searchText }) {
+ return matchUser.execute({ step: $searchText });
+ },
},
},
};
});
This pattern is deprecated该写法已废弃

We've demonstrated this pattern to show the easiest way to migrate, but the typeDefs/plans pattern is deprecated because it's hard to make it type safe. Instead, the new pattern would have typeDefs/objects (for object types, types that use the type keyword in GraphQL) with the plans within that:

前面演示 typeDefs/plans 写法是为了展示最平滑的迁移路径,但该模式现已废弃,因为它很难保证类型安全。推荐使用新版 typeDefs/objects 写法(针对 GraphQL 中用 type 关键字定义的对象类型),并将 plan 放在对应的类型对象内部:

-module.exports = makeExtendSchemaPlugin((build) => {
+module.exports = extendSchema((build) => {
+ const matchUser = build.pgResources.match_user;
return {
typeDefs: /* GraphQL */ `
type Query {
matchingUser(searchText: String!): User
}
`,
- resolvers: {
+ objects: {
Query: {
- matchingUser: async (parent, args, context, resolveInfo) => {
- const [row] = await resolveInfo.graphile.selectGraphQLResultFromTable(
- sql.fragment`(select * from match_user(${sql.value(
- args.searchText,
- )}))`,
- () => {}, // no-op
- );
- return row;
- },
+ plans: {
+ matchingUser($parent, { $searchText }) {
+ return matchUser.execute({ step: $searchText });
+ },
+ },
},
},
};
});

It's up to you whether you want to address this all at once, or migrate in two phases.

你可以选择一步到位直接改造,也可以分两个阶段逐步迁移。

embed​

There is currently no replacement for embed. You shouldn't need it any more; if you think you do, please come ask in the Discord.

目前没有与 embed 对应的替代方案,因为按理说已经不再需要它了;如果你确实遇到了看似离不开它的场景,欢迎前往 Discord 社区咨询。

SavepointsSavepoints(保存点)​

In PostGraphile V4 every GraphQL request was wrapped in a transaction. In order to be compliant with the GraphQL specification every mutation needed to be wrapped in a SAVEPOINT to ensure that if a single mutation failed, all the other mutations would not be rolled back (so called "partial success").

在 PostGraphile V4 中,每个 GraphQL 请求整体都会被包裹在一个事务里。为了符合 GraphQL 规范,每次 mutation 执行时还必须额外创建 SAVEPOINT,以确保单个 mutation 失败时不会导致同一请求中的其他 mutation 一并回滚(即所谓的“部分成功”语义)。

In PostGraphile V5, transactions are created on demand, so the use of savepoints is no longer necessary. That's good if you're concerned about SAVEPOINT impact on performance.

在 PostGraphile V5 中,事务改为按需创建,因此不再需要使用 savepoint。对于担心 SAVEPOINT 影响性能的团队来说,这无疑是个好消息。

context.pgClient.query​

In V4 we provision a Postgres client at the beginning of every GraphQL request and place it in a transaction, even if it isn't needed. This client was added to the GraphQL context as pgClient, and you could use it in your mutations.

在 V4 中,无论请求是否真正需要数据库操作,系统都会在每次 GraphQL 请求开始时预先分配一个 Postgres 客户端并开启事务。该客户端会作为 pgClient 挂载到 GraphQL 上下文中,供你在 mutation 中直接调用。

In V5, Postgres clients are provisioned on demand. For custom reads use loadOneWithPgClient() / loadManyWithPgClient() so you still benefit from Grafast batching. For mutations reach for sideEffectWithPgClient() or sideEffectWithPgClientTransaction() depending on whether you need an explicit transaction. Note that this pgClient is a generic adaptor, so if you want to deal with your Postgres client of choice here (pg, postgres, pg-promise, etc) you can do so!

在 V5 中,Postgres 客户端改为按需分配。对于自定义读取操作,请使用 loadOneWithPgClient() / loadManyWithPgClient(),从而继续享受 Grafast 的自动批处理能力;对于 mutation,则可根据是否需要显式事务,选用 sideEffectWithPgClient() 或 sideEffectWithPgClientTransaction()。需要注意的是,这里的 pgClient 是一个通用适配器,因此你可以自由使用自己偏好的 Postgres 客户端库(如 pg、postgres、pg-promise 等)!

import { object } from "postgraphile/grafast";
import { withPgClientTransaction } from "postgraphile/@dataplan/pg";
import { extendSchema } from "postgraphile/utils";

export default extendSchema((build) => {
const { sql } = build;
/**
* The 'executor' tells us which database we're talking to. This is the
* default executor.
*
* If you're talking to multiple databases, you can get this from the
* registry, the default executor name is `main` but you can override this and
* add extra sources/executors via the `pgServices` configuration option:
*
* ```
* const executor = build.input.pgRegistry.pgExecutors.main;
* ```
*/
const executor = build.pgExecutor;

return {
typeDefs: /* GraphQL */ `
input MyCustomMutationInput {
count: Int
}
type MyCustomMutationPayload {
numbers: [Int!]
}
extend type Mutation {
"""
An example mutation that doesn't really do anything; uses Postgres'
generate_series() to return a list of numbers.
"""
myCustomMutation(input: MyCustomMutationInput!): MyCustomMutationPayload
}
`,

objects: {
Mutation: {
plans: {
myCustomMutation(_$root, { $input: { $count } }) {
/**
* This step dictates the data that will be passed as the second argument
* to the `withPgClientTransaction` callback. This is typically
* information about the field arguments, details from the GraphQL
* context, or data from previously executed steps.
*/
const $data = object({
count: $count,
});

// Callback will be called with a client that's in a transaction,
// whatever it returns (plain data) will be the result of the
// `withPgClientTransaction` step; if it throws an error then the
// transaction will roll back and the error will be the result of the
// step.
const $transactionResult = withPgClientTransaction(
executor,
$data,
async (client, data) => {
// The data from the `$data` step above
const { count } = data;

// Run some SQL
const { rows } = await client.query(
sql.compile(
sql`select i from generate_series(1, ${sql.value(
count ?? 1,
)}) as i;`,
),
);

// Do some asynchronous work (e.g. talk to Stripe or whatever)
await sleep(2);

// Maybe run some more SQL as part of the transaction
await client.query(sql.compile(sql`select 1;`));

// Return whatever data you'll need later
return rows.map((row) => row.i);
},
);

return $transactionResult;
},
},
},
MyCustomMutationPayload: {
plans: {
numbers($transactionResult) {
return $transactionResult;
},
},
},
},
};
});

Another example of extendSchema being used can be found here.

关于 extendSchema 的另一个使用示例,可以查看这里。

QueryBuilder "named children"QueryBuilder 的“命名子节点(named children)”​

This concept is no longer useful or needed, and can be ported to much more direct Grafast steps. If you need help, do reach out on the Discord.

这一概念已不再适用,也不再需要,相关逻辑可以改写为更直接的 Grafast step。如果在迁移过程中需要帮助,欢迎前往 Discord 社区交流。

QueryBuilder itselfQueryBuilder 本身​

QueryBuilder no longer exists, instead you'll mostly be using the helpers on pgSelect and similar steps.

QueryBuilder 已彻底移除,取而代之的是直接调用 pgSelect 及同类 step 上的辅助方法。

build.getTypeAndIdentifiersFromNodeId​

This helper has been replaced with specFromNodeId. Each GraphQL type that implements Node registers a "node ID handler"; if you know the typeName you're expecting you can get this via build.getNodeIdHandler(typeName). From this, you can determine the "codec" that was used to encode the NodeID, and passing these two things to specFromNodeId along with the node ID itself should return a specification of your node, typically something like {id: $id} (where $id is an executable step), but can vary significantly depending on the node type.

该辅助方法已被替换为 specFromNodeId。每个实现 Node 接口的 GraphQL 类型都会注册一个“node ID handler”;如果你明确知道期望的 typeName,可以通过 build.getNodeIdHandler(typeName) 获取它。借此你可以确定用于编码该 Node ID 的 codec,再将这两项信息连同 Node ID 本身传给 specFromNodeId,即可返回对应节点的规格描述(specification),常见形式如 {id: $id}(其中 $id 是一个可执行的 step),具体结构会因节点类型而有较大差异。

Here's an example:

示例如下:

const typeName = "User";
const handler = build.getNodeIdHandler(typeName);

const objects = {
Mutation: {
plans: {
updateUser(parent, fieldArgs) {
const spec = specFromNodeId(handler, fieldArgs.$id);
const plan = object({ result: pgUpdateSingle(userSource, spec) });
fieldArgs.apply(plan);
return plan;
},
},
},
};