Skip to main content

CRUD mutations

CRUD, or “Create, Read, Update, Delete”, is a common paradigm in data manipulation APIs; “CRUD Mutations” refer to all but the “R”. PostGraphile will automatically add CRUD mutations to the schema for each table that has the relevant database permissions.

CRUD 即“增删改查”(Create、Read、Update、Delete),是数据操作 API 中常见的范式;其中“CRUD Mutation”指的是除“R(读取)”之外的增、删、改操作。PostGraphile 会针对每张拥有相应数据库权限的表,自动在 schema 中生成这些 CRUD mutation。

Designing mutations设计 Mutation​

CRUD mutations can easily be disabled by disabling the insert, update and delete behaviors in your preset:

在 preset 中禁用 insert、update 和 delete 这几个 behavior,即可轻松关闭自动生成的 CRUD mutation:

graphile.config.mjs
export default {
// ...
schema: {
defaultBehavior: "-insert -update -delete",
},
};

You might do this if you prefer to define all of your mutations yourself (e.g. with custom mutations).

如果你更倾向于完全由自己来定义所有 mutation(例如通过自定义 Mutation),就可以采用这种做法。

It’s a common misconception for people unfamiliar with PostGraphile that its main feature is the CRUD mutations. In actuality, a very significant portion of users (including the maintainer) hardly ever use the CRUD mutations. PostGraphile encourages you to write the best GraphQL API that you can, so before designing your mutations we strongly recommend that you read Marc-André Giroux’s excellent GraphQL Mutation Design: Anemic Mutations article.

不熟悉 PostGraphile 的人常有一个误解,以为它的核心卖点就是自动生成 CRUD mutation。实际上,相当大比例的用户(包括项目维护者本人在内)几乎从不使用 CRUD mutation。PostGraphile 鼓励你打磨出最优质的 GraphQL API,因此在动手设计 mutation 之前,我们强烈推荐你先阅读 Marc-André Giroux 的精彩文章 GraphQL Mutation Design: Anemic Mutations。

PostGraphile gives you a lot of ways to define your own mutations (from database functions, to schema extensions, to custom plugins), so you can pick whichever pattern you and your team are most comfortable with.

PostGraphile 提供了多种定义自定义 mutation 的方式——包括数据库函数、schema 扩展以及自定义插件,你和团队可以自由挑选最趁手的方式。

PostGraphile brings more than just handling CRUD mutationsPostGraphile 的价值远不止于处理 CRUD mutation

You might be wondering, "What value do users see in PostGraphile if not the CRUD mutations?" These users typically recognize PostGraphile’s significant efficiency gains in the query schema — meaning they can handle larger amounts of traffic and don’t need to concern themselves with the complexities of caches and cache invalidation for a lot longer. There’s also the consistency afforded through (and time saved by) autogeneration; the GraphQL best practices enabled by the out-of-the box schema; and the easy schema-wide changes via the plugin and behavior systems. These are just some of the well-known key features of PostGraphile.

你可能会好奇:“既然不是为了 CRUD mutation,那用户看重 PostGraphile 的究竟是什么?”这类用户通常更认可 PostGraphile 在 Query schema 上带来的巨大执行效率提升——这意味着他们能轻松承接更高流量,在很长一段时间内都不必过早陷入缓存与缓存失效的泥潭。此外,自动生成带来的一致性与时间节省、开箱即用便符合 GraphQL 最佳实践的 schema,以及借助插件与 behavior 系统实现的全局灵活定制,都是 PostGraphile 广受认可的核心优势。

CRUD mutation fieldsCRUD mutation 字段​

Using the users table from the parent article, depending on the PostGraphile settings you use (and the permissions you’ve granted), you might get the following mutations:

以上一篇表介绍文章中的 users 表为例,根据你所用的 PostGraphile 配置(以及授予的数据库权限),你可能会得到以下 mutation 字段:

  • createUser - Creates a single User. See example.

    createUser —— 创建一条 User 记录。查看示例。

  • updateUser - Updates a single User using its globally unique id and a patch.

    updateUser —— 通过全局唯一 id 与 patch 更新一条 User 记录。

  • updateUserById - Updates a single User using a unique key and a patch. See example.

    updateUserById —— 通过唯一键与 patch 更新一条 User 记录。查看示例。

  • updateUserByUsername - Updates a single User using a unique key and a patch.

    updateUserByUsername —— 通过唯一键与 patch 更新一条 User 记录。

  • deleteUser - Deletes a single User using its globally unique id.

    deleteUser —— 通过全局唯一 id 删除一条 User 记录。

  • deleteUserById - Deletes a single User using a unique key. See example.

    deleteUserById —— 通过唯一键删除一条 User 记录。查看示例。

  • deleteUserByUsername - Deletes a single User using a unique key.

    deleteUserByUsername —— 通过唯一键删除一条 User 记录。

The update and delete mutations are created only if the table contains a primary key column.

仅当表中包含 primary key(主键)列时,才会生成 update 和 delete mutation。

You also get the following query fields (“Read”):

同时你还会获得以下查询字段(即 CRUD 中的“Read”):

  • user - Returns a single User using its globally unique ID.

    user —— 通过全局唯一 ID 返回单条 User 记录。

  • userById - Reads a single User using its globally unique ID.

    userById —— 通过全局唯一 ID 读取单条 User 记录。

  • userByUsername - Reads a single User using its unique username.

    userByUsername —— 通过唯一的 username 读取单条 User 记录。

  • allUsers - Returns a connection enabling pagination through a set of (visible) User.

    allUsers —— 返回一个 Connection,支持对所有(可见的)User 进行分页查询。

Examples示例​

Create创建(Create)​

# Create a User and get back details of the record we created
mutation {
createUser(
input: { user: { id: 1, name: "Bilbo Baggins", username: "bilbo" } }
) {
user {
id
name
username
createdAt
}
}
}

Update更新(Update)​

# Update Bilbo using the user.id primary key
mutation {
updateUserById(
input: { id: 1, userPatch: { about: "An adventurous hobbit" } }
) {
user {
id
name
username
about
createdAt
}
}
}

Delete删除(Delete)​

# Delete Bilbo using the unique user.username column and return the mutation ID
mutation {
deleteUserByUsername(input: { username: "bilbo" }) {
deletedUserId
}
}

If mutations don’t show up...如果 mutation 没有出现……​

First of all, check for errors being output from your PostGraphile server. If there are no errors, here’s some reasons that mutations might not show up in the generated schema:

首先请检查 PostGraphile 服务端是否有报错输出。若无报错,生成的 schema 中未出现 mutation 可能有以下原因:

  • Your behaviors (e.g. defaultBehavior: "-insert -update -delete" or @behavior -insert -update -delete smart comments on the tables) may be disabling them

    behavior 配置将其禁用了(例如 defaultBehavior: "-insert -update -delete",或在表上添加了 @behavior -insert -update -delete smart comment)

  • Insufficient permissions on the tables

    对相应表的数据库权限不足

  • Tables not in an exposed schema

    表未位于对外暴露的 schema 中

  • Views instead of tables

    目标对象是视图(view)而非表

  • Missing primary keys (though ‘create’ mutations will still be added in this case)

    表缺少主键(不过这种情况下仍会生成 create 类的 mutation)

  • If you only see mutations using primary key: You might be using the PrimaryKeyMutationsOnlyPlugin

    如果只看到了基于主键的 mutation:你可能启用了 PrimaryKeyMutationsOnlyPlugin

If you’re new to GraphQL, perhaps you’re looking in the wrong place? In Ruru (the GraphiQL interface), open the docs on the right and go to the root. Select the Mutation type to see the available mutations. If you try to execute a mutation (e.g. using autocomplete) you must use the mutation operation type when composing the request:

如果你刚接触 GraphQL,也可能是看错了位置。在 Ruru(即 GraphiQL 界面)中打开右侧文档面板并回到根节点,选择 Mutation 类型即可查看所有可用的 mutation。若要执行某个 mutation(例如配合自动补全编写请求),在构造请求时必须显式使用 mutation 操作类型:

mutation {
createThing...
}

otherwise GraphQL will interpret the request as a query.

否则 GraphQL 会将该请求按 query 来解析。