Declares an explicit foreign-key path between the field’s parent table and the field’s target table. The generator threads the path through jOOQ’s catalog and emits a JOIN whenever the field is selected.
The directive is repeatable on output field definitions: repeated applications compose one table chain in the order they are written, and they compose with @routine so a database function can sit anywhere in the chain.
SDL signature
directive @reference(
path: [ReferenceElement!]!
) repeatable on FIELD_DEFINITION | ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION
input ReferenceElement {
table: String,
key: String,
condition: ExternalCodeReference
}
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
|
|
(required) |
Ordered list of hops from the parent table to the target table. Each element pins one hop by table name, foreign-key constraint name, or an external join condition. |
ReferenceElement fields:
| Name | Type | Default | Description |
|---|---|---|---|
|
|
inferred from the field’s target type |
The jOOQ table identifier for this hop’s destination. Overrides the type-level |
|
|
inferred when unique |
The foreign-key constraint name (matching jOOQ’s |
|
|
none |
An external Java method that returns a |
Canonical example
The tutorial’s Customer.address is a single-hop reference along a named foreign key:
type Customer @table(name: "customer") {
address: Address @reference(path: [{key: "customer_address_id_fkey"}])
}
customer_address_id_fkey is the FK constraint declared in init.sql as address_id int NOT NULL REFERENCES address(address_id). A query selecting customers { address { district } } emits:
SELECT customer.first_name AS "firstName",
address.district AS "district"
FROM customer
LEFT JOIN address ON customer.address_id = address.address_id
The JOIN is added only when the selection set traverses through address; selecting only firstName skips it.
@reference chains across hops. From the same Customer type:
storeAddress: Address @reference(path: [
{key: "customer_store_id_fkey"},
{key: "store_address_id_fkey"}
])
The path is customer.store_id → store.store_id → store.address_id → address.address_id: two FKs and three tables touched, but still a single SQL statement with the same projection-narrowing.
When exactly one foreign key exists between two tables, @reference is unnecessary and the generator picks the path automatically:
type Store @table(name: "store") {
customers: [Customer!]! @defaultOrder(primaryKey: true)
}
There is exactly one FK between customer and store (customer.store_id), so the join is implicit. Multiple-FK cases must declare the path explicitly: the generator does not guess.
Composing chains with repeated applications
On an output field definition, @reference may be applied more than once. The applications' path elements concatenate in the order they are written, over one running source, so the composed chain is exactly the longer path you could have written in a single application:
type Film @table(name: "film") {
castActors: [Actor!]
@reference(path: [{key: "film_actor_film_id_fkey"}])
@reference(path: [{key: "film_actor_actor_id_fkey"}])
@defaultOrder(primaryKey: true)
}
On its own this form is a stylistic choice. It exists for composition with @routine: the directives on a field, read left to right, describe the path your data travels, starting at the enclosing type’s table and ending at the field’s type, and a routine node can sit before, between, or after the @reference hops. See the @routine page for the chain rule and the routine-bearing shapes.
The order is load-bearing. Directive application order is semantically significant here, which the GraphQL spec sanctions and graphql-java preserves. Tooling that rewrites SDL and reorders repeatable directive applications (schema printers, federation composition pipelines) is out of contract: the terminus and keying checks catch most reorders, but two orderings can both terminate correctly and mean different join graphs, so an order-preserving round-trip is a stated requirement on any SDL tooling in your pipeline.
Constraints
-
In a chain of several applications, every application must carry at least one path element; an element-less application is rejected with
must carry at least one path element(element-less FK inference resolves between the field’s endpoints, and an application inside a chain has no endpoints of its own). -
Repetition is legal only on output field definitions. Repeated
@referenceon an argument or an input field is rejected, pointing at the field-level composition surface. -
When more than one foreign key exists between the source and destination tables for a given hop,
keyis required. The build fails with an ambiguous-reference error otherwise. -
When
keyis provided alone,tableis inferred from the FK target. Whentableis provided alone,keyis inferred when unique. Setting both is allowed but redundant. -
A
condition-only hop (notable, nokey) is treated as a joinONcondition; the generator joins the field’s target table and applies the condition. Use this when the join is non-FK or computed.
Path rules
Every field, argument and input field reached in a query has a path: the joins from the row its parent stands on to the row it reads. The rules below decide that path. They are the same rules for output and input, input being the more limited; a filter will extend them.
Output fields
-
Written, inherited or inferred. A path is written with
@reference(or per participant with@referenceFor), inherited from the same-named field of an interface the type implements, or inferred. An interface that extends another overrides the path it redeclares, and@referenceForis inherited member by member. Two interfaces, neither extending the other, that both write the field’s path are an error. -
Inferred between two tables. Between two different tables the path is inferred over exactly one foreign key, in either direction. From the table a
@routinereturns, it is inferred over the target’s primary key, its columns matched by name. -
Inferred on one table. A field whose type is bound to its parent’s table is inferred over the table’s one self-referencing foreign key, its direction taken from the field: a single-valued field follows the key to the row it points at, a list or a connection follows it back to the rows pointing here.
type Category @table(name: "category") { parent: Category # category.parent_category_id -> the parent row children: [Category!] # the rows whose parent_category_id is this one } -
When inference fails, write the path. No foreign key is an error, and so is more than one; name the key with
{key:}. To read the parent’s own row, name its primary key (Joining a row to itself). A same-table field is never read uncorrelated, whatever arguments narrow it. -
An empty path. A field whose type binds no table is a nesting: it reads the parent’s own row. So is the data field of a write’s payload, and a child resolved by a
@serviceof its own. -
A table record a service returns carries its primary key only. The fields under it are resolved by the queries that follow, lifting each record’s key and re-selecting, never by a path from the record.
-
A routine on a child is a join. Only a
@routineon a root field is a call; on any other field it is a step of the field’s path, joined to the rows the function returns.
Arguments and input fields
-
An input is bound to a table record. An argument and the input fields under it are bound to the field’s target table; under a
@service, to the table of the record type of the parameter they fill (aFilmRecordparameter bindsfilm), or of the bean member they fill (aList<PersonTelefonRecord>member bindsperson_telefonfor each element). An input type is never bound to a table itself. -
Without
@referencethe path is empty. A nested input is the same row, unnested into the bound record. -
A filter’s
@referenceis a join in its condition. On an argument or input field that filters, a path lowers to a correlatedEXISTS, single- or multi-hop, by the output rules. -
On an input that fills a record,
@referencegoes with@nodeIdonly. A record does not nest, so a path elsewhere on such an input is an error. -
@nodeId(typeName:)is bound to its node’s table, and always has a path from the bound table to it. The path is inferred as between two output types, over exactly one foreign key in either direction; with none or more than one, write it. A written path is the whole path from the bound table to the node’s. On an input that fills a record it may take several hops only where identity passes along it: each column of the node’s key is carried back through each step’s column pairs to a column of the bound record, and that is the column the decoded key fills. A key column the path does not carry back is refused, naming the column. On a filter, any written path stands. Where the node’s table is the bound table and no path is written, the id is the record’s own key.input InsertEmailReplyInput { # email's key to itself: the decoded Email key fills (mailbox_id, in_reply_to_no), not its own key inReplyTo: ID @nodeId(typeName: "Email") @reference(path: [{key: "email_in_reply_to_fk"}]) } -
A self-referencing key is never inferred on an input. Write it.
Duplicate rows through a junction
A @reference path is foreign-key traversal, and a SQL join produces a bag rather than a set. So a list field whose path passes through a table that can hold more than one row per pair of columns the hops either side of it join on returns the same child row once per such row. That is the correct result of the path you declared, and it is easy to misread: a field named for a set looks like one.
The build says so. A list field over such a path draws a warning under the rule id reference-path-fans-out, naming the table that multiplies and which element of the path it is:
type Film @table(name: "film") {
# inventory is keyed on its own inventory_id, which neither hop binds, so a film
# stocked three times at one store yields that store three times.
stores: [Store!] @reference(path: [
{key: "inventory_film_id_fkey"}, {key: "inventory_store_id_fkey"}])
}
A pure junction stays quiet. film_actor’s primary key is exactly `(actor_id, film_id), which is the pair the two hops bind, so film → film_actor → actor returns each actor once and draws nothing.
The remedy is a relation with set semantics rather than a flag that changes what the join means: declare a view over the junction that selects the bound columns DISTINCT, give it a key for the path to join on, and point the hop at that. Graphitron will not add a DISTINCT for you; it changes what the field returns, and it interacts with ordering and pagination in ways only you can decide.
Five boundaries, each for its own reason:
-
A filter path is not judged, and has nothing to judge. A
@referenceon an argument or an input field lowers to a correlatedEXISTS, so each parent row matches once however far the path fans out. The property does not exist there. -
A
@referenceForpath is not looked at. A quiet build says nothing about one either way. -
A hand-written join stops the rule. Where the element entering or leaving the table joins on a
conditionmethod, or departs a table-valued function’s result, the columns it joins on are in no catalog and the rule declines rather than guessing. This is where an author is likeliest to assume it looked. -
An excluded type is not linted by this rule either. A type matching an
excludedTypesglob is skipped here as it is in the schema linter. -
A scalar field over the same path is a different defect. It lowers to a capped subselect, so it picks an arbitrary row rather than repeating one, and the remedy is an ordering or a narrower path rather than a
DISTINCTview. This rule does not word it.
Silence it like any other rule, by putting reference-path-fans-out in the <lint> block’s disabledRules.
Schema-qualified keys
On a database with more than one schema, two schemas can carry a foreign key under the same constraint name (PostgreSQL scopes constraint names per table, so this is legal). When the generator cannot tell which one a bare {key:} means, and the source table does not resolve the tie, the build fails with an ambiguous-key error.
A {key:} value may carry a leading schema. qualifier to scope the lookup to foreign keys held in that schema, the sibling of the schema.table form on @table:
event: Event @reference(path: [{key: "multischema_a.note_event_fk"}])
The qualifier binds the FK-holder (child / referencing) side, the schema whose generated Keys class declares the constraint, not the FK target’s schema. A qualifier naming a schema that holds no such foreign key is rejected as unresolved; a qualifier that resolves to a foreign key not connected to the current source table is rejected with the same "does not connect" error a wrong bare key gets. Unqualified keys resolve exactly as before; reach for the qualifier only on an actual cross-schema collision.
Joining a row to itself
A {key:} element may name the primary key of the table the path starts on, by its constraint name or its jOOQ Keys constant. The hop joins each row to itself, so the field returns the parent’s own row:
type Film @table(name: "film") {
summary: FilmSummary @reference(path: [{key: "film_pkey"}])
}
type FilmSummary @table(name: "film") { title: String }
This is how a field returns its parent’s row as a @table type, which a field with no @reference cannot: an unwritten path on one table is a join over the table’s self-referencing key, never the parent’s own row (Path rules). The element must be the path’s only element, the field must be single-valued, and its parent and return type must both be bound to the key’s table. Anywhere else, including an argument or input-field path and a @referenceFor path, naming a primary key is rejected. See Map types to tables.
See also
-
Tutorial page 4: Joining tables introduces single-hop and multi-hop references.
-
How-to: Join with references for recipe-shaped variants.
-
@discriminate/@discriminatorfor the union/interface variant. See How-to: Polymorphic types for the supported shapes. -
@referenceForfor the per-participant join path on a multi-table interface/union child field (where a field-level@referenceis rejected). Note the opposite repetition semantics:@referenceapplications concatenate;@referenceForapplications are independent, one per participant. -
@tableestablishes the table binding both endpoints rely on. -
@routinecontributes a database-function node to the same chain; the chain rule and the routine-bearing shapes live there.