Why is it Nullable?
It's common for people, particularly those using strongly typed GraphQL implementations such as ReasonML or TypeScript, to ask why certain elements in a PostGraphile schema are nullable. A lot of thought has gone into which parts should/should not be nullable, but the reasoning behind these decisions is not always obvious to users, so hopefully this article will help to explain.
不少开发者——尤其是使用 ReasonML、TypeScript 等强类型 GraphQL 客户端的用户——经常会疑惑:为什么 PostGraphile 生成的 schema 中有些元素会是可空(nullable)的?其实,团队在决定“哪些字段应该可空、哪些应该非空”时经过了深思熟虑,只是背后的权衡未必一目了然,希望本文能为你解答其中缘由。
Nulls in GraphQLGraphQL 中的 Null 冒泡机制
In GraphQL, nulls cascade up the tree until they find the first "nullable". So take for example this GraphQL Schema:
在 GraphQL 中,当某个字段产生 null 值时,它会沿着查询树向上级联传播,直到遇到第一个“可空”节点为止。不妨看下面这个 GraphQL schema 示例:
# This is a bad practice GraphQL schema to demonstrate a point.
type Numbers {
one: Int!
two: Int!
three: Int!
}
type Letters {
a: String!
b: String!
c: String!
}
type Query {
numbers: Numbers!
letters: Letters!
}
and this query:
以及对应的查询:
{
numbers {
one
two
three
}
letters {
a
b
c
}
}
If there was an issue causing the resolver for Numbers.three to throw an
error, then GraphQL would first try and make the field itself null. It can't,
because it's not nullable, so it would then try and make the parent field
(numbers) null. But that's marked as non-nullable too, so the only thing left
to make nullable would be the entire query itself. This means that all the
letters, despite producing no errors, would also be omitted from the result.
假设由于某种异常,Numbers.three 的 resolver 抛出了错误。此时 GraphQL 会先尝试将该字段本身置为 null;但它被标记为非空,于是只好继续尝试将父字段(numbers)置为 null;可 numbers 同样是非空的,最终唯一能设为 null 的就只剩下整个查询结果本身了。这意味着,尽管 letters 部分完全没有出错,也会跟着从最终响应中被一并抹掉。
One of the key aims of GraphQL is to deal smoothly with temporary errors — i.e. when an error occurs it aims to not "throw the baby out with the bathwater". This is one of the reasons (the main reason, really) that GraphQL treats all fields as nullable by default ("errors happen") and allows you to mark things as not null, rather than the other way around which is more common in typed languages. GraphQL wants you to think about where errors may occur and where they should be limited to, preventing them from flowing over into unrelated areas.
GraphQL 的核心设计目标之一就是优雅地应对临时性错误——换言之,在局部出错时尽量避免“连同洗澡水一起把婴儿倒掉”(因小失大)。这正是 GraphQL 默认将所有字段视为可空(默认“错误随时可能发生”)、并由开发者显式标记非空的原因(也是最主要的原因),而与传统静态类型语言“默认非空、按需标记可空”的做法恰好相反。GraphQL 希望你主动思考哪些地方可能出错、以及错误应当被限制在什么边界之内,从而防止局部故障蔓延到毫不相干的数据区域。
Root (Query, Mutation and Subscription) fields根字段(Query、Mutation 与 Subscription)
If you're following GraphQL best practices, then all of your root level Query, Mutation and Subscription fields should be nullable unless you're absolutely certain that they cannot throw an error or be null, and further that none of their children or grandchildren or great-grandchildren can throw an error or return a null that would cascade and cause the field itself to be null.
按照 GraphQL 最佳实践,根级别的 Query、Mutation 和 Subscription 字段原则上都应当保持可空——除非你百分之百确信该字段本身绝对不会抛错或返回 null,并且它的所有子字段、孙字段乃至更深层的后代字段,也绝不会因为抛错或返回 null 而一路向上级联导致该根字段变为 null。
In PostGraphile, two of our Query fields are not nullable because they adhere
to this check:
在 PostGraphile 中,只有两个 Query 根字段满足这一严苛标准,因此被设为非空:
-
nodeIdreturns a constant value (the string 'query') so it can never errornodeId始终返回一个常量值(字符串 'query'),永远不会出错 -
queryreturns theQueryobject again (it's a Relay 1 hack) and so it has all the same guarantees as the Query objectquery直接再次返回Query对象自身(这是为了兼容 Relay 1 的特殊设计),因此具备与根 Query 对象完全相同的可靠性保证
Everything else is nullable, because errors happen and we don't want them to cascade to sibling fields.
除此之外的所有根字段均为可空,因为错误总是难免发生,我们绝不希望单个字段的异常级联影响到其他同级字段。
To make this even clearer: if our mutation fields were "not nullable" and you performed a mutation such as this:
为了更直观地说明这一点:假设我们的 mutation 字段都被设为“非空”,而你执行了下面这个包含多个操作的变更请求:
mutation {
createSecret(input: {label: "Foo"}) { secret }
someOtherMutation(input: {...}) { ... }
}
If mutations were marked non-nullable and yet for some reason
someOtherMutation threw an error, then the entire GraphQL response would come
back null and you wouldn't see the result of the createSecret mutation. As per
the GraphQL spec: mutations are independent, thus the createSecret mutation
would not be rolled back and the value would be created but never shown.
如果 mutation 字段是非空的,而 someOtherMutation 因故抛出了异常,那么整份 GraphQL 响应都会变成 null,导致你根本看不到 createSecret 的执行结果。更糟的是,依据 GraphQL 规范,各 mutation 字段彼此独立执行,createSecret 并不会因此回滚——数据实际上已经被创建,客户端却永远无法获知结果。
Relations: RLS visibility关联关系(Relation):RLS 可见性
PostgreSQL uses foreign keys to assert that relations exist. Take this SQL schema:
PostgreSQL 使用外键来保证表之间的关联确实存在。请看下面这段 SQL schema:
create table person (
id serial primary key,
username citext not null
);
create table post (
id serial primary key,
author_id int not null references person on delete cascade,
body text not null
);
From this we know that given a Post record exists, then the associated
Person object must also exist — PostgreSQL guarantees this. So why does
PostGraphile mark the Post.personByAuthorId field as nullable? Well, consider
this:
由此可知,只要一条 Post 记录存在,其关联的 Person 对象就必然存在——这是 PostgreSQL 在数据库层面提供的保证。既然如此,PostGraphile 为什么还要把 Post.personByAuthorId 字段标记为可空呢?不妨考虑下面这种 RLS 策略:
-- Users can only see their own 'Person'
create policy select_self on person for select using (id = current_user_id());
-- Users can see all Posts
create policy select_all on post for select using (true);
Given the above, it's possible for you to be able to see a Post without you being allowed to see the associated Person. So even though the person definitely exists, that doesn't guarantee that you can see them.
在这种策略配置下,当前用户完全有可能有权查看某篇 Post,却无权查看对应的作者 Person。也就是说,即便数据库里那位作者确实存在,也并不意味着你有权限读取该记录。
Fields under mutation payloadsMutation payload 中的字段
For similar reasons to the Relations above, it's possible for you to be able to create something but then not see the result of that — it really depends how you've defined your security. For example, if you create a truly anonymous "feedback" item then there's nothing in it to indicate that you're allowed to view it.
基于与上述 relation 相同的原因,在权限配置下,你完全有可能“有权创建某条记录,却无权在创建后查看它”——这完全取决于你的安全策略是如何定义的。例如,当用户提交一条完全匿名的“意见反馈(feedback)”时,记录本身没有任何属性能够证明当前用户有权读取它,因此 mutation payload 中的结果字段也必须允许为 null。
What about nullable nodes in table connections?为什么表 Connection 中的节点也是可空的?
This one at first seems obviously a mistake — of course if I request a list of
rows from a table or function I'm not going to get some rows and some nulls -
they'll either all fail or all succeed... Surely? Well, it turns out: no -
functions which return connections (that is
CREATE FUNCTION ...(...) RETURNS SETOF table_type AS ...) can return nulls as
well as table rows. In my opinion, doing so is a bad practice.
这一点乍看之下简直像是个设计失误——按常理来说,从表或函数查询一组记录时,结果要么全部成功返回数据行,要么整体失败,怎么可能一部分是正常行、一部分是 null 呢?可实际情况恰恰如此:返回 Connection 的函数(即 CREATE FUNCTION ...(...) RETURNS SETOF table_type AS ...)在返回表记录的同时,确实有可能夹杂返回 null 值(尽管在我看来这种写法并不妥当)。
If you can commit to never returning null rows in your SETOF functions, then
you can use the preset.schema.pgForbidSetofFunctionsToReturnNull setting to change this
behaviour. I recommend this flag; but it's disabled by default to maximise
compatibility (also going from nullable to non-nullable is fine, but going the
other way is a breaking change).
如果你能确保自己的 SETOF 函数永远不会返回空行,可以通过配置项 preset.schema.pgForbidSetofFunctionsToReturnNull 来改变这一默认行为。我个人很推荐开启此选项;之所以默认关闭,是为了最大限度保障兼容性(毕竟日后从可空改为非空属于兼容变更,而反过来从非空改回可空则是破坏性变更)。
export default {
// ...
schema: {
pgForbidSetofFunctionsToReturnNull: true,
},
};
What about computed fields?计算字段(Computed fields)呢?
It's very easy for computed fields (functions) to throw an error due to a logic issue in the function. We don't want that bringing down the entire schema so we leave these as nullable.
计算字段本质上对应数据库函数,函数内部的业务逻辑很容易因为各种边界情况抛出异常。我们不希望一个计算字段的报错波及整个查询树,因此默认将计算字段保持为可空。
I'd be happy to accept a Pull Request that adds functionality marking a function
as non-nullable via a smart comment (e.g.
COMMENT ON FUNCTION foo_func(foo) IS E'@notNull';) — do raise an issue if this
is of interest to you. Even with this, though, it would be unwise to mark
root-level functions as non-nullable — what if the PostgreSQL connection is
terminated when resolving that field, should that make all the other fields null
too? GraphQL best practices suggest that we should keep errors as localised as
we can.
如果你希望通过 smart comment(例如 COMMENT ON FUNCTION foo_func(foo) IS E'@notNull';)将函数显式标记为非空,欢迎先提一个 issue 讨论,我也非常乐意接受相应的 Pull Request。不过即便支持了这一特性,将根级别的函数标记为非空依然是不明智的——试想在解析该字段时若 PostgreSQL 连接意外中断,难道要连带让同级其他所有字段的结果也都变成 null 吗?GraphQL 最佳实践始终倡导将错误的影响范围尽可能局部化。
I've read the above, but I still want this particular thing to be non-nullable!我理解上述原因,但还是希望把特定字段设为非空!
Sure! PostGraphile is built with extensibility and customizability in mind — you can fix that with a plugin.
当然可以!PostGraphile 在设计之初就充分考虑了可扩展性与可定制性——你完全可以通过插件来调整这一行为。
Here's a plugin which looks for all forward relation fields (like
personByAuthorId) and changes their definition so that their type is the
GraphQLNonNull-wrapped version of their original type:
下面是一个插件示例,它会筛选出所有正向关联(relation)字段(如 personByAuthorId),并将其字段类型修改为用 GraphQLNonNull 包装后的非空版本:
const NonNullRelationsPlugin: GraphileConfig.Plugin = {
name: "NonNullRelationsPlugin",
description:
"Makes foreign key fields non-nullable if their columns are all `not null`",
version: "0.0.0",
schema: {
hooks: {
// Hook a field that has already been defined
GraphQLObjectType_fields_field(field, build, context) {
const {
graphql: { GraphQLNonNull, getNullableType },
pgRelations,
} = build;
// Extract details about why this field was defined.
const { isPgSingleRelationField, pgRelationDetails } = context.scope;
// See if the field was defined for a singular relation
if (isPgSingleRelationField && pgRelationDetails) {
// If so, extract details about the relation
const { codec, relationName } = pgRelationDetails;
// Look up the relation in the registry
const relation = pgRelations[codec.name][relationName];
// Determine if every column is non-null
const everyColumnIsNonNull = relation.localAttributes.every(
(attrName) => codec.attributes[attrName].notNull,
);
if (!relation.isReferencee && everyColumnIsNonNull) {
// If so, change the type of the field to be non-nullable
field.type = new GraphQLNonNull(getNullableType(field.type));
}
}
return field;
},
},
},
};
If there's other things that are null but you think should not be, please raise and issue on GitHub and we'll either fix it, or update this document to explain why it's nullable.
如果 schema 中还有其他你认为本不该为 null 的字段,欢迎在 GitHub 上提交 issue——我们会视情况修复它,或者补充更新本文档以说明其保持可空的原因。