Generated code contains no authorization checks: the database is the enforcement point (see the Security Model and Row-Level Security and the integrity gradient below). Everything else about how a request reaches the database, connection acquisition, transaction demarcation, and mounting the caller’s identity, comes in one of two shapes, and this document is the reference for both:

  • The owned-connection path (recommended). Graphitron owns the connection lifecycle. You give it a dialect once, and per request a connection source; it leases a connection from the source when a field first needs one, commits each mutation field independently, and releases every lease exactly once at completion. See The owned-connection path.

  • The escape-hatch path. You bring your own DSLContext per request and own transaction demarcation and identity yourself; Graphitron’s owned-connection guarantees do not apply. This is the lower-opinion path built on GraphitronContext. See The escape-hatch path.

Both paths read per-request values the same way, through the emitted GraphitronContext and the Graphitron.newExecutionInput(…​) / Graphitron.newOwnedExecutionInput(…​) factories. For the minimal wiring that stands up a working endpoint, see the tutorial; this file picks up where that leaves off.


The owned-connection path

Build the runtime once at wiring time over the jOOQ dialect every context renders with; the pools stay yours, and so does the choice of which one a request’s connection comes from:

var runtime = Graphitron.runtime(SQLDialect.POSTGRES);
var engine  = runtime.newGraphQL(Graphitron.buildSchema()).build();

Graphitron.runtime(dialect, settings) is the same with the jOOQ Settings (a schema or render mapping) that reach every context Graphitron mints over a leased connection.

runtime.newGraphQL(schema) attaches the connection-lifecycle instrumentation, so you register nothing else. To add your own instrumentation (for example OpenTelemetry) pass it to runtime.newGraphQL(schema, telemetry.newInstrumentation()): Graphitron’s stays first in the chain and yours follow in the order given, so you never write a ChainedInstrumentation. A later .instrumentation(other) on the returned builder still replaces the whole chain, after which nothing is leased; pass instrumentations to newGraphQL instead. Per request you pass the ConnectionSource the request’s connections come from (and any declared contextArguments):

var source = ConnectionSources.mounting(key -> dataSource, mount, unmount);
var input = Graphitron.newOwnedExecutionInput(source, userId).query(q).build();

For that operation Graphitron calls the source’s acquire(key) when a field first needs the connection for a key, never twice for one key, executes (each top-level mutation field, payload included, in its own transaction that commits or rolls back independently, see Transactions on the owned-connection path; queries in autocommit), and releases every lease it took, exactly once, on every completion path, including a query cancelled through ExecutionInput.cancel() or abandoned by an exception during dispatch. Once the operation has released, it takes no new connection: a request for one after that point, for example from one of your fetchers still running asynchronously after the operation was cancelled, is refused with an IllegalStateException rather than given a connection nothing would return.

The source is the consumer’s whole side of the contract. acquire returns a Lease: the connection, the session handle where <handle> names one, and the release, built with Lease.of(connection, handle, release) (or with a dialect and settings of the lease’s own). Throwing KeyNotPermitted refuses a key: the field that asked answers with an error carrying its message, and node, nodes and _entities answer null. Any other throw rejects the request (A request rejection rejects the request). A lease must be in autocommit; one that is not is refused as a failed acquisition and released. Graphitron rolls back anything the operation left open before it releases a lease, and a connection it had to stop (a fan-out worker past its deadline, a connection it could not settle) is aborted through JDBC before its release runs. The generated ConnectionSources.mounting(pool, mount, unmount) is the ready-made source: it takes a connection from the pool the key names, mounts identity on it, and at release unmounts, resets (on PostgreSQL) and returns it, evicting it when any of that fails. A failed unmount or reset fails the operation, since the identity on the connection cannot be proven cleared. A failed rollback before the unmount on a connection the driver no longer reports valid does not: the server has ended the session, and the identity and transaction with it, so the connection is evicted, the failure logged as a warning, and the response the operation computed stands.

Session identity through <sessionState>

Identity goes to the database, not to Java. The connection source sets it on each connection it leases; switching on <sessionState> (optionally naming the <handle> type the leases carry) declares that the build does so, and types the lease’s handle() for $session bindings. The source rides the request’s GraphQLContext, and the connection-lifecycle instrumentation reads it when the operation starts, so an input built without one fails before any SQL. Graphitron parses nothing about your identity; your source and the database do. See Session identity for the configuration and the contract.

This differs from a mutation hook, which is a static method resolved from the schema: identity varies per request and has to carry the request’s own claims, so it lives in a value the consumer builds per request, the source, and the build reads only the handle type, from the classpath, to check $session bindings.

The hook state contract: session-scoped, never transactional

Session identity is connection-scoped state, and your mount and unmount must treat it that way. Graphitron cannot see inside the source you author, so the contract is stated here and holds for every source:

  • Set and reset session-scoped state only. On Postgres that means set_config(key, value, false) (the third argument false means session-scoped), never SET LOCAL and never set_config(…​, true), both of which are transaction-scoped and vanish at the end of the statement that set them. Oracle RAS attach/detach and VPD context calls are session operations and already comply.

  • Do not rely on a surrounding transaction. Neither mount nor unmount may depend on any transaction committing or rolling back: no state that a commit wipes (for example a global temporary table declared ON COMMIT DELETE ROWS), no work left uncommitted for a later commit to persist.

  • Lease in autocommit. Graphitron refuses a lease whose connection has autocommit off, and settles any transaction the operation left open before it releases a lease, so the release runs outside any transaction. ConnectionSources.mounting puts the connection in autocommit before the mount, first rolling back any transaction the pool handed over open (switching autocommit on would otherwise commit it), so a pool configured with autoCommit=false works.

  • On PostgreSQL ConnectionSources.mounting backs your unmount up. It captures the connection’s session-set built-in settings (those pg_settings lists with source = 'session' and context = 'user') before the mount and, after the unmount, issues RESET ALL and restores them, so a defective unmount leaves the next borrower with no identity rather than the previous caller’s. It neither relaxes this contract nor reverts the role: reverting an init-SQL SET ROLE would hand the next borrower the table owner, whom RLS does not apply to. An unmount that leaves autocommit off is evicted rather than reset, since RESET ALL inside its transaction would be rolled back. A source of your own carries this duty itself.

A mount that violates the first two points can leave identity mounted for the pool’s next borrower or drop it mid-operation; both are security defects, not performance defects. The structure is what makes the contract cheap to hold: a lease is taken once per key with autocommit on, so what its mount set is committed session state, and a mutation field’s transaction settling later cannot revert it. Graphitron therefore never asks the source again around transaction boundaries.

The execution evidence that a connection is returned with identity cleared on every completion path is SessionIdentityPoolIsolationExecutionTest in graphitron-sakila-example: it sends requests as different users, and a borrower outside Graphitron, through one real connection pool of size one, and its class javadoc names the paths it does not yet cover.

A request rejection rejects the request

Some faults mean no field of the request can be answered, so Graphitron rejects the whole request once rather than answering each field with a redacted error. On the owned-connection path, GraphQL.execute throws the generated RequestRejectedException (in your <outputPackage>.schema package) in place of a result, and executeAsync completes exceptionally with it. It is sealed, and its arms are the build’s:

  • AcquisitionFailedException, in every build: the source threw anything but KeyNotPermitted (the database rejects the caller’s identity in your mount, say, or the pool is exhausted). What your source threw is its cause, so you can read its SQLState.

  • VoucherRejectedException, in a build that accepts vouchers: a voucher failed a check. Its reason() names the check, and its message carries nothing from the token.

A representation whose voucher vouches for a value past the cap on the request’s vouched-for set is not a request rejection: it fails alone, at its own index, as a client error naming the limit and no value, and the rest of the request is answered. Nor is a representation whose voucher is null, which an issuing subgraph gives a row it cannot sign: it carries no voucher, and its slot is null.

ExecutionResult result;
try {
    result = engine.execute(input);
} catch (RequestRejectedException rejected) {
    // Graphitron.requestRejection(rejected) is the source's own exception for a
    // failed acquisition (map an identity fault to 401, an outage to 503) and the
    // rejection itself for a voucher check (usually 401 or 403).
    return answer(Graphitron.requestRejection(rejected).orElseThrow());
}

What you can rely on:

  • One rejection per request. The first rejection is remembered for the operation, and once there is one Graphitron acquires nothing more: every later field that needs a connection, on any key, gets the same exception without asking the source again. A voucher is checked while the entity dispatch registers its representations, before any connection is taken, so a failed check takes none.

  • Nothing is logged per field. The rejection never reaches the FetcherErrorLog, mints no reference and is never claimed by an @error channel, whatever its handlers match, and a list slot does not redact it.

  • Every throw of the source is a failed acquisition. A pool fault and a rejected identity reach you the same way; tell them apart by the cause before mapping to 401, so an outage is not answered as an identity fault.

  • A request that needs no database never acquires, so it succeeds whatever the caller’s identity.

With graphitron-jakarta-rest, return the status from GraphitronApplication.rejectedRequest(Throwable), which receives what rejected the request (the adapter hands the library Graphitron::requestRejection, which recognises the generated exception so the library need not name it): usually a 401 or 403 for a voucher rejection and a 503 for an acquisition fault. It runs before clientFault(Throwable), which still answers any other escape; without an answer the handler answers the reference-only 500.

A mount that has to write (for example provisioning the caller’s row) may open its own transaction on the connection, as long as it leaves it in autocommit before the lease is returned: jOOQ’s default provider switches autocommit off for a transactionResult(…​) and restores it when the transaction ends.

If you configure no <sessionState>, the build declares no per-request identity and warns at build time (no-session-state): an unsecured direct-to-database API is a data-exposure risk. Silence that rule only if the API is intentionally unsecured or uses the escape hatch exclusively.

Transactions on the owned-connection path

Each top-level mutation field runs in one transaction. It begins the first time the field uses a connection and ends when the field’s value is complete, payload included: it commits when the field succeeded and rolls back when the field failed. A field fails when its fetcher, or anything under it, threw, whether or not an @error channel turned the exception into a typed payload, or when a GraphQL error lies under the field’s path. Fields commit independently of each other, in document order. A field that never touches the database opens no transaction. Query operations run in autocommit.

Inside the field there is one transaction and no savepoints. A transaction(…​) or transactionResult(…​) your @service opens joins the field’s transaction, and Graphitron logs a warning naming the field and your calling method, once per calling method: leaving it normally commits nothing, and leaving it by an exception marks the whole field to roll back. Catching that exception does not save the field: nothing the field wrote commits, before or after the nested scope, and the field is reported as failed with an error that says a nested transaction failed and the field’s writes were rolled back, whatever else went wrong after it; the log under the error’s reference says whether your code caught the exception. The same holds on every database. On PostgreSQL there is no carrying on after a failed SQL statement at all: the statement aborted the whole transaction, so the next one fails too. Only an exception that is not a database error leaves the transaction usable after the catch. The same rule applies to a @service on a Query field that opens a transaction of its own: what it nests inside that transaction joins it, and a caught nested failure makes the transaction’s commit fail. Work that must commit on its own belongs in its own top-level mutation field, or in a job.

A mutation field whose @service says transactionControl: SERVICE opens no transaction of Graphitron’s. It runs on the same connection, in autocommit, as a Query field’s @service does: a transaction the service opens is its own and commits as the service leaves it, and no warning is logged. The field still settles in document order, but there is nothing to commit or roll back: when it fails, what the service committed stands, and the field’s error says the service failed and nothing was rolled back. Its @outbox messages follow the field’s outcome in a transaction of their own, at most once (see the @outbox page). The connection carrier records the field as service-controlled before its fetcher acquires anything, so every acquisition under the field, payload re-reads included, hands out the connection in autocommit. Under CommitPolicy.ROLLBACK_ONLY the field’s first acquisition starts the operation’s discarded transaction instead, so a transaction the service opens is a savepoint inside it: dev commits and rolls back as production does, and still leaves nothing behind (Alf, 2026-11-18).

A field reported as successful has committed, and a field that rolled back is never shown with a value: a field that rolled back because of an error under it (a nested read in its payload that failed, say) is null, like one that failed itself; only an @error channel’s payload, which describes the failure, is kept. If the commit fails, or the database had already aborted the transaction (on PostgreSQL, any statement that failed inside it aborts it, and the driver’s commit then rolls back without an error), the field is reported as failed: its value becomes null and the response carries an error at its path, logged under the error’s reference through your FetcherErrorLog like any unmatched fetcher failure. Later fields in the operation still run.

The mutations run one field at a time. An engine configured with a mutation execution strategy other than graphql-java’s serial one (AsyncSerialExecutionStrategy or a subclass) is rejected when a mutation starts, since each field settles when the next one starts.

In a multi-tenant build each connection the field touches has its own transaction: there is no transaction across connections. Before committing anything, Graphitron checks every connection the field used, the PostgreSQL aborted-transaction check included, and a field rolls back on every connection when any of them is not clean. Only then do they commit, in the order the field first used them, so a field is left partly committed only when a commit itself fails on a later connection (a deferred constraint, a serialization failure, a lost connection), and it is then reported as failed with the earlier connections' writes kept. A tenant whose fan-out worker missed its deadline fails the field, and its transaction is discarded with its connection. A worker that acquires a connection after its field has settled is refused, so it writes nothing.

Under CommitPolicy.ROLLBACK_ONLY, the dev-execution mode, each field is one savepoint in a single operation transaction that is discarded at the end, so later fields observe earlier ones. That is the only savepoint Graphitron takes.

On the escape-hatch path Graphitron opens no scope per mutation field; each generated write runs in its own transaction on your DSLContext, which commits when the write’s statement returns. The same effect there is a consumer Instrumentation that opens a transaction on your connection when a top-level mutation field starts and settles it when the next one starts or the operation completes, with a jOOQ TransactionListener if code must run as each transaction begins.

Per-tenant routing

For database-per-tenant deployments the connection source chooses each tenant’s pool from the connection key’s tenant part; Graphitron leases one connection per distinct divined tenant within an operation. The source names the fan-out domain, its tenants(), read once per request, and refuses a key it will not serve by throwing the generated key-not-permitted refusal from acquire; the generated per-operation connection carrier remembers that refusal, so the source is asked once per key in a request. The schema-side inference that divines the tenant key is the tenant-column work; the runtime seam it rides is part of this path. The consumer-facing recipe is How-to: Tenant scoping.

The direction (Alf, 2026-11-14): a default source is supported for backwards compatibility and is not the model. Which connection a query gets is the consumer’s choice, made in code it owns and can test rather than in the schema: the consumer supplies a connection source, which receives the whole ConnectionKey and returns the connection for it. A key’s parts are each optional, the tenant among them; a key whose tenant part is empty is a key like any other, and what it means is the source’s decision, not a fallback graphitron picks. The key is a value, so graphitron knows when a child’s key differs from its parent’s and acquires again only then.

One request rejection (Alf, 2026-11-17). A failed acquisition and a failed voucher check reject the request the same way: one generated sealed request rejection, remembered once per request by the carrier and thrown in place of the result. A vouched-for value past the limit is not one: it fails only its own representation. The facade’s requestRejection(thrown) answers what rejected it (the source’s own exception for a failed acquisition, the rejection itself for a voucher check, which carries no token content), and graphitron-jakarta-rest’s rejectedRequest(Throwable) receives that value, so an adapter tells an identity fault from an outage by it.

A request’s vouched-for values share one vouched connection (Filip, 2026-11-23). A router batches every representation bound for a subgraph into one _entities call, so a list whose rows belong to different owners presents several vouched-for values at once. They are read on one connection mounted for the whole set, not on a connection per value: a value’s connection is held until the subtree below its entities is read, so a connection per value grows with the list. The key’s vouched-for part is a set of rows, one component per vouched-for field, so a voucher’s grant stays whole where it vouches for several fields, and the database’s policies test membership in the set.

The set is type-blind (Filip, 2026-11-24). A row names values, not the accepting type a voucher was presented for, so two accepting types whose vouched-for fields share a name and a type share values, and a policy on either table admits values vouched for the other. That is accepted: there is no known case of an issuing subgraph vouching for a value to a caller for one accepting type and not for the other.

The set is bounded by a runtime hook, not by the schema (Filip, 2026-11-24). How many distinct vouched-for values one request admits is asked of a limit the consumer gives the runtime (withVouchedValueLimit), a hook shaped like BatchSizeLimit and taking the _entities field’s environment, once per request. Without one the limit is 1000, sized to a list, since a voucher per entity presents one value per row. It bounds what one request costs the database and grants nothing, since every admitted value was vouched for to the same caller. Unlike BatchSizeLimit it fails closed: an answer below 1 admits no value.

No default tenant and no @defaultTenant (Alf, 2026-11-17). The request names no default tenant: which pool serves the key whose tenant part is empty is the source’s decision, so every read and write of a global table runs on that key and there is no separate global-read route. @defaultTenant goes with it, since its lookup needs a tenant value the request no longer names.

The contract that source takes (Alf, 2026-11-16). The runtime’s own connection setup and the request tenant set are gone; the source names the fan-out domain:

  • The consumer hands each request a connection source, a generated functional interface whose one method, acquire, takes the connection key and returns a lease; it is given to newOwnedExecutionInput. It is built when the request is, captures whatever the consumer needs of the request in its closure, and acquires nothing until called.

  • A lease holds the mounted connection, the session handle where <handle> names one, and its release. The jOOQ dialect and settings Graphitron uses the connection with are the runtime’s, application-wide; a lease may name its own, for a pool of another database or another configuration. Which pool, how to mount and how to clear are the source’s, inside acquire and release; Graphitron knows no mount and no unmount.

  • Graphitron owns the lifecycle. It calls acquire when a field first needs a key’s connection, once per distinct key per request, possibly for distinct keys from several threads at once, keeps the lease, uses it wherever that key applies, and releases every lease exactly once on every path. A race of its own, such as a fan-out worker past its deadline, it settles itself before releasing; the source never sees it.

  • A throwing acquire rejects the request as a whole and nothing more is acquired. A throwing release is logged, the remaining leases are still released, and the first failure surfaces.

  • Tenancy is not a mode. ConnectionKey is a record with one component per part the schema has, each possibly empty: an Optional tenant where it has a tenant column, a set of vouched-for rows where it accepts vouchers, generated in every build and with no component in one with neither. What an empty part means is the source’s decision.

  • Which tenants are valid and whether a request may reach one is the source’s to decide: it refuses a key by throwing the generated key-not-permitted refusal from acquire, which answers as a field error and as null in the entity and node dispatch, like a row that does not exist; any other throw rejects the request. Graphitron keeps no request tenant set.

  • A fan-out spans the tenants the source names, one key and one lease each. In a build with a tenant column the source declares them and is built through its factory from acquire and the tenants, so a missing domain does not compile; in a build without one the source is a plain functional interface.

  • A ready-made source, from a key-to-DataSource function and a mount and unmount, ships with the contract, so today’s behaviour stays one call away.

  • A build whose key has parts, a tenant or vouched-for values, is owned connections only; the escape hatch below does not apply to it.

The escape-hatch path: GraphitronContext

On the escape-hatch path you bring your own DSLContext per request through Graphitron.newExecutionInput(dsl, …​) and own transaction demarcation and identity yourself; Graphitron’s owned-connection guarantees do not apply. The escape-hatch engine (Graphitron.newGraphQL()) attaches no connection-lifecycle instrumentation and logs a one-time notice to that effect at wiring time. This is the right path when you already own a request-scoped DSLContext (an existing transaction manager, a framework-provided connection) and want Graphitron to use it rather than acquire its own.

A tenant-routed build is owned connections only (Alf, 2026-11-14). Routing by tenant means graphitron acquires each query’s connection from its connection key, so a caller-supplied connection has no place in such a build; the consumer’s control over which connection a key gets is the connection source, not this path.

GraphitronContext is the sealed per-request contract every generated DataFetcher reads from. It is emitted per app under <outputPackage>.schema and sealed to permit only the generator’s own GraphitronContextImpl singleton (nested inside the interface to inherit same-compilation-unit permits); apps no longer implement it directly. The extension surface moves to the points where per-request values cross the boundary:

  • Per-request DSLContext: pass it as the first parameter of Graphitron.newExecutionInput(dsl, …​). On the owned-connection path you do not supply one, the instrumentation produces it from the leased connection.

  • Per-request contextArgument values: pass each one as a typed parameter to Graphitron.newExecutionInput(…​). The factory’s parameter list reflects the schema’s declared contextArguments and their reflected Java types, so the consumer’s request-entry code threads each value through a typed slot rather than stashing arbitrary entries on GraphQLContext by hand.

  • Custom validator factory: not configurable today. The default reads Validation.buildDefaultValidatorFactory().getValidator(); the single existing override point is currently unused, so no migration is required.

// GENERATED (illustrative shape; full method set evolves with the schema)
public sealed interface GraphitronContext {
    default DSLContext getDslContext(DataFetchingEnvironment env) { ... }
    default Object getContextArgument(DataFetchingEnvironment env, String name) { ... }
    default Validator getValidator(DataFetchingEnvironment env) { ... }

    final class GraphitronContextImpl implements GraphitronContext {
        public static final GraphitronContextImpl INSTANCE = new GraphitronContextImpl();
        private GraphitronContextImpl() {}
    }
}

getContextArgument reads the value from env.getGraphQlContext() and returns it as Object; the cast to the expected Java type happens at the generated call site ((String) graphitronContext(env).getContextArgument(env, "userId")). A missing entry throws IllegalStateException naming the contextArgument and pointing at Graphitron.newExecutionInput(…​); a wrong-typed entry surfaces as ClassCastException at the generated cast. Both paths are only reachable when a consumer hand-rolls an ExecutionInput.Builder outside Graphitron.newExecutionInput(…​); the typed factory makes the same mistake a compile error at the call site. The framework’s redact path replaces the prose message with a correlation-id reference before it reaches the consumer, so the runtime throw is server-log surface only; the typed factory’s parameter list is the load-bearing diagnostic.

Where the interface comes from

The interface is emitted per app, not imported from a shared module. Every code-generation run produces one GraphitronContext.java file under <outputPackage>.schema, written by GraphitronContextInterfaceGenerator. The generated interface depends only on graphql-java’s DataFetchingEnvironment and jOOQ’s DSLContext; it does not pull in any Graphitron runtime jar. The sealed declaration plus nested impl mean the contract is global to the build (one impl per app), with all per-request state living in the GraphQLContext the factory populates.

Where each per-request value comes from

Generated fetchers retrieve the singleton through a private helper emitted once per *Fetchers class:

// GENERATED: from TypeFetcherGenerator.buildGraphitronContextHelper
private static GraphitronContext graphitronContext(DataFetchingEnvironment env) {
    return env.getGraphQlContext().get(GraphitronContext.class);
}

The singleton’s default methods then read the per-request values back from env.getGraphQlContext(): DSLContext.class for the per-request DSLContext, the contextArgument’s string name for each typed value the factory put. The full minimum viable wiring (building the schema, wiring GraphQL, calling the factory) lives in the Runtime API reference.

sequenceDiagram
    participant Client
    participant Engine as graphql-java engine
    participant Fetcher as generated DataFetcher
    participant Ctx as GraphitronContext<br/>(consumer impl)
    participant DSL as DSLContext
    participant DB as PostgreSQL

    Client->>Engine: ExecutionInput<br/>(query, populated GraphQLContext, DataLoaderRegistry)
    Engine->>Fetcher: invoke (DataFetchingEnvironment env)
    Fetcher->>Ctx: graphitronContext(env).getDslContext(env)
    Ctx-->>Fetcher: per-request DSLContext<br/>(read from env.getGraphQlContext().get(DSLContext.class))
    Fetcher->>DSL: select(...).from(...).where(...)
    DSL->>DB: SQL (driven by selection set)
    DB-->>DSL: Result&lt;Record&gt;
    DSL-->>Fetcher: rows
    Fetcher->>Ctx: getContextArgument(env, "userId")<br/>(if @condition uses contextArguments)
    Ctx-->>Fetcher: claim value (Java cast applied at call site)
    Fetcher-->>Engine: Result&lt;Record&gt; / connection class
    Engine-->>Client: response (graphql-java traverses records via field DataFetchers)

The diagram shows one fetcher invocation; per-request behaviour (tenant routing in getDslContext, session variables for RLS, JWT claims through getContextArgument) all happen on the request thread, scoped to the DataFetchingEnvironment. The generator emits the call sites; the consumer’s GraphitronContext implementation decides what each call returns.

getDslContext: database access

Every generated query method calls getDslContext(env) to obtain the DSLContext for executing SQL. The default impl reads env.getGraphQlContext().get(DSLContext.class), populated by the factory’s defaultDsl parameter. This is the only impl; the sealed interface closes off ad-hoc overrides. On the escape-hatch path you build the right per-request DSLContext at request entry and pass it to Graphitron.newExecutionInput(dsl, …​); on the owned-connection path the instrumentation produces the DSLContext from the leased connection and per-tenant routing is the connection source’s (above). The same shape composes with PostgreSQL row-level security; see Row-Level Security and the integrity gradient below.

getContextArgument: passing runtime values into generated methods

getContextArgument passes values from the GraphQL context into generated condition and method calls. It is invoked when a method parameter is classified as ParamSource.Context, driven by the contextArguments field on the @condition and @service directives.

For example, a field with @condition(condition: "AccessControl.visibleToUser", contextArguments: ["userId"]) produces:

// GENERATED
condition = condition.and(AccessControl.visibleToUser(table,
    (String) graphitronContext(env).getContextArgument(env, "userId")));

The Java cast at the generated call site is reflected from the developer method’s parameter type, so it matches the compile-time signature the consumer wrote against. The supplying side is the factory’s typed parameter slot: Graphitron.newExecutionInput(dsl, userId) with userId: String reflects straight into the consumer’s method, and a typo in the SDL contextArguments: list surfaces as a compile error at the factory call (not a null at request time).


Complementary Technologies

The sections below describe standard capabilities that compose naturally with GraphitronContext. They are not Graphitron-specific extension points: they work because getDslContext gives you full control over the DSLContext and its configuration.

Where each concern belongs. Three layers, in order of preference:

  • jOOQ Configuration for cross-cutting jOOQ behaviour: type converters, forced types, RecordMapperProvider, naming strategies. Configured once per app and shared by every DSLContext you return from getDslContext.

  • The DSLContext you pass into Graphitron.newExecutionInput for per-request decisions: which tenant’s DSLContext to use, which session variables to SET LOCAL, which connection to acquire. Anything that varies request-by-request gets composed at request entry and threaded through the factory.

  • Schema directives (@condition, @reference) for predicates and joins that are part of the schema’s business semantics. Anything a schema author should be able to read in the SDL belongs here, not in a runtime hook.

ExecuteListener is an advanced jOOQ-level hook (logging, metrics, query rewriting); use it sparingly and prefer Configuration or a directive when either fits.

Instance @service holders

Instance @service classes are constructed per call via new ClassName(DSLContext). The holder is created fresh per fetcher invocation; do not stash request-scoped state on instance fields, since each call gets its own holder. For per-tenant or per-request decisions inside the holder, ride into the holder via the DSLContext’s `Configuration: Configuration.data(key) carries ad-hoc per-request values written by your getDslContext implementation, and Configuration.settings() plus registered Converter / RecordMapperProvider carry cross-cutting jOOQ behaviour. For SDL-visible per-request arguments, prefer a static method that takes the value via getContextArgument. The single-(DSLContext) constructor contract is a deliberate constraint, mirroring the legacy generator: every per-request seam already exists on Configuration or in the SDL, so a wider holder ctor would duplicate plumbing without adding capability.

jOOQ Configuration

For most applications, jOOQ’s Configuration is the most important extension point. DefaultConfiguration controls type converters, forced types, synthetic primary keys, embedded records, naming strategies, and more. These settings flow through every query Graphitron generates.

var config = new DefaultConfiguration();
config.set(SQLDialect.POSTGRES);
config.set(dataSource);
// Type converters, forced types, RecordMapperProvider, etc. go here
config.set(new DefaultRecordMapperProvider());
DSLContext ctx = DSL.using(config);

See the jOOQ Configuration documentation for the full set of options.

jOOQ ExecuteListener

ExecuteListener is an advanced hook that intercepts query execution at lifecycle points (before rendering, before execution, after execution, etc.). Most applications do not need this: it is mainly useful for SQL logging, metrics collection, or query rewriting. Register a listener on DefaultConfiguration before creating the DSLContext; see the jOOQ ExecuteListener documentation for the full lifecycle and available hooks.


Row-Level Security and the integrity gradient

RLS-assumed is a stated principle. Graphitron cannot enforce that the database enforces row access; it assumes it, and says so. Generated code issues plain SELECT statements and carries no authorization logic; row-level security (RLS/VPD) is the recommended enforcement mechanism, filtering rows transparently from session state with no change to generated queries. Consumers who do not use RLS remain responsible for exposing only safe surfaces (views, restricted schemas). If a mounted identity is wrong or absent, the failure is a data-exposure failure, not a confusing-UI failure, so the safe posture is fail closed: an RLS policy must treat both a NULL and an empty session variable as "no identity" and deny.

The integrity gradient. How tamper-resistant the mounted identity is varies by dialect and pattern, and it is a spectrum, not a yes/no. Choosing where on it to sit is the load-bearing security decision.

The gradient is read off the routine your mount calls, not off graphitron configuration: what the routine’s own definition says is the whole story, and the callback is the one place of consumer Java between the request and the database, so it is the one more place to read.

  • Enforced fence (strongest). The mounted state lives behind a privilege fence: an Oracle package-bound context or RAS session attached by a definer-rights package, so code on the connection cannot set identity state except through the trusted package. Your mount calls the package’s executing method; the fence is the package’s own definition.

  • Convention fence. Plain PostgreSQL GUCs written by your mount (directly, or via a SECURITY DEFINER routine): any SQL on the connection can overwrite them, so the real guarantee is that Graphitron generates every statement and any @service code on the connection behaves. The build cannot see which fence a mount implements, so no warning grades it; the choice is documented here and in the security guide rather than policed at build time.

  • Cryptographic fence. Pass the raw signed token into the mount and have the routine verify the signature in-database, reading claims only from verified state, so even arbitrary SQL on the connection cannot forge another user’s identity. The fence is the routine’s verification logic; the callback merely calls it.

On the owned-connection path

Identity is mounted by your connection source, typically the mount of ConnectionSources.mounting (see above); your RLS policies read whatever it set. For a mount that writes a session GUC per request (and an unmount that clears it to the empty string, since a touched GUC cannot return to unset), a fail-closed policy reads:

-- ILLUSTRATIVE: PostgreSQL RLS policy, fail-closed on unset/empty identity
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;

CREATE POLICY caller_isolation ON documents
    USING (owner_id = NULLIF(current_setting('app.user_id', true), ''));

Generated code is unaware of RLS: it issues plain SELECT statements on the leased connection and the database enforces the policies automatically.

On the escape-hatch path

You own the connection and the identity on it, so you do by hand what the owned path’s mount and unmount do: set identity session-scoped on a connection in autocommit before the request runs, and clear it before the connection goes back to the pool. Hold one connection for the whole request, so the set, every query, and the clear share it.

// ILLUSTRATIVE: session identity on the escape-hatch DSLContext
Connection conn = dataSource.getConnection();
try {
    settle(conn);
    DSLContext ctx = DSL.using(conn, SQLDialect.POSTGRES);
    ctx.execute("select set_config('app.user_id', ?, false)", userId); // false: session-scoped
    var input = Graphitron.newExecutionInput(ctx, /* contextArguments... */).query(q).build();
    result = engine.execute(input);
} finally {
    try {
        settle(conn);
        DSL.using(conn, SQLDialect.POSTGRES).execute("select set_config('app.user_id', '', false)");
        conn.close();
    } catch (Exception clearFailed) {
        conn.abort(Runnable::run); // identity not proven cleared: evict, never hand it on
        throw clearFailed;
    }
}

// Autocommit on, with nothing left open. Roll back first: JDBC commits an open
// transaction when autocommit is switched on.
static void settle(Connection conn) throws SQLException {
    if (!conn.getAutoCommit()) {
        conn.rollback();
        conn.setAutoCommit(true);
    }
}

Why each piece is there:

  • Session scope, set in autocommit. The third argument false makes the setting last for the session; set in autocommit it is committed at once, so the commits and rollbacks your request goes on to make cannot revert it. true does not work in either place you might put it. In autocommit it reverts at the end of its own statement. Inside a transaction you open around the whole request it reverts at that transaction’s first commit, and Graphitron’s generated mutations each open and commit a transaction on the DSLContext you pass (see @mutation and @routine), so identity ends with the first mutation field.

  • The clear runs after execution, in autocommit. With engine.executeAsync(…​), run the finally block when the returned future completes, not when executeAsync returns; the connection stays borrowed until then. The settle before the clear matters: a clear issued inside a transaction your request left open is reverted when the pool rolls that transaction back on return.

  • Clear to the empty string. A custom setting PostgreSQL has seen cannot return to unset; the policy’s NULLIF treats '' as no identity.

  • Evict when the clear fails. close() hands a connection back to the pool, still carrying identity if the clear did not run; abort makes the pool discard it.

Graphitron’s own reset at release covers only connections it borrowed itself, so the clear on this path is yours. EscapeHatchSessionIdentityExecutionTest runs this shape against PostgreSQL with row-level security.

Producing the claims payload

On the owned-connection path the claims reach your mount through the closure of the connection source you build per request; no auth-framework type enters generated code. For the common single-String payload your mount takes an opaque claims string. From MicroProfile JWT (or any JWS bearer) the two forms come straight off the injected JsonWebToken, and which you pick is the integrity-gradient decision:

  • Signed compact token (cryptographic fence): pass jwt.getRawToken(). Your mount routine verifies the signature and reads claims in-database, so the identity holds even against distrusted SQL on the connection.

  • Bare claims JSON (for a mount that parses claims without verifying): the payload segment of a JWS already is the claims JSON, so decode it with the JDK alone, no JSON parser:

String claims = new String(
    Base64.getUrlDecoder().decode(jwt.getRawToken().split("\\.")[1]),
    StandardCharsets.UTF_8);
return Graphitron.newOwnedExecutionInput(sourceFor(claims));

getRawToken() returns the three-segment compact serialization, not JSON; passing it where claims JSON is expected fails inside your mount (for example at a jsonb cast), with the mount’s own error. If your platform hands you an encrypted token (JWE), the payload segment is ciphertext; rebuild the claims JSON from the platform’s claim accessors instead.


See also:

  • Runtime API reference: buildSchema, the GraphitronContext factory, custom scalars, federation, and context arguments from the consumer side

  • Code Generation Triggers: Schema patterns to sealed variants, including the @condition directive that drive getContextArgument calls

  • Security Model: Database-level security philosophy