graphql

package
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 17 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BindSQL

func BindSQL(sql string, exprs []string) (string, error)

BindSQL rewrites the named placeholders of a computed field's SQL into the alias-qualified column expressions that stand for them. The values come from the row itself, never from the request, so substitution is safe; a placeholder that is not a column of the table is an error.

func CompileSelect

func CompileSelect(sel *SelectionSet, opts CompileOptions, tables map[string]*Table) (string, error)

CompileSelect builds the statement for a root field selection. The result is one row holding one JSON array, so a nested query costs exactly one round trip.

func Introspect

func Introspect(ctx context.Context, db *sql.DB, schemas []string) (map[string]*Table, error)

Introspect reads the columns and foreign keys of every table and view in the named schemas, keyed by lowercased `schema.table`, using the SQLite dialect.

func QuoteIdent

func QuoteIdent(s string) string

QuoteIdent quotes one SQLite identifier.

func QuoteLit

func QuoteLit(s string) string

QuoteLit quotes a string as a standard SQL string literal.

func WithClaims

func WithClaims(ctx context.Context, c map[string]any) context.Context

WithClaims returns a context carrying the request's claims, which policy filters read.

Types

type Backend

type Backend interface {
	Dialect() Dialect
	Runtime() Runtime
}

Backend is one borrowed database: the dialect its SQL is written in and the runtime statements run through. A single graphql endpoint can merge several backends (sqlite + pgsql + mysql); each table remembers the backend it came from, so a query routes to the right engine and dialect.

type BatchResult

type BatchResult struct {
	Rows     []map[string]any
	HasRows  bool
	Affected int64
}

BatchResult is the outcome of one write, backend-agnostic. A backend adapts its own result type to this so the engine depends on no database driver.

type Column

type Column struct {
	Name    string
	Type    string
	NotNull bool
	PK      int
}

Column is one column of an exposed table or view.

type CompileOptions

type CompileOptions struct {
	Table   *Table
	Policy  *TablePolicy
	Role    string
	Claims  map[string]any
	Dialect Dialect
	Where   map[string]any
	Args    *[]any
}

CompileOptions carries what the compiler needs that is not part of the selection set: the table being queried, the role's policy, the dialect that renders engine-specific SQL, and the argument list to bind.

type Compiler

type Compiler struct {
	// contains filtered or unexported fields
}

Compiler turns one selection set into a single statement that returns the whole nested result as one JSON value. There is no per-row query: every relationship becomes a correlated subquery in the same statement.

type DeletePerm

type DeletePerm struct {
	Filter map[string]any
}

DeletePerm limits which rows a delete may touch.

type Dialect

type Dialect interface {
	// Name is the engine identifier: "sqlite", "postgres" or "mysql".
	Name() string

	// QuoteIdent quotes one identifier (column or table).
	QuoteIdent(s string) string

	// QuoteLit quotes a string literal.
	QuoteLit(s string) string

	// ILike is the case-insensitive LIKE operator: ILIKE on PostgreSQL, LIKE on
	// engines whose LIKE already folds case.
	ILike() string

	// Similar is the SIMILAR TO operator, or "" when the engine lacks it.
	Similar() string

	// Regex is the regex match operator for case-sensitive (ci=false) or
	// insensitive (ci=true) matching, or "" when the engine lacks it.
	Regex(ci bool) string

	// Placeholder returns the bind placeholder for the 1-based argument n.
	// SQLite and MySQL use "?"; PostgreSQL uses "$n".
	Placeholder(n int) string

	// JSONObject renders the engine's JSON object constructor from already
	// rendered "key, value" pairs.
	JSONObject(pairs []string) string

	// JSONArray wraps a rendered object expression in the engine's array
	// aggregation, so a nested selection is one correlated subquery.
	JSONArray(objExpr string) string

	// DecodeJSON normalizes a value read from the aggregated "data" column
	// into the bytes of a JSON document. SQLite and MySQL hand back a string;
	// PostgreSQL jsonb hands back []byte. ok is false for a NULL.
	DecodeJSON(v any) (raw []byte, ok bool)

	// SupportsReturning reports whether INSERT/UPDATE/DELETE ... RETURNING is
	// native (SQLite and PostgreSQL). MySQL emulates it.
	SupportsReturning() bool

	// LastInsertIDExpr is the SQL expression yielding the just-inserted row's
	// id for engines without RETURNING, or "" when unsupported. MySQL returns
	// "LAST_INSERT_ID()".
	LastInsertIDExpr() string

	// Introspect reads the tables, views, columns and foreign keys of the
	// named schemas through the borrowed pool, keyed by lowercased
	// "schema.table".
	Introspect(ctx context.Context, db *sql.DB, schemas []string) (map[string]*Table, error)
}

Dialect is the per-engine SQL surface the GraphQL engine needs. Everything above it (selection flattening, roles, policies, relationships, the SSE subscription loop) is shared; only the four things that differ between SQLite, PostgreSQL and MySQL live here. A backend plugin selects a dialect by its module id, so one engine serves all three unchanged.

var MySQL Dialect = mysqlDialect{}

MySQL serves MySQL and MariaDB. It has no RETURNING, so the insert path reads the row back with LAST_INSERT_ID().

var Postgres Dialect = pgDialect{}

Postgres serves PostgreSQL. jsonb aggregation returns []byte, placeholders are $n, and introspection reads information_schema.

var SQLite Dialect = sqliteDialect{}

SQLite is the default dialect. The package-level QuoteIdent, QuoteLit and Introspect predate the abstraction and delegate here, so existing callers and tests keep their exact behaviour.

type Engine

type Engine struct {
	Runtime  Runtime
	Dialect  Dialect
	Tables   map[string]*Table
	Policies map[string]*TablePolicy
	Exposes  []Expose
	Remotes  []RemoteSource
	// contains filtered or unexported fields
}

Engine builds one GraphQL schema per role and runs the statements behind it.

func (*Engine) Known

func (e *Engine) Known(role string) bool

Known reports whether a role is named by any expose block.

func (*Engine) Schema

func (e *Engine) Schema(role string) (graphql.Schema, error)

Schema returns the schema for a role, building it on first use.

type Expose

type Expose struct {
	Table string
	Reads []string
	// Writes is nil unless the block names `writes`: a bare expose is
	// read-only, and `writes` with no roles is writes for every role.
	Writes    []string
	HasWrites bool
}

Expose is one `expose` block: the table and the roles that may read and write it. A role in neither list sees nothing.

type Field

type Field struct {
	Name string
	SQL  string
}

Field is one computed column: SQL run against the row's own table, with every column of the row bound by name.

type ForeignKey

type ForeignKey struct {
	Column    string
	RefTable  string
	RefColumn string
}

ForeignKey is one side of a foreign key constraint: the column on this table and the column it points at on another table.

type InsertPerm

type InsertPerm struct {
	Columns []string
}

InsertPerm limits which columns an insert may set.

type Relation

type Relation struct {
	Name    string
	Table   string
	Mapping map[string]string
	Many    bool

	Through string            // junction table (schema.table)
	Via     map[string]string // this table's columns -> junction columns
	Using   map[string]string // junction columns -> remote columns
}

Relation is one declared relationship: a name, the remote table, and the column pairs that link the two. One pair is the ordinary foreign key; more than one is a composite link, joined with AND. When Through is set the link crosses a junction table: Via maps this table to the junction, Using maps the junction to the remote, and the relation is many-to-many.

type RemoteSource

type RemoteSource struct {
	Name   string
	URL    string
	Client *http.Client
	Fields []string
}

RemoteSource is a stitched remote GraphQL schema: its root query fields are merged into the local schema and resolved by forwarding to the upstream.

type Role

type Role struct {
	Select []string
	Insert *InsertPerm
	Update *UpdatePerm
	Delete *DeletePerm
}

Role is one role's permissions on one table. A nil *Role means the role has no access at all.

func (*Role) Allows

func (r *Role) Allows(col string) bool

Allows reports whether a role may select a column. A role with no policy allows everything; a policy with an empty list allows nothing.

func (*Role) CanDelete

func (r *Role) CanDelete() bool

CanDelete reports whether a role may delete.

func (*Role) CanInsert

func (r *Role) CanInsert() bool

CanInsert reports whether a role may insert.

func (*Role) CanUpdate

func (r *Role) CanUpdate() bool

CanUpdate reports whether a role may update.

type Runtime

type Runtime interface {
	Query(ctx context.Context, sqlText string, args []any) ([]map[string]any, error)
	Write(ctx context.Context, schema, sqlText string, args []any, returnsRows bool) (*BatchResult, error)
	GenFor(schema string) uint64
}

Runtime is the slice of a database the GraphQL engine needs. A backend adapts its cluster to this, so the engine never opens a connection and depends on no driver.

type SelectedField

type SelectedField struct {
	Alias  string
	Name   string
	Args   map[string]any
	Select *SelectionSet
}

SelectedField is one field in a selection set.

type SelectionSet

type SelectionSet struct {
	Fields []SelectedField
	Args   map[string]any
}

SelectionSet is one parsed selection: the fields asked for, with aliases.

type Table

type Table struct {
	Schema      string
	Name        string
	View        bool
	Columns     []Column
	ForeignKeys []ForeignKey

	// Backend is the database this table was introspected from. The engine
	// routes reads and writes for the table through it, so one schema can span
	// several backends. Nil means the engine's default backend.
	Backend Backend
	// BackendKey identifies the backend group for cross-backend checks.
	BackendKey string
}

Table is one exposed table or view. A view is read-only for every role.

func (*Table) Column

func (t *Table) Column(name string) (Column, bool)

Column looks up a column by name, case-insensitively, the way SQLite does.

func (*Table) PrimaryKey

func (t *Table) PrimaryKey() (string, bool)

PrimaryKey names the single-column primary key, if the table has one.

func (*Table) Qualified

func (t *Table) Qualified() string

Qualified is the `schema.table` spelling every statement uses.

type TablePolicy

type TablePolicy struct {
	Relations []Relation
	Fields    []Field
	Roles     map[string]*Role
	// Enums maps a column to its allowed string values, exposed as a GraphQL
	// enum. Scalars maps a column to a named custom scalar.
	Enums   map[string][]string
	Scalars map[string]string
}

TablePolicy is everything declared for one exposed table beyond its name.

func LoadPolicy

func LoadPolicy(dir, table string) (*TablePolicy, error)

LoadPolicy reads one table's policy file. A missing file is not an error: the table is full access for the roles the Caddyfile names.

type UpdatePerm

type UpdatePerm struct {
	Columns []string
	Filter  map[string]any
}

UpdatePerm limits which columns an update may set and which rows it may touch.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL