Experimental. The Go embedding and plugin API (the
pdbqpackage, the hook interfaces and the pdbcore packages they expose) is outside the 1.0 compatibility promise and may change in a minor release. See Compatibility and versioning.
pdbq v1 plugins are compile-time: a plugin is any Go type implementing one or more hook interfaces, registered in an ordered registry. Third parties embed pdbq as a library:
app := pdbq.New(cfg, pdbq.WithPlugins(myPlugin{}))
app.Serve(ctx)(Out-of-process plugins — go-plugin/wasm — are a possible future direction; these interfaces are the contract either way.)
Implement only what you need; every hook is optional:
type Plugin interface { // required base
Name() string // config key under plugins.settings
Priority() int // lower runs earlier / outermost
}
type CatalogHook interface { // mutate/filter the introspected catalog
TransformCatalog(ctx context.Context, c *introspect.Catalog) error
}
type InflectionHook interface { // control every generated name
Inflect(kind inflect.Kind, in inflect.Input, next inflect.Next) string
}
type SchemaHook interface { // add/remove/wrap fields & types
TransformSchema(ctx context.Context, s *schema.Builder) error
}
type CompileHook interface { // wrap SQL generation per root field
WrapCompile(next compile.Func) compile.Func
}
type RequestHook interface { // request lifecycle (auth, logging, tx policy)
BeforeOperation(ctx context.Context, op *exec.Operation) (context.Context, error)
AfterOperation(ctx context.Context, op *exec.Operation, res *exec.Result)
}Import paths: Plugin, CatalogHook and InflectionHook — together with
introspect.Catalog, inflect.Kind/Input/Next and the naming helpers
(inflect.UpperCamel, Singularize, …) — are defined in the shared engine
module github.com/suprbdev/pdbcore (pdbcore/plugin, pdbcore/introspect,
pdbcore/inflect); a catalog- or naming-only plugin therefore compiles
against pdbcore alone and works in pdbr too. pdbq's Kind* constants
(KindAllRowsField, …) and inflect.Default stay in pdbq
(internal/inflect), as do the GraphQL-typed SchemaHook, CompileHook and
RequestHook (internal/plugin; re-exported for embedders through the
pdbq package: pdbq.Plugin, pdbq.CatalogHook, pdbq.InflectionHook,
pdbq.SchemaHook, pdbq.CompileHook, pdbq.RequestHook).
Inside a request, the executor attaches the in-flight operation to the
context before hooks and compilation run, so a CompileHook (whose
compile.Func only receives a context) can read the verified claims, role,
and operation metadata: exec.OperationFromContext(ctx) /
exec.ClaimsFromContext(ctx).
A compile.Statement may carry a Then statement, run after it in the same
transaction with its result as $1 (a custom mutation whose payload reads
tables; see Mutations). A
CompileHook that rewrites a statement returned by next keeps Then;
the field's value is what the last statement returns.
One plugin instance builds every schema the App serves: one per
contract, and again on every watch-mode rebuild, while the
executors of earlier schemas keep serving. A plugin whose CompileHook or
RequestHook needs what its SchemaHook learned stores it in
SchemaBuilder.Ext[<plugin name>] and reads it back from the request's
schema (compile.Request.Built.Ext, exec.Operation.Built.Ext), never from
its own fields; nested_mutations does this.
Errors a hook returns reach the client with an extensions.code
(errors.md): a BeforeOperation error that is a
*gqlerror.Error carrying Extensions["code"] passes through unchanged,
any other one becomes operation_rejected with its message; a
CompileHook reports a client error with compile.UserErrorf (code
invalid_argument) or compile.UserErrorCodef(code, …), and any other
compile error is internal.
Hooks compose middleware-style: call next(...) to continue the chain (the
innermost link is pdbq's default behaviour). Ordering is deterministic —
priority, then registration order.
Plugin names are snake_case: smart_comments (priority 50),
simple_names (100), advanced_filters (150), postgis (160), contrib
(170), aggregates (180) and nested_mutations (200). Users disable a
built-in by name in plugins.disabled; any other name is a config error with
a "did you mean" hint (smart-comments → smart_comments). A plugin added
with pdbq.WithPlugins is enabled by registering it.
Each configurable built-in has a typed settings section under
plugins.settings.<name>, declared by its package as a Settings struct
(with koanf and doc tags, a DefaultSettings() and, where values are
constrained, a Validate() run by config validation) and passed to its
New. Unknown keys are config errors, and environment variables decode like
any other key:
$ PDBQ_PLUGINS_SETTINGS_ADVANCED__FILTERS_RELATIONS=false pdbq serve
$ PDBQ_PLUGINS_SETTINGS_NESTED__MUTATIONS_MAX__DEPTH=2 pdbq serve(__ keeps the underscore inside advanced_filters and max_depth.) The
aggregates plugin is the exception: it is configured by the top-level
aggregates section (PDBQ_AGGREGATES_ENABLED=true), whose enabled
gate has the same name in pdbr; see Aggregates.
| Key | Default | Effect |
|---|---|---|
simple_names.enabled |
false |
short names (users, user(id:), updateUser, author, posts) instead of PostGraphile v4's |
advanced_filters.relations |
true |
relation filters (forward, reverse some/none/every, <rel>Exists) |
advanced_filters.computed |
true |
filtering and ordering by computed columns |
advanced_filters.relation_order |
true |
relational orderBy values (REL__COLUMN_ASC) |
advanced_filters.relations_opt_in |
false |
only @filterable foreign keys get relation filters, only @sortable ones relational orderBy values |
advanced_filters.computed_opt_in |
false |
only @filterable computed columns get filter fields, only @sortable ones orderBy values |
postgis.filters |
true |
GeoJSONFilter, RasterFilter |
postgis.derived |
true |
derived and raster accessors |
postgis.ordering |
true |
distance ordering, <field>Distance, their near: references |
postgis.projection |
true |
buffer:, simplify:, transform:, precision: |
postgis.typed_geometry |
false |
typed geometry objects instead of GeoJSON |
contrib.filters |
true |
contrib filter operators and rank fields (Contrib) |
contrib.ordering |
true |
rank, similarity and distance ordering |
nested_mutations.max_depth |
3 |
nesting levels per root field (>= 1) |
nested_mutations.max_operations |
50 |
nested operations per root field (>= 1) |
smart_comments has no settings.
internal/plugins/simplenames is a pure naming plugin with zero core
changes. It is registered but inert until plugins.settings.simple_names.enabled
is set, the way @graphile-contrib/pg-simplify-inflector is an opt-in on top
of PostGraphile's verbose default. It overrides a handful of inflect.Kinds
and delegates everything else to next:
| Default (PostGraphile v4) | simple_names |
|---|---|
allUsers |
users |
userById(id:) |
user(id:) |
updateUserById, deleteUserById, upsertUserById |
updateUser, deleteUser, upsertUser (primary key only) |
userByAuthorId (FK author_id or authorId) |
author |
userByAuthor, userByOrgIdAndUserId (any other FK) |
same |
postsByAuthorId (posts has one FK to users) |
posts |
transfersByFromId (transfers has several FKs to users) |
same |
The names come from the schema's shape alone. It also implements
CatalogHook, not to change the catalog but to capture it, so it can count
a child table's foreign keys to the parent. A relation whose name is already
a field of its type (a column, another relation, a computed column) is a
schema build error naming the type, the field and the constraint; rename it
with @fieldName / @foreignFieldName on the constraint
(smart-comments.md). Other residual field-name
collisions are caught by the schema builder, which keeps the first field and
logs a warning.
internal/plugins/advancedfilters shows the "schema surface + metadata"
pattern: the plugin implements only SchemaHook, yet changes compiled SQL.
- It adds relation fields to every
<Type>Filterinput — a forward FK takes the parent's filter directly (PostFilter.userByAuthorId: UserFilter), a reverse FK takes a{some|none|every}wrapper (UserFilter.postsByAuthorId: PostToManyFilter), and each direction gets a Boolean existence variant (PostFilter.userByAuthorIdExists: Boolean,UserFilter.postsByAuthorIdExists: Boolean) compiling to a bare(NOT) EXISTS— adds one-level relational orderBy values (USER_BY_AUTHOR_ID__EMAIL_ASCon posts,POSTS_BY_AUTHOR_ID__TITLE_DESCon users; reverse relations aggregate withMIN/MAX) — and exposes eligible computed columns (single row-argument stable functions) as filter fields and orderBy enum values (postCount: BigIntFilter,POST_COUNT_DESC). - Each added field carries a binding (
InputField.Relation,InputField.Computed,EnumValue.Computed,EnumValue.Relation) thatBuilder.Build()copies intoschema.Built. The core compiler consults those tables when it meets a filter key with no column mapping — relations becomeEXISTSsubqueries, computed columns become function calls over the current row — and stays inert when they are empty, so disabling the plugin removes the feature end to end. NoCompileHookneeded. - Forward relation names come from
Builder.ForwardRelationName, which inflectsKindRelationForward, orKindRelationForwardManyfor a temporal (PERIOD) foreign key; such a key may reference several rows (ForeignKey.ReferencesOne()is false), so it gets the reverse-relation shapes (see Temporal keys).
The halves toggle independently:
plugins.settings.advanced_filters.relations and ...computed (both default
true), plus ...relation_order (default true, also off when relations is
off) for the relational orderBy values. Computed filters are not
index-backed, so they sidestep the filters.indexed_only policy by nature —
leave computed: false if that matters for your workload. Relational order
columns do respect filters.indexed_only, exactly like the related table's
own orderBy enum.
The built-in postgis plugin (priority 160) follows exactly this shape for
PostGIS columns: it adds GeoJSONFilter fields, derived accessors,
projection arguments and distance-ordering enum values plus their bindings
(and the raster accessors, pixel value, statistics and RasterFilter),
and the core compiler reads the bindings without a CompileHook. See
PostGIS. The contrib plugin (priority 170) does the same for
full-text, pg_trgm, unaccent, hstore, ltree, range, inet, pgvector, cube
and earthdistance columns (vocabulary operators, <field>Rank and
<field>Headline fields, rank, similarity, vector, cube and earth distance
ordering); see
Contrib types. Fields whose values are expensive to compute
declare it on their binding: FieldMeta.RowCost is charged each time the
field is evaluated (headlines, raster pixel values and summary statistics) and FieldMeta.ArgCost per argument given a
non-null value (the spatial buffer:), both in the cost estimate. The aggregates plugin (priority 180, opt-in)
adds @graphile/pg-aggregates-style connection, grouped, relational-order and
relational-filter aggregates the same way: FieldMeta.Aggregate,
InputField.Aggregate, EnumValue.GroupBy and OrderRelation.Aggregate
bindings carry SQL templates the core compiler renders inside the statement,
and FieldMeta.ScanCost feeds the cost estimate; see
Aggregates.
internal/plugins/smartcomments combines three hooks to turn PostgreSQL
COMMENT tags (@omit, @name, @primaryKey, …) into schema customization
(full tag reference: docs/smart-comments.md):
- CatalogHook — parses and indexes every comment's tags, then edits the
catalog: fully-omitted tables/functions/constraints are removed, mutation
omits clear privilege flags,
@primaryKey/@unique/@foreignKeyadd logical constraints,@notNullfixes view nullability,@filterableadds a synthetic index (the builder's indexed-only allow set). It then drops what an omitted object would leave reachable: keys over a column hidden from read, and functions over an omitted table's rows. - InflectionHook —
@namereplaces the pg identifier at the head of the naming chain and delegates tonext, so downstream naming plugins (simple_names) and the default inflector derive everything from the new name;@fieldName/@foreignFieldNameshort-circuit with exact names. This is why the plugin runs at priority 50 (beforesimple_namesat 100). - SchemaHook — removes what has no catalog representation (per-action
table/column omits, orderBy and distinctOn values), marks fields
@deprecated, and strips tag lines from GraphQL descriptions. It runs beforeadvanced_filters(150), so a dropped<Type>Filteris never referenced by relation filters.
advanced_filters reads the same tags straight from the catalog (@omit filter on a FK, opt-in via relations_opt_in/computed_opt_in settings), so
per-object filter tuning works even with smart_comments disabled. Every
plugin decides through internal/omit, the one place that maps tags to the
surfaces they hide.
internal/plugins/nestedmutations exercises the schema and compile hook
surfaces. Its input shapes follow
postgraphile-plugin-nested-mutations.
Every row input (PostInput, the create values) and patch (PostPatch) gets one
field per foreign key, in both directions, named like the relation field of
the row type (userByAuthorId, postsByAuthorId; @fieldName/@foreignFieldName
rename both). Its type lists the operations on the related rows:
| Operation | Forward (post.userByAuthorId, the FK is on this row) |
Backward (user.postsByAuthorId, the FK points here) |
|---|---|---|
connectBy<Key>, connectByNodeId |
look the row up and point this row's FK at it | point the row's FK at this row |
create |
insert the row and point this row's FK at it | insert rows referencing this row |
updateBy<Key>, updateByNodeId (patches only) |
patch the row this row references | patch rows that reference this row |
deleteBy<Key>, deleteByNodeId (patches only) |
delete the row this row references | delete rows that reference this row |
disconnectBy<Key>, disconnectByNodeId (patches only) |
clear this row's FK if it references the row | clear the FK of rows that reference this row |
<Key> is each primary key and unique constraint of the related table
(connectById, connectByEmail, connectByRoomIdAndValidAt); the
ByNodeId variants exist when its type implements Node. A forward
operation takes one input, a backward one a list (a single object is
coerced to a one-element list):
mutation {
updateUserById(input: {id: 1, userPatch: {
fullName: "Ada"
postsByAuthorId: {
connectById: [{id: 7}]
create: [{title: "New"}]
updateById: [{id: 3, postPatch: {title: "Renamed"}}]
deleteByNodeId: [{nodeId: "WyJQb3N0IiwgNF0="}]
}
}}) { user { postsByAuthorId { totalCount nodes { title } } } }
createPost(input: {post: {title: "Hi", userByAuthorId: {connectByEmail: {email: "ada@example.com"}}}}) {
post { userByAuthorId { fullName } }
}
}- Create inputs take
<Type><Relation>NestedInput(PostUserByAuthorIdNestedInput,UserPostsByAuthorIdNestedInput), which only offersconnect…andcreate: a row being created references nothing yet and nothing references it. Patches take<Type><Relation>NestedPatchInputwith every operation. - Key inputs are
<Type><Verb>By<Key>Input(UserConnectByEmailInput { email },UserDeleteByIdInput { id }) and<Type><Verb>ByNodeIdInput { nodeId }; update inputs add the patch as<type>Patch(UserUpdateByIdInput { id, userPatch: UserPatch! }), the same<type>Patchfield the root update mutations take, which may carry nested fields itself. - An operation is only offered when the role may run it and the input may
write the columns it sets:
createneeds the related create input,updateits patch,deletetheDELETEprivilege; operations that set an FK (connect…,create,disconnect…) need its columns in the input that would otherwise set them (an FK column hidden by@omit createor@omit updategets no such operation on that input) and the referenced columns readable (an FK referencing a column tagged@omit readgets none, since they would copy the hidden value into the readable FK column), anddisconnect…needs all of them nullable (aNOT NULLFK has no disconnect fields).@omit manyon the FK or the referencing table removes the one-to-many nested field. - A forward field takes at most one of
create,connect…anddisconnect…(they set this row's FK), plus anyupdate…anddelete…, which only reach the row this row references before the mutation. Forward delete leaves the FK alone, so the database'sON DELETEaction applies; pair it withdisconnect…to clear a nullable FK in the same mutation. Backward fields take any combination;update…,delete…anddisconnect…only reach rows that reference this row. - A patch may not change a column that a backward nested field of the same row matches its children on (the referenced key); that is a client error.
connect…,update…anddelete…must match a row, and so must the key of an update mutation using nested fields: a key that matches nothing (missing, or filtered out by RLS) fails the whole mutation withnested_mutations: <path> matched 0 rows(codenot_found, e.g.postsByAuthorId.updateById[0]orupdateUserById).disconnect…of a row that is not linked does nothing.- At most
plugins.settings.nested_mutations.max_operationsoperations (default 50, each list item counting once) run per root field, nested at mostmax_depthlevels (default 3). - The bulk mutations (
createManyUsers,updateManyUsers) and upserts take no nested fields; using one is an error. - A row may be modified only once per statement (a PostgreSQL rule for
data-modifying CTEs): two operations updating the same row leave only one
change, and an operation then reports
matched 0 rows. - Referential actions are not reflected in the payload.
ON DELETE CASCADE/SET NULL/SET DEFAULTandON UPDATE CASCADErun as triggers after the statement's last query, so rows they change or delete still show in the payload as they were before them (a forwarddeleteBy…whose FK cascades to this row returns the row although it is gone). The database state is correct; query it again to see the result.
Differences from the PostGraphile plugin: the relation fields keep pdbq's
relation names instead of <table>To<Columns>/<tables>Using<Columns>,
forward update…/delete… act on the referenced row instead of relinking,
create inputs offer no update/delete/disconnect, and there is no
deleteOthers. The root mutations take PostGraphile v4's shapes
(createPost(input: {post: {…}}), updatePostById(input: {id, postPatch})),
as without the plugin.
-
SchemaHook — walks foreign keys and adds the nested fields above to create inputs and patches, relaxing FK columns a nested operation can supply to optional in create inputs (the database still enforces
NOT NULL). -
CompileHook — when a create or update mutation actually uses a nested field, it replaces the DML with one multi-CTE statement: forward operations (lookups, inserts,
UPDATE … RETURNING,DELETE … RETURNING) first, then the main row'sINSERTorUPDATE … FROM <parent CTEs>, then the backward operations joined to the main row's CTE. A patch that sets no column locks the row withSELECT … FOR UPDATEinstead, which still requires theUPDATEprivilege and passes the table'sUPDATEpolicies. Each operation that must match a row adds a guard,(SELECT CASE WHEN count(*) > 0 THEN true ELSE concat('nested_mutations: …', count(*), ' rows')::boolean END FROM <cte>).compile.MutationStatementevaluates the guards in aMATERIALIZEDCTE scanned as the outer side of aLEFT JOIN LATERALwith the payload, so they run even when the payload is empty, and a failing guard raises inside the statement: it is atomic even without a transaction. Values go throughcompile.ParamSet.Value/KeyValue(enum labels, contrib and PostGIS constructors) and key comparisons throughcompile.EqualOperator(citext).The payload is compiled with
compile.MutationPayload. Rows written by CTEs are invisible to same-statement table scans, so it passes row-source overrides mapping every table the chain wrote to a visibility CTE:__vis_n AS NOT MATERIALIZED (SELECT <cols> FROM <table> WHERE <not replaced or deleted> UNION ALL SELECT <cols> FROM <insert and update CTEs> …). Replaced and deleted rows are excluded by aNOT NULLkey the operation leaves alone, matched against its returned rows (or by the operation's key lookup when it patches every such key). Every payload relation, connection,totalCount, relation filter and relationalorderByover that table reads the CTE, so the payload sees the table as it stands after the statement. The table half stays subject to the role's RLS policies, and the returned rows already passed them (anINSERT/UPDATE … RETURNINGwhose new row fails aSELECTpolicy is an error, rolling back the whole statement). Every operation runs as the request's role, soUPDATE/DELETEpolicies narrow what it can match.RETURNINGandSELECTneed theSELECTprivilege per column, so nothing selects*: once the payload is compiled, itsMutationPayload.Aliasesandcompile.ReferencedColumnsgive the columns it reads through each override and__mut. Visibility CTEs project only those (and are left out for tables the payload does not read), and each CTE'sRETURNINGlist is resolved to the columns the payload, the visibility CTEs and the other CTEs (FK copies, child matching, exclusion keys) read from it.