Bulk insert mutations with GraphQL
GraphQL insert mutations are used to create new objects in your back-end (typically a database) which can then be queried.
- How many network requests are needed to achieve the inserts?
- How many and how efficient are the insert queries that will actually be run on the database?
- Is each insert independent of others? i.e. is the order of execution important.
- If some of the inserts fail, what happens to the rest of the inserts? Should the rest of the inserts go through or should all the inserts be rolled back?
The Hasura GraphQL Engine
- multiple objects of the same type can be inserted using a single insert mutation field within a mutation. This will be executed as a single SQL statement in the database.
- multiple objects of different types can be inserted using multiple insert mutation fields within the same mutation.
- if there are multiple mutation fields within a mutation, they will be executed sequentially on the database.
- if any of the mutation fields within a mutation fail, all the mutation fields in that mutation will be rolled back. i.e. all the mutation fields within a mutation are run as a transaction.
Setup a GraphQL Project
Insert multiple objects of same type
- If insertion of any row fails (for example due to a duplicate primary key), none of the rows will get inserted.
Insert multiple objects of different types
- In this example, the
articles
can be inserted only after theauthor
is inserted as it would otherwise violate theauthor_id
foreign key constraint. Hence the sequential execution of inserts is necessary here. - If the inserting of
author
fails, the execution of the entire mutation halts and inserting ofarticles
is not even attempted. - If the inserting of
articles
fails, the insertion of theauthor
is rolled back and the database state is restored to what it was before the mutation was attempted.
Related reading