NAME

DBIO::GraphQL - Auto-generate a GraphQL schema from a DBIO schema

VERSION

version 0.900007

SYNOPSIS

use DBIO::GraphQL;

my $db     = My::Schema->connect(...);
my $result = DBIO::GraphQL->to_graphql($db,
  except    => [qw(AuditLog)],                    # leave a source out
  hide      => { User => [qw(password_hash)] },   # no field, filter, order, argument
  readonly  => { User => [qw(is_admin tenant_id)] }, # readable, never written
  mutations => [qw(Book)],                        # mutations are opt-in
  authorize => sub {
    my ($op, $moniker, $args, $context, $relationship) = @_;
    return { tenant_id => $context->{tenant} };   # restrict to one tenant
  },
  introspection => 0,
  default_rows  => 100,                           # rows without page/cursor
  max_rows      => 1000,                          # ceiling for take, first, skip
  max_in        => 500,                           # ceiling for an in-list
  max_depth     => 10,                            # selection depth after unfolding
  max_cost      => 10000,                         # fields x rows a query may cost
);

# Simple plural query
$result->{execute}->(
  '{ allBooks { total nodes { title } } }',
  undef, $result->{context});

# Filtered + paginated + ordered (nested-DBIO-style filter)
$result->{execute}->('
  query {
    allBooks(
      filter:  { title: { like: "%Perl%" } }
      orderBy: { field: "title", direction: ASC }
      page:    { skip: 0, take: 5 }
    ) {
      total
      hasNextPage
      nodes { id title }
    }
  }', undef, $result->{context});

# Cursor pagination
$result->{execute}->('
  query($after: String) {
    allBooks(cursor: { after: $after, first: 5 }) {
      total
      nextCursor
      hasNextPage
      nodes { id title }
    }
  }', undef, $result->{context}, { after => $cursor });

# Mutation
$result->{execute}->(
  'mutation { createBook(title: "Dune", author_id: 4) { id title } }',
  undef, $result->{context});

DESCRIPTION

Trust model. Without an authorization layer of its own in front of it, the generated API is full access to what to_graphql releases: every source and column it is given is readable and filterable by any client that can send a query, and a mutation writes what the client sends. What leaves the boundary is chosen by the caller of to_graphql through its options (see "to_graphql"): the sources, the hidden and the readonly columns, the sources that get mutations, the authorize hook that runs before every resolver that touches the database, and introspection. Anything not chosen there is exposed.

Introspects every source registered with the supplied DBIO::Schema and builds a complete, executable GraphQL::Schema with:

  • One scalar field per column, typed as Int, Float, Boolean, or String based on the column's declared data_type.

  • One relationship field per DBIO relationship (has_many resolves to a List type; belongs_to / might_have resolve to a single object type). Build-time errors are emitted when the DBIO relationship contract is incomplete (see DBIO::GraphQL::Relationship).

  • A root Query type with singular lookup and plural all<Source>s queries supporting filtering, ordering, and both offset and cursor pagination. Filter arguments use a nested per-column shape that mirrors the DBIO search-condition format (see DBIO::GraphQL::Filter).

  • A root Mutation type with createX, updateX, and deleteX entry points for every source that opted in with the mutations option (see DBIO::GraphQL::Mutation); without that option the schema has no Mutation type. A source without a primary key gets only createX and its plural query: no singular query, no updateX, no deleteX.

Composite primary keys are fully supported throughout.

METHODS

to_graphql

my $result = DBIO::GraphQL->to_graphql($db, %options);

Class method. Accepts a connected DBIO::Schema instance and the options below. Returns a hashref:

{
  execute       => sub { ... },       # the entry point, see below
  schema        => $graphql_schema,   # GraphQL::Schema
  context       => $db,               # the original schema: pass it as context
  introspection => 1,                 # the introspection option, see check_document
}

Run queries through execute. It takes the arguments of GraphQL::Execution::execute without the schema:

my $response = $result->{execute}->($query, $root, $context, \%variables, $operation);

execute checks the document before the engine runs it, and an error comes before the first SQL: fragment cycles are refused, the selection depth after unfolding fragments must not exceed max_depth, the cost must not exceed max_cost, and a document that selects __schema or __type is refused when introspection is off. A refused document answers { errors => [ { message => ... } ] }. The depth, the cost and the upper bounds of the result sets (default_rows, max_rows, max_in) together bound the work of one request, and that holds for execute. Executing schema directly with GraphQL::Execution skips the document check: the relationship resolvers still bound the depth at run time, but fragment cycles, the cost and introspection are not checked there.

An unknown option, a source or column the options name that does not exist, and sources together with except die.

sources / except
sources => [qw(Author Book)]
except  => [qw(AuditLog)]

sources lists the sources to expose, except the ones to leave out; both together die. A source that is left out disappears entirely: no type, no queries, no mutations, and no relationship field of another source that points at it.

hide
hide => { User => [qw(password_hash)] }

Takes the columns out of the schema, the filters, the ordering and the mutations. A column declared is_serializable => 0 is hidden without being named. A hidden primary-key column is no field, filter or ordering either, but stays usable as the identity of the singular query, updateX and deleteX.

readonly
readonly => { User => [qw(is_admin tenant_id)] }

The columns stay readable but are no argument of createX or updateX, and a unique-constraint column that is readonly does not identify a row either. Primary-key columns stay the identity of the singular query, updateX and deleteX; readonly on one forbids only setting it on createX.

mutations
mutations => 1
mutations => [qw(Book)]

Mutations are opt-in: 1 for every exposed source, a list for those sources only. Without the option the schema has no Mutation type.

authorize
authorize => sub {
  my ($op, $moniker, $args, $context, $relationship) = @_;
  ...
}

Runs before every resolver that touches the database: root queries, mutations, relationship fields and the count of a plural query. $op is get, list, create, update, delete or relationship; for relationship $moniker is the target source and $relationship the name of the relation. $context is the context given to execute. The answer decides:

  • false: the field fails with not authorized, before any SQL.

  • true: allowed.

  • a hashref: allowed with a restriction. For get, list and relationship it is ANDed into the search, also for the total; the lookup of the related rows happens only within it. For updateX and deleteX it stands in the writing statement itself, so a row outside it is not touched: updateX reports "not found", deleteX returns false. For createX its equality values are set as column values, and a different value from the client dies; a restriction value that is not plain (an operator hash) cannot be applied to a create and dies.

on_error
on_error => sub {
  my ($exception, $correlation_id) = @_;
  ...
}

Every resolver runs inside an error envelope. An error that DBIO::GraphQL words for the client itself (validation, bounds, not authorized) reaches the client as it is. A refusal by the database (DBIO::Exception::Server) is classified by its SQLSTATE and answered with a fixed message and a code in extensions.code: UNIQUE_VIOLATION (23505), FOREIGN_KEY_VIOLATION (23503), NOT_NULL_VIOLATION (23502) or CHECK_VIOLATION (23514). Every other failure is INTERNAL_ERROR with the message internal error and a extensions.correlation_id. The statement, bind values, constraint names, file paths and stack traces never reach the client.

The hook receives the original exception and the correlation id of every INTERNAL_ERROR; it is the one place the original text goes (to a log, for instance). Without the hook the correlation id and the original text are written with warn. The option is a code reference.

introspection
introspection => 0

Switches __schema and __type off (default on). The engine resolves them itself and offers no switch, so the option is enforced on the document by the execute code reference of the result (see "check_document").

default_rows / max_rows / max_in
default_rows => 100
max_rows     => 1000
max_in       => 500

Every result set has an upper bound. Each option is a positive integer, and default_rows must not exceed max_rows: to_graphql dies naming both values otherwise.

default_rows (default 100) is the number of rows a plural query returns without page or cursor, and the most a has_many relationship field returns; hasNextPage of a plural query says whether rows remain beyond it. max_rows (default 1000) bounds take, first and skip; a larger value is an error before any SQL, the rows are not cut silently. max_in (default 500) bounds the number of values of an in filter, also inside AND / OR; a longer list is an error before any SQL.

max_depth / max_cost
max_depth => 10
max_cost  => 10000

Each option is a positive integer; both are enforced by execute before any SQL.

max_depth (default 10) is the depth of the selection after fragments are unfolded: a root field is at depth 1, its sub-fields at depth 2, and so on (nodes of a plural query counts as a level). A deeper selection is an error. The relationship resolvers check the same depth at run time against the path of the field being resolved.

max_cost (default 10000) bounds the cost of the operation: every field costs 1, each alias on its own, and a fragment costs what its fields cost at every spread. A field that yields rows multiplies the cost of what is below it by the number of rows it yields: a plural query (allXs, with its connection object) by its page size (page.take, cursor.first, variables and their defaults resolved, otherwise default_rows), a has_many relationship field by default_rows. So { allBooks { total nodes { id } } } costs 1 + 100 * 3 = 301 at the defaults; a full max_rows page with a few fields and a has_many level of default_rows times default_rows rows fit into the default budget. Fragment cycles are always an error.

check_document

DBIO::GraphQL->check_document($result, $query);

Dies when the result was built with introspection => 0 and the query document selects __schema or __type, anywhere in it (fragments and aliases included). A document that does not parse passes, the engine reports that error itself. The engine resolves the two meta fields on its own and offers no switch, so the check runs on the document before the engine does: the execute code reference of the result runs it. Executing schema directly does not enforce introspection.

SCALAR TYPE MAPPING

SQL column types are mapped to GraphQL scalars in the following priority order:

Boolean: bool, boolean, tinyint(1)
Float  : float, double, double precision, real
Int    : int, integer, smallint, tinyint, mediumint, serial
String : everything else, among them bigint, bigserial, decimal,
         numeric and money (safe fallback)

Int is GraphQL's 32-bit signed integer, Float a double: a column whose values do not fit either travels as String, in arguments, filters and output, and reaches the database as the exact text.

The mapping is centralised in DBIO::GraphQL::ScalarMap and reused by the filter, mutation, and relationship modules.

PLURAL QUERIES

Every source X gets an allXs query returning an XConnection:

type XConnection {
  nodes:       [X]
  total:       Int        # total rows matching filter, before pagination;
                          # the COUNT runs only when total is selected
  nextCursor:  String     # opaque cursor; set only during cursor pagination
  hasNextPage: Boolean    # true when rows remain after this page (page or cursor)
}

Filtering

Filter arguments use a nested per-column shape that mirrors the DBIO search-condition format. Each column accepts a typed *Filter input with operators that depend on the column's scalar type (IntFilter, FloatFilter, StringFilter, BoolFilter).

allBooks(filter: {
  title:     { like:    "%Perl%" }
  author_id: { gt:      3 }
  active:    { eq:      true }
  AND: [
    { title: { contains: "Hobbit" } }
    { OR:    [ { title: { contains: "Ring" } }, { author_id: { gt: 5 } } ] }
  ]
}) { total nodes { title } }

Per-scalar operators:

IntFilter / FloatFilter
  eq, not, gt, gte, lt, lte, in, isNull

StringFilter
  eq, not, like, contains, startsWith, endsWith, in, isNull

BoolFilter
  eq, not, isNull

Logical combinators (available on every per-source filter):

AND: [ Filter, Filter, ... ]
OR:  [ Filter, Filter, ... ]

Ordering

allBooks(orderBy: { field: "title", direction: ASC }) {
  total nodes { title }
}

direction is the OrderDirection enum: ASC or DESC. When omitted, results are ordered by primary key ascending.

Offset pagination

allBooks(page: { skip: 10, take: 5 }) { total nodes { title } }

skip defaults to 0, take defaults to 10. A take below 1 or a skip below 0 is an error, and so is a take or skip above max_rows. Without page and cursor a plural query returns the first default_rows rows.

Cursor pagination

# First page
allBooks(cursor: { first: 5 }) {
  total nextCursor hasNextPage nodes { title }
}

# Subsequent pages - pass nextCursor from the previous response
allBooks(cursor: { after: "...", first: 5 }) {
  total nextCursor hasNextPage nodes { title }
}

first defaults to 10 and may not exceed max_rows. Cursor pagination takes precedence over offset pagination if both are supplied in the same query. Cursors are opaque base64-encoded strings derived from the row's primary key and should be treated as implementation details subject to change.

Cursor pagination always runs in ascending order of the complete primary key. A composite key is compared as a whole, so following nextCursor until hasNextPage is false delivers every matching row exactly once.

Because a cursor is a position in that order, an orderBy is accepted next to cursor only when it asks for the same order: field is the first primary-key column and direction is ASC or omitted. The rows still come in the order of the complete primary key. Any other orderBy - DESC, a column outside the primary key, a later primary-key column - is an error; use offset pagination (page) for those. A cursor that does not carry one value per primary-key column, such as one obtained from a different source, is an error as well, and so is a string that is not a cursor as nextCursor issues it (it must be canonical base64). first below 1 is an error. A source without a primary key cannot be paginated by cursor; use page there. An empty after string is a cursor like any other (the cursor of the key ''), not "no cursor".

MUTATIONS

For every source X that opted in with the mutations option, three mutations are generated by DBIO::GraphQL::Mutation:

createX

mutation { createBook(title: "Dune", author_id: 4) { id title } }

Accepts the column values as arguments, except hidden and readonly columns. Columns that are non-nullable, have no declared default, and are not auto-increment are wrapped in NonNull and must be supplied. On failure, dies - the error appears in the top-level errors array of the response.

updateX

mutation { updateBook(id: 1, title: "Dune Messiah") { id title } }

Identifies the target row by its primary key or by the complete set of columns of one unique constraint declared on the source. The key rule:

  • A complete primary key alone decides. Unique-constraint columns passed alongside are values to write, never a second way to find a row, and an unknown primary key is "not found" - there is no fallback to a unique constraint.

  • Without a complete primary key, exactly one complete unique constraint identifies the row. Two complete constraints supplied together, or a partial primary key beside a constraint, are rejected with an error instead of guessing which one is meant.

  • A partial primary key without a complete constraint names no row: "not found".

Consequence: the value of a unique column can only be changed through the primary key, because supplying it beside another complete constraint is rejected and supplying it beside the primary key makes it data.

All non-key columns are optional: only the columns you pass with a non-null value are written, omitted columns keep their current value (sparse update). dies if the row cannot be found or the update fails. A column cannot be set to NULL through updateX, because a null or omitted argument is ignored.

Sources without a primary key get no updateX.

deleteX

mutation { deleteBook(id: 1) }

Identifies the target row by primary key or unique constraint under the key rule of "updateX": a complete primary key alone decides and an unknown one deletes nothing; without it exactly one complete unique constraint decides; several complete constraints, or a partial primary key beside one, are an error. Sources without a primary key get no deleteX. Returns true (Boolean) on success, false if the row is not found. A DELETE the database rejects (for example a foreign-key violation) dies, see "ERROR HANDLING".

ERROR HANDLING

  • A document execute refuses (fragment cycle, max_depth, max_cost, introspection switched off) answers with an errors list and no data, before any SQL.

  • createX, updateX and deleteX resolver failures die. GraphQL catches the exception and surfaces it in the top-level errors array, after the error envelope of the on_error option has classified it; the data field for the failed mutation will be null.

  • deleteX returns false when no row matches the supplied key(s); a failing DELETE dies.

  • Relationship resolution dies at build time when the DBIO relationship contract is incomplete (see DBIO::GraphQL::Relationship). to_graphql always builds its relationship resolver in the default die mode. Only a DBIO::GraphQL::Relationship constructed directly with on_error => 'warn' downgrades the failure to a warning and skips the field; to_graphql offers no way to pass that option.

LIMITATIONS

  • Relationship fields are unfiltered. Relationship fields within a query (e.g. author { books { title } }) return all related rows, a has_many field at most default_rows of them. They do not accept filter, orderBy, or pagination arguments.

  • No nested input for mutations. createX and updateX accept only scalar column values. Related rows must be created or linked separately using their own mutations and raw foreign-key values.

  • updateX cannot set a column to NULL. Non-key columns are optional and only non-null arguments are written, so a column can be changed but not cleared.

  • Cursor pagination runs in primary-key order only. The after cursor encodes the primary key of the last returned row and continues with the rows whose key is greater. Combining cursor with an orderBy that is not the ascending primary-key order is rejected with an error rather than served in an order the cursor cannot follow. Use offset pagination (page) for descending order and for ordering by other columns (see "Cursor pagination").

  • No custom scalars. Column types such as date, datetime, json, and uuid all map to String. Custom GraphQL scalars are not generated.

  • No subscriptions. Only Query and Mutation operation types are generated.

  • String filter case sensitivity is database-dependent. The like, contains, startsWith and endsWith operators all run an SQL LIKE. SQLite LIKE is case-insensitive for ASCII characters but case-sensitive for Unicode. PostgreSQL LIKE is always case-sensitive.

ARCHITECTURE

DBIO::GraphQL is a thin orchestrator over focused modules:

ACKNOWLEDGEMENTS

DBIO port of DBIx::Class::Schema::GraphQL by Mohammad Sajid Anwar (MANWAR). The original DBIx::Class implementation, design, and documentation are his work; this distribution adapts them to the DBIO schema introspection API and re-architects the filter surface into a nested per-column shape that mirrors DBIO's native search-condition format.

SEE ALSO

DBIx::Class::Schema::GraphQL, GraphQL::Plugin::Convert::DBIC, DBIO::Schema, GraphQL::Schema

AUTHOR

DBIO Authors

COPYRIGHT AND LICENSE

Copyright (C) 2026 DBIO Authors

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.