Marks a mutation field as fully generated and picks the SQL shape (INSERT, UPDATE, DELETE, UPSERT). The write runs inside a transaction graphitron opens, with a primary-key-only RETURNING; a @table-typed response is then read back by a follow-up SELECT keyed on those primary keys, so the response selection set never widens the write statement itself. On the owned-connection path that transaction is the field’s own and covers the read-back too: the write, the follow-up SELECT and the payload’s nested reads commit or roll back together (Transactions on the owned-connection path). The delegated alternative carries no boundary of its own on the escape-hatch path: see @service.
Every INSERT, UPDATE and UPSERT checks the strings it writes against their columns' declared lengths before the statement runs, and rejects an over-long value without writing anything; see the column-length check.
SDL signature
directive @mutation(typeName: MutationType!, multiRow: Boolean = false, table: String,
failOnMissing: Boolean = false) on FIELD_DEFINITION
enum MutationType { UPDATE, DELETE, INSERT, UPSERT }
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
|
|
(required) |
The SQL shape to emit. |
|
|
|
On |
|
|
(none) |
Names the SQL table to write to, on the consuming field. It gives a write that carries no table on its return side a field-relative write target: a bare |
|
|
|
On a |
Input shape
A @mutation field takes exactly one input argument. Its fields bind to columns of the write target’s table (@field(name:), or the SDL name by default). The input type carries no table directive of its own (@table on an input is a deprecated location and is ignored): for INSERT and UPDATE the write target is derived from the field’s return (see Naming the INSERT and UPDATE write target), and for DELETE it is named on the field with @mutation(table:) (see Naming the DELETE write target).
An input field may also be a nested input object: a grouping shape whose own fields map onto columns of the same table. The grouping carries no DML semantics; the leaves flatten onto the outer write target as if declared at the top level, and absent-vs-null is honored independently at every nesting layer (an absent or null group skips its whole subtree; a present group descends per leaf). The tutorial’s Grouping fields with nested input types walks a worked example. A nested input introducing a second DML target is a separate compound-mutation shape and is not admitted here.
Canonical example
The tutorial’s film mutations cover the two most common shapes. Neither input carries a directive; the write target is derived from the Film return type (Film carries @table(name: "film")):
input FilmCreateInput {
title: String! @field(name: "title")
languageId: Int! @field(name: "language_id")
}
input FilmUpdateInput {
filmId: Int! @field(name: "film_id")
title: String! @field(name: "title")
}
type Mutation {
createFilm(in: FilmCreateInput!): Film @mutation(typeName: INSERT)
updateFilm(in: FilmUpdateInput!): Film @mutation(typeName: UPDATE)
}
The INSERT shape produces a two-step exchange. The write commits inside a transaction with a primary-key-only RETURNING:
INSERT INTO film (title, language_id)
VALUES (?, ?)
RETURNING film.film_id
and the response selection set is then read back by a follow-up SELECT keyed on the returned primary key:
SELECT film.film_id AS "filmId", film.title AS "title"
FROM film
WHERE film.film_id = ?
The follow-up SELECT narrows to the response selection set: a mutation that asks for { filmId title } retrieves only those columns. On the escape-hatch path the write has already committed when the read-back runs, so an error during the response SELECT surfaces as a field error and cannot undo the write. On the owned-connection path the read-back runs inside the field’s transaction, so such an error fails the field and rolls the write back.
For a bulk mutation (list input, [Film!]! return), the follow-up SELECT joins a VALUES (idx, pk) table over the returned keys and orders by idx. The payload list contains one entry per written row, in the order the rows were written, mirroring @lookupKey's ordering contract ("returns a list of results in the same order").
UPDATE identifies the target row by which input columns cover a primary key or unique key of the write-target table (inferred from the jOOQ catalog, no directive needed): the matched key’s columns become the WHERE clause and the remaining input fields populate the SET clause. UPSERT adds ON CONFLICT keyed on the matched key’s columns.
Most input fields fall wholly on one side of that boundary, but a @nodeId reference to another table need not: it expands into the foreign key’s child columns on the write target, and those can include columns the matched key also covers. Such a field partitions per column rather than being rejected. Its out-of-key columns become SET writes; its in-key columns are the row’s identity, so they contribute to the WHERE clause where no other field supplies them, and are otherwise only checked. Where both the reference and another field decode a value for the same column, the two are compared before any DML runs and a mismatch fails the call with an error naming both input fields, writing nothing. The foreign key forces them equal for well-formed input, so this only catches a caller who sent a reference belonging to a different row.
A reference in that shape may be nullable (ID). Its in-key half is row identity and is therefore never written, so an explicit null clears only its out-of-key half: those columns are written NULL, and the in-key columns stay as the rest of the input pins them. A half-null foreign key imposes no referential obligation under PostgreSQL’s default MATCH SIMPLE, so a cleared reference is an absent one rather than a dangling one. A cleared reference supplies no value, so it takes no part in the comparison above. The build rejects the nullable spelling in one shape only: when the reference is the sole supplier of one of the matched key’s columns, since an omitted or cleared value would leave nothing to find the row by. Give that column another contributor, or spell the reference ID!.
A field carrying the row’s own columns is still rejected when it straddles part of the matched key, because writing only some of a row’s key columns would move the row rather than update it. The exception is a node id whose key columns are the whole matched key plus more, for example a type declared @node(keyColumns: ["inventory_id", "store_id"]) over a table whose primary key is inventory_id. Such an id identifies the row by the matched key alone: its other columns are neither filtered on nor written. Another field may write them; a storeId: Int @field(name: "store_id") beside the id moves the item to another store, and the payload’s ids encode the new value. An id minted before that change still updates the row.
DELETE identifies rows the same way (primary-key-or-unique-key coverage), but has no SET clause: every admitted input column is a WHERE filter, and the deleted row’s primary key is returned through RETURNING. Extra input columns beyond the matched key add further AND`ed predicates (they narrow the match, they don’t move to a `SET side). A node id whose key columns are the whole matched key plus more is the exception: it filters on the matched key only, so an id whose extra columns have since changed still deletes its row. When the input covers no primary key or unique key, the DELETE is rejected at build time so a non-unique filter cannot silently broadcast; set multiRow: true on the @mutation directive to opt into a deliberate broadcast (non-key) delete that may remove more than one row. A key that matches no row counts as already deleted, which an input covering a unique key or carrying extra filter columns cannot express; such an input needs failOnMissing: true (see When a DELETE key matches no row).
Naming the INSERT and UPDATE write target
An INSERT or UPDATE usually names its write target on the return side: the written row’s type is the natural return. Graphitron derives the write target by this precedence:
-
The return’s own
@table(preferred). A direct@tablereturn (createFilm(…): Film,Filmcarrying@table), or a carrier payload whose single data field is a@table-element (createFilms(…): FilmsPayload,FilmsPayload { films: [Film!] }). The input’s fields resolve against the return’s table. -
@mutation(table:)on the field. For the encoded-ID/ scalar-return field whose return names no table (createFilm(in: FilmInput!): ID @mutation(typeName: INSERT, table: "film")).
Where the return names the table, a @mutation(table:) also present must name the same table (the RETURNING projection reads from the write target, so a disagreement cannot emit a coherent statement); a mismatch is rejected at build time. A field that names its table by neither rung is rejected, with the message leading with the preferred return-derived fix.
input FilmInput { # no directive: the write target is derived from the return
title: String! @field(name: "title")
}
type FilmsPayload { films: [Film!] } # Film is @table(name: "film")
type Mutation {
createFilms(in: [FilmInput!]!): FilmsPayload @mutation(typeName: INSERT)
}
Naming the DELETE write target
DELETE cannot use the return-derived rung: it commonly returns a bare ID (the encoded primary key of the deleted row), a Boolean, or a delete count, and it can never return the deleted row’s @table type, because the row is gone after the statement runs. So a DELETE names its write target on the consuming field with @mutation(table:):
input FilmDeleteInput {
filmId: Int! @field(name: "film_id")
}
type Mutation {
deleteFilm(in: FilmDeleteInput!): ID @mutation(typeName: DELETE, table: "film")
}
The input type carries no directive; its fields resolve against the table named on the field. A DELETE that does not name its table with @mutation(table:) is rejected at build time, with the message steering you to the argument. (An input type still carrying a legacy @table builds with a warning; the directive is ignored, so it does not name the table either. See the deprecated location.)
Payload-returning DELETE
@mutation(typeName: DELETE) returns the ids of the rows it removed, on the field itself or on a field of the payload type it returns. Cardinality follows the carrier field’s wrapper: ID for a single DELETE, [ID!] for a bulk one.
Echoing the deleted ids
The payload returns the encoded NodeId of each deleted row:
type SlettRegelverksamlingPayload {
deletedIds: [ID!] # implicit @nodeId; encoder resolves against the write-target table's @node
}
extend type Mutation {
slettRegelverksamling(input: [RegelverksamlingDeleteInput!]!): SlettRegelverksamlingPayload
@mutation(typeName: DELETE)
}
The carrier field’s element type must be ID (single DELETE) or [ID!] (bulk DELETE). The list wrapper must be list-of-non-null; [ID] (list-of-nullable) is rejected, because every element of a successful DELETE response is the encoded PK of an actually-deleted row, the slot cannot be null. The encoder is recognised implicitly when the mutation’s write-target table backs a @node type. If the write-target table is not @node-backed, the carrier is rejected; register the table’s SDL type as @node first. To pin the encoder explicitly (recommended when grep-ability matters), attach @nodeId(typeName: "…") to the carrier field; the directive’s encoder must resolve to the same table as the mutation’s write target. An @nodeId whose encoder resolves to a different table is rejected: you would be returning IDs of a different entity than the one the DML acted on.
The response holds one id per input key, in input order: a deleted row’s id, or, for a key that matched no row, the id the input supplies (see When a DELETE key matches no row). When the node type’s key columns go beyond the primary key, a deleted row’s extra columns are read back from the row, so its id encodes the row as it was stored rather than as the input id described it.
What you can’t return
-
Arbitrary non-PK columns of the deleted row. The row is gone;
RETURNINGis narrowed to primary-key columns, plus the node key’s other columns where the payload’s ids encode them. If you need the full pre-delete state, snapshot it in your application code before issuing the mutation. -
The deleted row’s
@tabletype, even one whose fields are all primary-key columns. Reading a type by a row’s keys finds no row after a DELETE, so the build rejects it (REREAD_OF_DELETED_ROWS). Return the ids instead. -
A bare class-backed payload type. Use a NodeId echo.
When a DELETE key matches no row
A DELETE treats a key that matches no row as already deleted. The rows that exist are deleted, the call commits, and the response holds every input key in input order, whether or not its row existed. A retried call, or two clients deleting the same row, then succeed, and the response does not tell the caller which rows existed. This holds whether the field returns a payload or ID / [ID!] directly.
To answer a key whose row is gone, Graphitron builds its id from the input, so the input must identify rows by exactly the table’s primary key, directly or through a node id. A node id whose key columns go beyond the primary key qualifies; a key that matches no row is answered with the id the client sent. An input keyed by a unique key, or one with a filter column beyond the primary key, fails the build: a unique key cannot be turned into the primary key for a row that is not there, and an extra filter column would let a row that survives the filter be reported as deleted. If the response’s ids need columns beyond the primary key and the input supplies only the primary key’s plain fields, the build fails too, because nothing in the input says what a missing row’s id would have encoded; key the input by the node id instead. Each of these failures also takes failOnMissing: true as its way out.
Set failOnMissing: true to fail the call on such a key instead. Nothing is deleted, and the field reports an error: a typed one if a handler in the payload’s errors field matches, otherwise a redacted one. A single-row DELETE fails the same way. failOnMissing admits any input that covers a primary key or unique key, extra filter columns included.
deleteStorageBinByCodePayload(in: StorageBinDeleteByCodeInput!): DeletedStorageBinPayload
@mutation(typeName: DELETE, table: "storage_bin", failOnMissing: true)
A multiRow: true DELETE whose input covers a primary key or unique key follows the same rule. One whose input covers no key deletes whatever its filter matches and names no key, so neither reading applies to it, and failOnMissing is rejected there.
A list-input DELETE that names keys runs one statement per input row inside one transaction, so the response can answer each key in its own slot.
Payload with an errors field
A payload may declare an errors-shaped field beside its data field, a list of @error types; the errors-channel how-to covers the types themselves. When the write raises an exception one of the handlers matches, the transaction rolls back and the field renders { films: null, errors: [<typed error>] } with no field error. On success the data field carries the written rows and errors is null.
type FilmsPayload {
films: [Film]
errors: [FilmWriteError]
}
Two rules follow from that:
-
On the error path a nullable data field renders
null. A non-null list data field renders[], since nothing was written; declare[Film!]!when your clients should never seenullthere. Every other data field must be nullable:Film!beside an errors field is rejected at build time, because there is no empty value to give it and anullwould let null propagation erase the errors list. A connection (@asConnection) counts as a single value here, not a list. -
A single-row write whose key matches no row renders the whole payload
null, the same as on a payload without an errors field. ADELETEis the exception: it answers the key it was sent, or, withfailOnMissing: true, fails into the errors list (see When a DELETE key matches no row).
Give one @error type in the errors field {handler: VALIDATION} and the column-length check’s errors become entries in the errors list rather than top-level errors; see the column-length check. Without that member a payload with an errors field skips the check.
The same rules hold in a database-per-tenant build: the payload’s fields read the tenant the write ran on, and the errors travel with the payload.
When an UPDATE key matches no row
A list-input UPDATE that returns a payload fails the whole call when any input row’s key matches no row: nothing is written, and the field reports an error, a typed one if a handler in the payload’s errors field matches, otherwise a redacted one. Graphitron runs every row before failing, so the error counts all of them. The exception is <outputPackage>.schema.ZeroRowsMatchedException, generated into your output package; it is an IllegalStateException whose message contains "matched zero rows", and it tells you which rows missed:
@Override
public String unmatchedMessage(Throwable thrown, String reference, DataFetchingEnvironment env) {
if (thrown instanceof ZeroRowsMatchedException miss) {
return miss.missCount() + " of " + miss.rowCount()
+ " rows in this write were not found, or are not writable for you.";
}
return FetcherErrorResponse.super.unmatchedMessage(thrown, reference, env);
}
missedRowIndices() gives the zero-based input positions, and fieldCoordinate() the field, as Mutation.updateFilms. A key that matches no row may be a row the caller is not allowed to see, so decide how much of this to show. A list-input UPDATE that returns the @table type or ids directly does not fail on a missed key: it returns the rows it wrote.
Constraints
-
INSERTandUPDATEderive their write target from the return (a@tablereturn, or a payload’s@table-element data field), falling back to@mutation(table:)for an encoded-ID/ scalar return (see Naming the INSERT and UPDATE write target).DELETEnames its write target with@mutation(table: "…")on the field (it cannot derive the table from its return type, since the row is gone after the statement). A field with no write-target source is rejected at build time, with the message naming the applicable fix.@tableon the input type is a deprecated location, ignored rather than consulted, so it is never a write-target source. -
UPDATEandDELETErequire the input columns to cover a primary key or unique key of the write-target table (inferred from the catalog, no directive needed); otherwise the build fails so a non-unique filter cannot silently broadcast.DELETEcan opt out withmultiRow: truefor a deliberate broadcast;UPDATEhas no broadcast shape (cover a key).@lookupKeyis declared on arguments only, so schema assembly refuses it on a mutation input field, where it identified rows in the pre-catalog model; remove it. -
UPDATErequires at least one input field outside the matched key (otherwise theSETclause is empty).DELETEhas no such requirement — a key-only DELETE is the canonical single-row delete.UPSERTis exempt on the SET side: an upsert with no SET-clause fields isINSERT … ON CONFLICT DO NOTHING, which is a legitimate shape.The
UPDATErule is about the input type. A request may still leave every one of those fields out, or send a nested group as absent ornull: the row is then an empty patch. Graphitron issues noUPDATEfor it, reads the row back by its key, and returns it in the payload in the row’s position, as it would an updated row; other rows in the same list input update normally. An empty patch on a key that matches no row behaves like anyUPDATEon that key: a single-row mutation resolvesnull, and a list input with a payload raises the same "matched zero rows" error its error handlers already see (see When an UPDATE key matches no row). -
A field returning a bare
ID(INSERT,UPDATEorDELETE) returns the node id of the written row, so exactly one@nodetype must declare itself over the write-target table. No such type isNODE_ID_TARGET_UNRESOLVED: declare@nodeon the table’s type. Several areNODE_ID_TARGET_AMBIGUOUS: return the node type you mean instead of a bareID. -
@mutationand@serviceare mutually exclusive on the same field. Pick one:@mutationfor fully-generated DB operations,@servicefor handing the operation to custom Java. -
Optional input fields participate in the operation only when the client provides them. Absent optional fields are omitted from the
SETclause (UPDATE/UPSERT) and from the column list of a single-rowINSERTand of a bulkINSERTwhose rows supply the same fields, so the database applies each column’s default without being asked by name. A bulkINSERTis one statement with one column list: when its rows differ, the list covers every field some row supplies, and a row that leaves one of those out writesDEFAULTfor it. A bulkINSERTof several rows that supply no field at all names every column withDEFAULT, since an empty column list would insert a single row. AnINSERTthat supplies no field at all rendersdefault values, which jOOQ emulates with aDEFAULTper column on a database that lacks that clause, Oracle among them. Oracle rejects an explicitDEFAULTagainst a view (ORA-32575), so on an Oracle view these three shapes fail at the database: a bulkINSERTwhose rows differ, one whose rows supply no field, and anINSERTwith no field at all.
See also
-
Tutorial page 5: A first mutation walks the
INSERT/UPDATEflow against a running database. -
@lookupKeyis a Query-side lookup-key marker onARGUMENT_DEFINITION; it no longer participates in mutation row identification (that is catalog-derived). -
@tablebinds the object types whose returns carry a write target; on input types it is a deprecated location and is ignored. -
@servicefor custom-Java mutations.