Skip to main content

Grafast for PostGraphile users

PostGraphile plans and executes fields through Grafast. When building a plan() function (a "field plan resolver") for use in extendSchema or similar you will be using Grafast "steps" to compose that part of the "operation plan", and these steps are generated from step functions such as loadOne().

PostGraphile 通过 Grafast 来规划和执行字段。当你在 extendSchema 等场景下编写 plan() 函数(即“字段 plan resolver”)时,需要用 Grafast 的执行步骤(step)来编排对应部分的“操作执行计划(operation plan)”,而这些 step 通常由 loadOne() 等 step 函数创建。

Together these steps let you blend PostgreSQL data, external APIs, and custom business logic into a single plan. Grafast keeps the execution efficient while PostGraphile gives you the extension points to shape the graph you need.

借助这些 step,你可以将 PostgreSQL 数据、外部 API 与自定义业务逻辑无缝整合进同一个执行计划中。Grafast 负责保障高效执行,PostGraphile 则提供各类扩展点,让你自由塑造所需的 GraphQL 图结构。

Main docs at grafast.org完整文档请见 grafast.org

The authoritative reference for every step lives on grafast.org; follow the links below for the full API.

每个 step 的权威参考文档均位于 grafast.org;点击下文链接即可查阅完整的 API 说明。

Below are the steps PostGraphile users encounter most when extending their schema.

下文列出了 PostGraphile 用户在扩展 schema 时最常打交道的各类 step。

Of course it makes sense that PostGraphile users will deal with the database a lot. Often the step that represents a specific type you're extending will be a pgSelectSingle step representing a row in the database. Sometimes you'll need to query or update other rows in the database.

PostGraphile 用户自然会频繁与数据库打交道。在扩展某个特定类型时,代表该类型的 step 通常是一个对应数据库单行记录的 pgSelectSingle step;有时你还需要查询或更新数据库中的其他记录。

pgResourcespgResources(数据库资源)​

For most query operations you'll start with the "resource" that represents your database table, and you'll .get() a single row or .find() many rows. This will, under the hood, create a pgSelectSingle or pgSelect step for you.

大多数查询操作都要从代表数据库表的 resource(资源对象)入手,调用 .get() 获取单行,或调用 .find() 获取多行。它们会在底层为你创建对应的 pgSelectSingle 或 pgSelect step。

Resources are found in the build.pgResources object (or, equivalently, build.input.pgRegistry.pgResources), keyed by the inflected name of the resource. Typically this will be the name of the table/view/function/etc:

所有的 resource 都存放在 build.pgResources 对象中(等价于 build.input.pgRegistry.pgResources),其键名为经过 inflection 命名推导后的资源名称,通常也就是表、视图或函数等的名称:

const { users, get_users_by_organization } = build.pgResources;

pgResource.get()pgResource.get()(按唯一键获取单行)​

You can then select a single row from a resource by passing a "specifier" object to .get(). This must identify the step to check equality with for each of the attributes in a unique constraint or primary key:

调用 resource 的 .get() 并传入一个“定位描述符(specifier)”对象,即可从中查询单行记录。该对象必须为某个唯一约束或主键中的每一个属性指定用于等值匹配的 step:

const $user = users.get({ id: $id });

(Returns a pgSelectSingle step.)

(返回一个 pgSelectSingle step。)

pgResource.find()pgResource.find()(查询多行)​

Alternatively, you might wish to select many rows from the resource. You may optionally still use a specifier object to give some equality constraints, but more typically you will want to add your own conditions:

如果需要从 resource 中查询多行记录,可以改用 .find()。你同样可以可选地传入 specifier 对象来添加等值条件,不过更常见的做法是自行追加筛选条件:

const $users = users.find();
$users.where((sql) => sql`${$users}.is_active = true`);

(Returns a pgSelect step.)

(返回一个 pgSelect step。)

When you pass SQL fragments to .where(...), .having(...), or .orderBy(...), use the callback form; it provides the sql tag so you do not need to import it for simple cases, and also enables you to embed more types of expressions, reducing the need for explicit placeholders.

向 .where(...)、.having(...) 或 .orderBy(...) 传入 SQL 片段时,请使用回调函数形式:回调会自动提供 sql 标签函数,简单场景下无需手动导入;同时它支持直接嵌入更多类型的表达式,减少显式占位符的使用。

pgResource.execute()pgResource.execute()(执行函数资源)​

"Resources" aren't limited to just being database tables; views, materialized views, and even functions are also resources. For a function, you would issue an execute command instead, passing descriptions of each argument:

“Resource” 不仅限于数据库表——视图、物化视图乃至数据库函数同样属于 resource。对于函数类型的 resource,应改用 .execute() 方法,并传入每个参数的描述信息:

const $users = get_users_by_organization.execute([
{ step: $organizationId, pgCodec: TYPES.uuid },
]);

(Returns a pgSelect step.)

(返回一个 pgSelect step。)

The codec is currently required当前必须指定 codec

Unfortunately the work required to make the codecs optional didn't make the cut for the V5.0.0 release.

遗憾的是,让 codec 变为可选项的相关工作未能赶上 V5.0.0 版本的发布窗口。

pgSelectpgSelect(多行查询 step)​

A pgSelect step represents selecting a list of rows from a database. It's rare that you would construct a pgSelect(...) step directly; instead use the resources as shown above.

pgSelect step 表示从数据库中查询多行记录。实际开发中极少直接构造 pgSelect(...),通常应像上文那样通过 resource 来创建。

A pgSelect step has loads of useful methods, including:

pgSelect step 提供了许多实用方法,包括:

  • .where(...) - add a WHERE clause

    .where(...) —— 添加 WHERE 子句

  • .orderBy(...) - add an ORDER BY clause

    .orderBy(...) —— 添加 ORDER BY 子句

  • .setOrderIsUnique() - if you know the ordering is stable (no two rows can have the same values for the ordered columns) set this for efficiency

    .setOrderIsUnique() —— 当你确定排序结果唯一且稳定(任意两行的排序列取值均不相同)时,调用此方法可提升执行效率

  • .groupBy(...) - add a GROUP BY clause

    .groupBy(...) —— 添加 GROUP BY 子句

  • .having(...) - add a HAVING clause

    .having(...) —— 添加 HAVING 子句

  • .setInliningForbidden() - prevent this select being inlined into its parent

    .setInliningForbidden() —— 禁止将该查询内联(inline)到其父查询中

  • .setTrusted() - don't invoke the selectAuth() and other methods from the resource (for efficiency, presumably because they were already validated some other way).

    .setTrusted() —— 跳过调用该 resource 上的 selectAuth() 等鉴权方法(通常用于已通过其他方式完成权限校验的场景,以提高性能)。

  • .setUnique() - indicate that this will return at most one row.

    .setUnique() —— 声明该查询最多只返回一行记录。

  • .single() - return the single row (or result if this is a scalar function) from this unique pgSelect

    .single() —— 从这个唯一的 pgSelect 中提取单行记录(如果是标量函数则返回其结果)。

pgSelectSinglepgSelectSingle(单行记录 step)​

A single row from the database is represented by a pgSelectSingle step. It's used for accessing columns (.get(columnName)) and constructing expressions. It's exceedingly rare to need to create a pgSelectSingle() directly, instead you would retrieve one via pgResource.get(), via regular list traversal of a pgSelect step, or via a pgSelect step's .single() method.

pgSelectSingle step 代表数据库中的单行记录,用于读取列值(.get(columnName))和构造表达式。几乎不需要手动创建 pgSelectSingle(),通常可以通过 pgResource.get()、遍历 pgSelect step 的列表项,或调用 pgSelect step 的 .single() 方法来获取。

Commonly used methods:

常用方法:

  • .get('column_name') - read the column column_name from the row

    .get('column_name') —— 从当前行读取 column_name 列的值

  • .select(...) - return a step representing the result of an SQL expression using this row, decoded with the given codec

    .select(...) —— 返回一个代表基于当前行计算的 SQL 表达式结果的 step(按指定的 codec 解码)

  • .record() - return an object representing the full database record (inefficient - avoid unless needed!)

    .record() —— 返回代表整条数据库记录的对象(性能开销较大,非必要请避免使用!)

  • .getPgRoot() - return the fetching step this pgSelectSingle step came from - this will typically be a pgSelect step, but need not be (e.g. in the case of pgCreateSingle/pgUpdateSingle)

    .getPgRoot() —— 返回该 pgSelectSingle step 所属的顶层数据获取 step;它通常是 pgSelect step,但也可能是 pgCreateSingle 或 pgUpdateSingle 等其他 step

  • .singleRelation(relationName) - get a pgSelectSingle step representing the row from traversing the relationName relation

    .singleRelation(relationName) —— 沿 relationName 关联关系(relation)跳转,获取表示对应单行记录的 pgSelectSingle step

  • .manyRelation(relationName) - get a pgSelect step representing the rows from traversing the relationName relation

    .manyRelation(relationName) —— 沿 relationName 关联关系(relation)跳转,获取表示对应多行记录的 pgSelect step

contextcontext(请求上下文)​

context() exposes the GraphQL context as a step so you can read or modify per-request values. PostGraphile users might use this to access methods that they've added to context to expose authentication information, or even in side effects to update database settings via pgSettings.

context() 会将 GraphQL 上下文(context)暴露为一个 step,方便你在计划中读取或修改请求级别的数据。PostGraphile 用户常通过它访问挂载在上下文中的鉴权信息与辅助方法,或在副作用(side effect)中借助 pgSettings 更新数据库会话配置。

import { context } from "postgraphile/grafast";

const $context = context();
const $pgSettings = $context.get("pgSettings");
const $currentUserId = get($pgSettings, "jwt.claims.userId");

You can also derive a new value and persist it back to context:

你也可以派生一个新值并将其写回上下文:

import { context, sideEffect } from "postgraphile/grafast";

const $context = context();

sideEffect([$context, $userId], (context, userId) => {
context.pgSettings["jwt.claims.userId"] = userId;
});

loadOneloadOne(批量加载单个值)​

Use loadOne() when fetching a single value from an external service (Stripe, REST APIs, microservices, etc.) by its identifier(s); for example "load customer by customer ID". (For PostgreSQL, lean on @dataplan/pg steps and pgResources instead.)

当需要按标识符从外部服务(如 Stripe、REST API、微服务等)获取单条数据时(例如“按客户 ID 查询客户信息”),请使用 loadOne()。(如果数据来自 PostgreSQL,则应优先使用 @dataplan/pg 的 step 与 pgResources。)

loadOne() is similar to DataLoader's load - it batches retrieving a values by their identifier(s) to avoid the N+1 problem. loadOne() is more powerful than the DataLoader equivalent because it lets Grafast reason about requested attributes and parameters.

loadOne() 类似于 DataLoader 的 load——它会按标识符对请求进行批量合并,从而避免 N+1 查询问题。不仅如此,由于 loadOne() 允许 Grafast 分析调用方实际请求的属性与参数,其能力比传统 DataLoader 更为强大。

import { context, loadOne } from "postgraphile/grafast";

const $currentUserId = context().get("currentUserId");
const $customer = loadOne($currentUserId, batchGetStripeCustomerByUserId);

loadManyloadMany(批量加载列表)​

loadMany() is identical to loadOne() except it expects the result to be a list - for example "load invoices by customer ID".

loadMany() 的用法与 loadOne() 完全相同,区别在于它预期返回的结果是一个列表——例如“按客户 ID 查询所有账单”。

import { loadMany } from "postgraphile/grafast";

const $stripeId = $customer.get("stripeId");
const $invoices = loadMany($stripeId, batchGetInvoicesByStripeCustomerId);

getget(读取属性)​

get($step, key) retrieves a property key from step $step, either using $step.get(key) if it is supported, otherwise falling back to access($step, key). Use it when you're not sure whether or not $step will always support .get().

get($step, key) 用于从 $step 中读取属性 key:如果 $step 支持 .get(key) 方法,则直接调用;否则回退到 access($step, key)。当你不确定某个 $step 是否始终提供 .get() 方法时,使用它可以保证兼容性。

import { get } from "postgraphile/grafast";

const $userId = get($user, "id");

sideEffectsideEffect(执行副作用)​

sideEffect() runs imperative work (like mutations). Keep it to mutation root fields and let the callback perform the state change.

sideEffect() 用于执行命令式的操作(例如变更操作)。请仅在 Mutation 根字段中使用它,并在回调函数中完成状态变更。

PostGraphile users may want to use it to mutate the context, e.g. updating pgSettings once the user has logged in.

PostGraphile 用户常通过它来修改请求上下文,例如在用户登录后更新 pgSettings。

IMPORTANT: sideEffect calls are NOT batched, if used outside mutation root fields they may result in N+1 executions.

重要提示:sideEffect 调用不会进行批处理,若在 Mutation 根字段之外使用,极有可能导致 N+1 次重复执行。

import { context, sideEffect } from "postgraphile/grafast";

const $context = context();

sideEffect($context, async (context) => {
await context.logout();
context.pgSettings["jwt.claims.userId"] = null;
});

constantconstant(常量值)​

constant() lifts a literal value into the plan. Use it when you need a fixed step value, typically as an argument to another step.

constant() 将字面量提升为一个 step 纳入执行计划中。当你需要向其他 step 传入固定值作为参数时,它非常实用。

import { constant } from "postgraphile/grafast";

const $true = constant(true);

eacheach(映射列表项)​

each() maps over a list step, returning a new step for the transformed list.

each() 对列表类型的 step 进行映射遍历,并返回一个表示转换后列表的新 step。

import { each, object } from "postgraphile/grafast";

const $points = each($rows, ($row) => {
const $lng = get($row, "x");
const $lat = get($row, "y");

return object({ lng: $lng, lat: $lat });
});

It's normally used as the return value for a field plan resolver to transform the result:

通常直接将其作为字段 plan resolver 的返回值,用于转换查询结果:

return $points;

However, if you feed $points into another step you will need to call applyTransforms($points) first so the mapping occurs before the dependent step runs:

不过,如果你要把 $points 作为输入传给另一个 step,则必须先调用 applyTransforms($points),确保在下游 step 运行前完成数据映射:

sideEffect(
// Ensure $points has been transformed
applyTransforms($points),
// Log it out
(points) => void console.dir(points),
);

lambdalambda(纯函数派生计算)​

lambda() lets you derive data with a pure callback. Avoid side effects here; if you need them reach for sideEffect() instead.

lambda() 允许你通过纯函数回调来派生数据。切勿在此产生副作用;若需要执行副作用操作,请改用 sideEffect()。

This should be used for simple synchronous transforms; using it for asynchronous work will result in the N+1 problem since lambda is explicitly unbatched.

该函数仅适用于简单的同步数据转换;由于 lambda 本质上不进行批处理,用它执行异步逻辑会引发 N+1 问题。

import { lambda } from "postgraphile/grafast";

const $first = $user.get("first_name");
const $last = $user.get("last_name");

const $fullName = lambda(
[$first, $last],
([first, last]) => `${first} ${last}`,
);

objectobject(组装对象)​

object() assembles an object by wiring keys to other steps. It's commonly used as the result of a mutation plan resolver.

object() 通过将对象的各个键关联到对应 step 来组装出对象,常用于构造变更字段 plan resolver 的返回值。

import { constant, object } from "postgraphile/grafast";

const $userId = $user.get("id");
const $includeArchived = constant(false);

const $loaderInput = object({
id: $userId,
includeArchived: $includeArchived,
});

connectionconnection(包装分页连接)​

connection() wraps a set of rows (typically a PgSelectStep) so connection fields keep the helper methods PostGraphile expects. Use it when returning Relay connections from custom fields.

connection() 用于包装一组行记录(通常是 PgSelectStep),使 Connection 字段具备 PostGraphile 所需的辅助方法。当你从自定义字段返回 Relay Connection 时,请使用它进行包装。

import { connection } from "postgraphile/grafast";

const $rows = reviews.find({ product_id: $productId });
return connection($rows);

listlist(组合 step 列表)​

list() bundles multiple steps together into a list step, typically useful so a downstream step can see them all via a single dependency.

list() 将多个 step 打包成一个列表 step,方便下游 step 通过单一依赖项一次性读取全部结果。

Rarely needed通常无需显式调用

Many of the builtin steps support accepting an array of dependencies ([$dep1, $dep2, ...]) directly instead of calling list([$dep1, $dep2, ...]) explicitly.

许多内置 step 都直接支持接收依赖数组([$dep1, $dep2, ...]),无需专门调用 list([$dep1, $dep2, ...])。

import { context, list } from "postgraphile/grafast";

const $context = context();
const $jwtClaims = $context.get("jwtClaims");
const $inputs = list([$jwtClaims, $itemId]);

accessaccess(底层属性访问)​

access($step, key) reads a property, key, from the result of any step, $step. Prefer get($step, key) unless you are implementing a custom $step.get(key) method; using get() there would recurse forever.

access($step, key) 用于从任意 $step 的执行结果中读取 key 属性。日常开发建议优先使用 get($step, key),除非你正在实现自定义的 $step.get(key) 方法——因为在 .get() 内部调用 get() 会导致无限递归。

import { access } from "postgraphile/grafast";

const $userId = access($user, "id");

specFromNodeIdspecFromNodeId(解码 Node ID)​

specFromNodeId() decodes a Node ID using a handler from build.getNodeIdHandler("TypeName"). It returns the step specifications you can feed into resources or other loaders.

specFromNodeId() 使用来自 build.getNodeIdHandler("TypeName") 的处理器对 Node ID 进行解码,并返回可直接传给 resource 或其他加载器的定位描述符(step specifications)。

import { specFromNodeId } from "postgraphile/grafast";

const spec = specFromNodeId(itemHandler, $nodeId);
const $itemId = spec.id;
const $item = items.get({ id: $itemId });

loadOneWithPgClientloadOneWithPgClient(通过 pgClient 批量加载单个值)​

loadOneWithPgClient() gives you DataLoader-style batching while letting the callback run custom SQL with the provided pgClient. Use it for single-row lookups that need bespoke queries.

loadOneWithPgClient() 提供 DataLoader 风格的批处理能力,同时向回调函数传入 pgClient 以执行自定义 SQL。适用于需要定制 SQL 语句的单行查询场景。

import { loadOneWithPgClient } from "postgraphile/@dataplan/pg";
import { get } from "postgraphile/grafast";

const $userId = get($input, "userId");
const $user = loadOneWithPgClient(
executor, // obtained from build.pgResources.users
$userId,
async (pgClient, userIds) => {
return selectUsersById(pgClient, userIds);
},
);
The result of this will not conform to PostGraphile's expectations该方法的返回值不符合 PostGraphile 的默认类型预期

This method is useful for getting data for your own usage, but if you're trying to get data to use in an autogenerated PostGraphile type based on a database table then it won't work, since those types expect a pgSelectSingle step.

此方法非常适合获取供自行处理的数据;但如果你希望返回的数据直接映射到 PostGraphile 基于数据库表自动生成的 GraphQL 类型,它将无法正常工作——因为这些自动生成类型期望接收的是 pgSelectSingle step。

You can work around this by making a pgSelectSingle step afterwards, but this will involve another fetch from the database:

你可以通过后续再构造一个 pgSelectSingle step 来变通解决,但这会引发一次额外的数据库查询:

const $userId = get($user, "id");
const $pgUser = users.get({ id: $userId });

Typically it would be better in this case to just use the users.get() method directly, however that may not always be possible.

在这种情况下,通常直接调用 users.get() 方法会更高效,尽管某些特殊场景下可能无法做到。

loadManyWithPgClientloadManyWithPgClient(通过 pgClient 批量加载列表)​

loadManyWithPgClient() mirrors loadMany() but still hands you the pgClient, so you can fan out SQL work using the same settings the rest of the request uses.

loadManyWithPgClient() 与 loadMany() 相对应,同样会向回调提供 pgClient,让你能沿用当前请求的数据库会话配置来批量执行自定义 SQL 查询。

import { loadManyWithPgClient } from "postgraphile/@dataplan/pg";
import { get } from "postgraphile/grafast";

const $userId = get($user, "id");
const $phones = loadManyWithPgClient(
executor, // obtained from build.pgResources.users
$userId,
async (pgClient, userIds) => {
// return an array aligned with userIds
return normalizePhones(pgClient, userIds);
},
);
The result of this will not conform to PostGraphile's expectations该方法的返回值不符合 PostGraphile 的默认类型预期

This method is useful for getting data for your own usage, but if you're trying to get data to use in an autogenerated PostGraphile type based on a database table then it won't work, since those types expect a pgSelectSingle step.

此方法非常适合获取供自行处理的数据;但如果你希望返回的数据直接映射到 PostGraphile 基于数据库表自动生成的 GraphQL 类型,它将无法正常工作——因为这些自动生成类型期望接收的是 pgSelectSingle step。

You can work around this by creating a pgSelectSingle step for the resulting rows, but this will involve another fetch from the database:

你可以通过为结果集中的每一行创建 pgSelectSingle step 来变通处理,但这同样会增加一次额外的数据库查询:

return each($users, ($user) => {
const $userId = get($user, "id");
return users.get({ id: $userId });
});

Typically it would be better in this case to just use the users.find() method directly with whatever .where() made sense, however that may not always be possible.

在这种情况下,通常直接结合适当的 .where() 条件使用 users.find() 方法会更好,不过某些复杂场景下可能并不适用。

sideEffectWithPgClientsideEffectWithPgClient(通过 pgClient 执行副作用)​

sideEffectWithPgClientTransactionsideEffectWithPgClientTransaction(在事务中通过 pgClient 执行副作用)​

sideEffectWithPgClient() and sideEffectWithPgClientTransaction() pass a pgClient to your callback and expect it to perform a side effect - they both run unbatched, so do not use them anywhere but in the root mutation fields. sideEffectWithPgClientTransaction() guarantess that the callback is wrapped in a transaction. sideEffectWithPgClient() may or may not wrap the callback in a transaction, depending on if it's necessary to create one in order to apply the pgSettings.

sideEffectWithPgClient() 和 sideEffectWithPgClientTransaction() 都会向回调函数传入 pgClient 以执行副作用操作——二者均以非批处理方式运行,因此切勿在 Mutation 根字段之外的地方使用。其中,sideEffectWithPgClientTransaction() 保证回调函数必定在数据库事务中执行;而 sideEffectWithPgClient() 则视应用 pgSettings 时是否需要开启事务而定,可能会也可能不会将回调包裹在事务中。

Do not issue BEGIN/COMMIT manually inside these callbacks; instead, use client.withTransaction(...) which will create a subtransaction (savepoint) if needed (depending on the adaptor).

切勿在这些回调内部手动执行 BEGIN 或 COMMIT 语句;请改用 client.withTransaction(...),它会根据所使用的适配器按需创建子事务(savepoint)。

import { object } from "postgraphile/grafast";
import { sideEffectWithPgClientTransaction } from "postgraphile/@dataplan/pg";

const $input = fieldArgs.getRaw("input");
const $user = sideEffectWithPgClientTransaction(
executor, // obtained from build.pgResources.users
$input,
async (pgClient, input) => {
return insertUser(pgClient, input);
},
);

return object({ user: $user });