zanith

API Reference

Complete reference for all Zanith exports, types, and configuration.

Core functions

ExportDescription
createZanith(config)Create a typed database client. Returns TypedZanithClient.
defineModel(factory)Define a model with typed fields. Returns TypedModelDefinition.
defineEnum(spec)Define an enum. Returns EnumNode.
compileSchema(models, enums)Compile model definitions into a SchemaGraph.
parseSchema(input)Parse a .zanith file into SchemaAST.
generateTypes(graph)Generate TypeScript type declarations from a schema graph.
measureTypegenSize(graph)Estimate the byte size of types generateTypes would emit.
SchemaGraphThe canonical runtime schema. Construct with compileSchema or parseSchema.
SQLCompilerLower-level SQL compiler — exposed for tooling that wants raw access.
RuntimeRegistryLoader for .zanith files imported at runtime.
QueryEngineThe execution layer — adapter + compiler + plugin pipeline.
ModelAPIThe per-model interface (findMany, create, query(), etc.).

Adapters

One adapter per driver. All implement the same DatabaseAdapter interface — the rest of the engine is driver-agnostic.

ExportDriverUse when
PgAdapterpg (node-postgres)Default. Pool-aware. Battle-tested.
PostgresJsAdapterpostgres (postgres.js)Lighter, faster startup, same five-method interface.
SqliteAdapterbetter-sqlite3File-backed and :memory: modes — tests, edge contexts.

Each ships an options type: PgAdapterConfig, PostgresJsAdapterConfig, SqliteAdapterConfig.

Dialects

A dialect describes the SQL emission rules for a specific database. Adapters pick one; you only touch dialects directly when building tooling on top of the compiler.

ExportDatabaseStatus
PostgresDialect · postgresDialectPostgreSQLShipped — full feature support.
SqliteDialect · sqliteDialectSQLiteShipped — limited subset (no LATERAL, ranges, etc.).
MysqlDialect · mysqlDialectMySQL / MariaDBDialect shipped, adapter pending — see roadmap.

Capabilities per dialect are enumerated in DialectCapabilities.

ModelAPI<T>

Every model gets a ModelAPI<T> instance with these methods.T is the field type map inferred from defineModel.

MethodReturnsDescription
findMany(args?)PromiseFind multiple records
findFirst(args?)PromiseFind first matching record
findUnique(args)PromiseFind by unique field
create(args)PromiseInsert a record
update(args)PromiseUpdate a record
delete(args)PromiseDelete a record
count(args?)PromiseCount matching records
query()RelationalQueryBuilderStart a relational query
insert(data)InsertBuilderStart an insert/upsert operation

RelationalQueryBuilder

MethodDescription
.with({ rel: true })Join a relation (LEFT JOIN by default)
.with({ rel: 'inner' })INNER JOIN
.with({ rel: { nested: true } })Multi-hop join
.select(fn)Explicit field projection with aliases
.where(fn)Filter with typed field references
.orderBy(fn)Sort by field references
.limit(n)Limit results
.offset(n)Skip results
.distinctOn(fn)PostgreSQL DISTINCT ON
.withCTE(name, sql)Define a CTE
.fromCTE(name)Select from a CTE
.fromSubquery(sql, params, alias)Select from a subquery
.groupBy(fn)GROUP BY fields
.having(fn)HAVING filter
.toSQL()Compile to { sql, params } without executing
.execute()Execute and return rows
.getNullableFields()Get field names that are nullable from LEFT JOINs

InsertBuilder

MethodDescription
.onConflict({ columns, action, set? })ON CONFLICT (upsert)
.returning(cols)Specify RETURNING columns (or '*')
.execute()Execute and return first row
.executeMany()Execute and return all rows (bulk insert)
.toSQL()Compile to { sql, params }

Logical & subquery helpers

ExportUsage
and(...conditions)Combine with AND
or(...conditions)Combine with OR
not(condition)Negate
exists(subquery)EXISTS subquery
notExists(subquery)NOT EXISTS subquery
inSubquery(field, subquery)field IN (subquery)
notInSubquery(field, subquery)field NOT IN (subquery)

Set operations

Combine query results across statements. See /docs/advanced/set-operations for examples.

ExportSQL
union(a, b)SELECT … UNION SELECT … (deduplicated)
unionAll(a, b)UNION ALL (preserves duplicates)
intersect(a, b)Rows present in both
intersectAll(a, b)INTERSECT ALL
except(a, b)Rows in a not in b
exceptAll(a, b)EXCEPT ALL

LATERAL joins · LISTEN / NOTIFY

ExportPurpose
lateralJoin(builder)Correlated subquery as a join — top-N per group, etc.
listen(channel)Postgres LISTEN channel — register a subscriber.
unlisten(channel)Postgres UNLISTEN channel.
notify(channel, payload)Postgres NOTIFY channel, 'payload'.

Expression builders (CASE / COALESCE / fn)

ExportSQL
lit(value)Bind a literal value as a parameter.
fieldRef(model, field)Reference a model field outside a query callback.
caseWhen(branches, else?)CASE WHEN … THEN … ELSE … END.
coalesce(...values)COALESCE(a, b, c, …).
nullIf(a, b)NULLIF(a, b).
fn(name, ...args)Call any SQL function by name (escape hatch).

JSON helpers

ExportPostgres operator
jsonGet(field, key)field->'key' (returns json)
jsonGetText(field, key)field->>'key' (returns text)
jsonGetDeep(field, path)field#>'{a,b,c}'
jsonGetDeepText(field, path)field#>>'{a,b,c}'
jsonContains(field, value)field @> value
jsonContainedBy(field, value)field <@ value
jsonHasKey(field, key)field ? key
jsonHasAllKeys(field, keys)field ?& keys
jsonHasAnyKey(field, keys)field ?| keys

Walkthrough at /docs/advanced/jsonb.

Array & range helpers

ExportPostgres operator
arrayContains(field, value)field @> value
arrayContainedBy(field, value)field <@ value
arrayOverlaps(field, value)field && value
arrayEquals(field, value)field = value
rangeContains(field, value)field @> value (range types)
rangeContainedBy(field, value)field <@ value
rangeOverlaps(field, value)field && value
rangeAdjacent(field, value)field -|- value
textSearch(field, query)field @@ to_tsquery(query)

Aggregate functions

ExportSQL
count(field?)COUNT(*) or COUNT(field)
countDistinct(field)COUNT(DISTINCT field)
sum(field)SUM(field)
avg(field)AVG(field)
min(field)MIN(field)
max(field)MAX(field)

Window functions

ExportSQL
rowNumber()ROW_NUMBER() OVER (...)
rank()RANK() OVER (...)
denseRank()DENSE_RANK() OVER (...)
sumOver(field)SUM(field) OVER (...)
avgOver(field)AVG(field) OVER (...)
countOver(field?)COUNT(*) OVER (...)

All window functions support .partitionBy(...fields) and .orderBy(...orders).

Plugin system

Plugins observe queries and transform results. Hooks fire in registration order; an adapter wrapped by wrapAdapterWithPlugins dispatches automatically. Walkthrough at /docs/production/plugins.

ExportPurpose
PluginManagerRegisters plugins, dispatches hooks.
wrapAdapterWithPlugins(adapter, plugins)Returns an adapter that runs hooks around every query.
TypeShape
ZanithPlugin{ name, onQuery?, onResult?, onError?, init? }
PluginContextInit payload — schema graph, adapter, plugin metadata.
QueryHook · QueryHookInfoPre-execute hook + the { sql, params, model } payload.
ResultHook · ResultHookInfoPost-execute hook + the { rows, durationMs } payload.
ErrorHook · ErrorHookInfoFailure hook + the { error, sql, params } payload.

Built-in plugins

Drop-in observability. See /docs/production/observability.

ExportWhat it does
consoleLogger(opts?)Pretty-print every query to stdout. Options: ConsoleLoggerOptions.
slowQueryLogger(opts)Log queries slower than thresholdMs. Options: SlowQueryLoggerOptions.
structuredLogger(opts)JSON line per query. Options: StructuredLoggerOptions. Records: LogRecord.
openTelemetryPlugin(opts)Wrap each query in an OTel span. Options: OpenTelemetryPluginOptions. Tracer shapes: TracerLike · SpanLike.

Multi-tenancy

Three isolation strategies, all packaged as plugins. See /docs/production/multi-tenancy for trade-offs.

ExportIsolation modelOptions type
rowLevelTenancy(opts)Inject tenant_id = $1 into every query.RowLevelTenancyOptions
schemaBasedTenancy(opts)SET search_path to a per-tenant schema.SchemaBasedTenancyOptions
databaseBasedTenancy(opts)Route to a per-tenant database via DatabaseTenantRouter.DatabaseBasedTenancyOptions

Ranked search — full-text, trigram similarity, vector distance — composable in a single query. See /docs/production/search.

ExportPurpose
search(opts)Build a ranked search query from SearchOptions (text, trigram, vector blocks).
tsvectorSetupSql(opts)Emit DDL for a tsvector column + trigger that maintains it.
facets(opts)Emit faceting SQL for filter UIs.

Option types: SearchOptions, SearchTextOptions, SearchTrigramOptions, SearchVectorOptions.

Postgres extension helpers

Typed wrappers for the four extensions Zanith treats as first-class. See /docs/production/extensions.

pgvector

ExportOperator
vectorLit(values)Bind a vector literal.
l2Distance(a, b)a <-> b (L2).
innerProductDistance(a, b)a <#> b (negative inner product).
cosineDistance(a, b)a <=> b (cosine).
l1Distance(a, b)a <+> b (L1).

pg_trgm

ExportOperator / function
trigramSimilar(a, b)a % b.
trigramDistance(a, b)a <-> b.
wordSimilar(a, b)a <% b.
similarity(a, b)similarity(a, b).
wordSimilarity(a, b)word_similarity(a, b).

pgcrypto

ExportFunction
genRandomUuid()gen_random_uuid() — UUID v4.
digest(data, type)digest(data, type) — hash.
hmac(data, key, type)hmac(data, key, type).
crypt(password, salt)crypt(password, salt).
genSalt(algorithm, rounds?)gen_salt(algo, rounds).
pgpSymEncrypt(data, key)pgp_sym_encrypt(data, key).
pgpSymDecrypt(data, key)pgp_sym_decrypt(data, key).

pg_cron

ExportFunction
cronSchedule(name, schedule, command)Schedule a job.
cronScheduleInDatabase(name, schedule, command, database)Schedule on another database.
cronUnschedule(name)Unschedule by name.
cronUnscheduleById(id)Unschedule by job id.
cronListJobs()Read cron.job.
cronJobHistory(name?)Read cron.job_run_details.

Shared

ExportPurpose
emitCreateExtension(name)DDL for CREATE EXTENSION IF NOT EXISTS ….
resolveExtensionName(name)Canonical name + schema lookup.
KNOWN_EXTENSIONSRegistry of recognised extensions.
ExtensionDeclarationType for declaring an extension dependency in a schema.

Migrations · diff & apply

The runtime side of migrations — diffing schemas, planning, applying. CLI surface at /docs/reference/cli; conceptual walkthrough at /migrate.

ExportPurpose
diffSchemas(from, to)Structural diff → MigrationOp[].
reverseOps(ops)Best-effort reversal of an op list.
applyMigrations(adapter, ops, opts?)Run a plan against an adapter. Returns ApplyResult.
rollbackMigrations(adapter, ids)Reverse a previously applied plan.
listAppliedMigrations(adapter)Read the applied-migrations table.
classifyRisk(op)Risk level + reasons for a single op.
summarizePlan(ops)PlanRiskSummary for a whole plan.
emitMigration(plan) · emitMigrationOp(op)Lower a plan or single op to SQL.
emitColumn · emitCreateTable · emitCreateIndexDDL primitives.
fieldSqlType(field, dialect)Compute the SQL type for a FieldNode.

Migrations · safety & recovery

ExportPurpose
verifyOnShadow(adapter, plan, opts)Apply on a shadow database, introspect, diff. Returns ShadowVerificationReport.
listMigrationSteps(adapter, migrationId)Per-step audit table read. Returns MigrationStepRow[].
findArtifact(adapter, name) · listArtifacts(adapter)Read soft-drop / archive artifacts.
restoreSoftDropColumn · restoreSoftDropTableBring back a soft-dropped column or table.
restoreArchiveColumn · restoreArchiveTableReplay archived data back into the live schema.
purgeArtifact(adapter, name) · purgeOlderThan(adapter, ms)Permanent deletion.
readArtifactRows(adapter, name)Stream rows out of an artifact.
rowsToCsv(rows) · rowsToJsonLines(rows)Export helpers.

Types: MigrationArtifact, ArtifactType, MigrationStepRow, ShadowVerificationOptions, ShadowVerificationReport, MigrationRiskLevel, MigrationRiskReason, RiskAssessment, PlanRiskSummary, ApplyResult, ApplyOptions, MigrationOp, MigrationPlan.

Introspection

Read an existing Postgres database into a runtime SchemaGraph. The CLI emitter that prints a .zanith file from the graph is in flight — see roadmap.

ExportPurpose
introspectPostgres(adapter, opts?)Read pg_catalogIntrospectedSchema.
introspectedToGraph(introspected)Convert the result to a SchemaGraph.

Types: IntrospectedSchema, IntrospectedTable, IntrospectedColumn, IntrospectedForeignKey, IntrospectedIndex, IntrospectedPolicy, IntrospectedEnum, IntrospectedExtension.

Type system exports

TypePurpose
InferModelFieldsExtract field type map from a TypedModelDefinition
InferFieldTypesExtract type map from a record of FieldBuilders
InferFieldTypeExtract T from FieldBuilder
TypedWhereInputTyped where input constrained to model fields
FilterOpsForMap scalar type to its filter operators
TypedZanithClientFully typed client mapped from model definitions
NullifyMake all values T | null (for LEFT JOIN)

Error types

ErrorCause
ZanithErrorBase error class
ParseErrorSchema parsing failure (line, column, file)
ValidationErrorSchema validation failure (missing @id, etc.)
QueryErrorSQL execution failure (includes sql string)
ConnectionErrorDatabase connection failure
UniqueConstraintErrorUNIQUE violation (constraint name, fields)
ForeignKeyErrorFK violation (constraint, detail)
NotNullErrorNOT NULL violation (column name)
SerializationErrorSerialization/deadlock failure (retryable)
NotImplementedErrorFeature not yet implemented