API Reference
Complete reference for all Zanith exports, types, and configuration.
Core functions
| Export | Description |
|---|---|
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. |
SchemaGraph | The canonical runtime schema. Construct with compileSchema or parseSchema. |
SQLCompiler | Lower-level SQL compiler — exposed for tooling that wants raw access. |
RuntimeRegistry | Loader for .zanith files imported at runtime. |
QueryEngine | The execution layer — adapter + compiler + plugin pipeline. |
ModelAPI | The 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.
| Export | Driver | Use when |
|---|---|---|
PgAdapter | pg (node-postgres) | Default. Pool-aware. Battle-tested. |
PostgresJsAdapter | postgres (postgres.js) | Lighter, faster startup, same five-method interface. |
SqliteAdapter | better-sqlite3 | File-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.
| Export | Database | Status |
|---|---|---|
PostgresDialect · postgresDialect | PostgreSQL | Shipped — full feature support. |
SqliteDialect · sqliteDialect | SQLite | Shipped — limited subset (no LATERAL, ranges, etc.). |
MysqlDialect · mysqlDialect | MySQL / MariaDB | Dialect 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.
| Method | Returns | Description |
|---|---|---|
findMany(args?) | Promise | Find multiple records |
findFirst(args?) | Promise | Find first matching record |
findUnique(args) | Promise | Find by unique field |
create(args) | Promise | Insert a record |
update(args) | Promise | Update a record |
delete(args) | Promise | Delete a record |
count(args?) | Promise | Count matching records |
query() | RelationalQueryBuilder | Start a relational query |
insert(data) | InsertBuilder | Start an insert/upsert operation |
RelationalQueryBuilder
| Method | Description |
|---|---|
.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
| Method | Description |
|---|---|
.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
| Export | Usage |
|---|---|
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.
| Export | SQL |
|---|---|
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
| Export | Purpose |
|---|---|
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)
| Export | SQL |
|---|---|
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
| Export | Postgres 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
| Export | Postgres 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
| Export | SQL |
|---|---|
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
| Export | SQL |
|---|---|
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.
| Export | Purpose |
|---|---|
PluginManager | Registers plugins, dispatches hooks. |
wrapAdapterWithPlugins(adapter, plugins) | Returns an adapter that runs hooks around every query. |
| Type | Shape |
|---|---|
ZanithPlugin | { name, onQuery?, onResult?, onError?, init? } |
PluginContext | Init payload — schema graph, adapter, plugin metadata. |
QueryHook · QueryHookInfo | Pre-execute hook + the { sql, params, model } payload. |
ResultHook · ResultHookInfo | Post-execute hook + the { rows, durationMs } payload. |
ErrorHook · ErrorHookInfo | Failure hook + the { error, sql, params } payload. |
Built-in plugins
Drop-in observability. See /docs/production/observability.
| Export | What 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.
| Export | Isolation model | Options 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 |
Search
Ranked search — full-text, trigram similarity, vector distance — composable in a single query. See /docs/production/search.
| Export | Purpose |
|---|---|
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
| Export | Operator |
|---|---|
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
| Export | Operator / 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
| Export | Function |
|---|---|
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
| Export | Function |
|---|---|
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
| Export | Purpose |
|---|---|
emitCreateExtension(name) | DDL for CREATE EXTENSION IF NOT EXISTS …. |
resolveExtensionName(name) | Canonical name + schema lookup. |
KNOWN_EXTENSIONS | Registry of recognised extensions. |
ExtensionDeclaration | Type 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.
| Export | Purpose |
|---|---|
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 · emitCreateIndex | DDL primitives. |
fieldSqlType(field, dialect) | Compute the SQL type for a FieldNode. |
Migrations · safety & recovery
| Export | Purpose |
|---|---|
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 · restoreSoftDropTable | Bring back a soft-dropped column or table. |
restoreArchiveColumn · restoreArchiveTable | Replay 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.
| Export | Purpose |
|---|---|
introspectPostgres(adapter, opts?) | Read pg_catalog → IntrospectedSchema. |
introspectedToGraph(introspected) | Convert the result to a SchemaGraph. |
Types: IntrospectedSchema, IntrospectedTable, IntrospectedColumn, IntrospectedForeignKey, IntrospectedIndex, IntrospectedPolicy, IntrospectedEnum, IntrospectedExtension.
Type system exports
| Type | Purpose |
|---|---|
InferModelFields | Extract field type map from a TypedModelDefinition |
InferFieldTypes | Extract type map from a record of FieldBuilders |
InferFieldType | Extract T from FieldBuilder |
TypedWhereInput | Typed where input constrained to model fields |
FilterOpsFor | Map scalar type to its filter operators |
TypedZanithClient | Fully typed client mapped from model definitions |
Nullify | Make all values T | null (for LEFT JOIN) |
Error types
| Error | Cause |
|---|---|
ZanithError | Base error class |
ParseError | Schema parsing failure (line, column, file) |
ValidationError | Schema validation failure (missing @id, etc.) |
QueryError | SQL execution failure (includes sql string) |
ConnectionError | Database connection failure |
UniqueConstraintError | UNIQUE violation (constraint name, fields) |
ForeignKeyError | FK violation (constraint, detail) |
NotNullError | NOT NULL violation (column name) |
SerializationError | Serialization/deadlock failure (retryable) |
NotImplementedError | Feature not yet implemented |