Schemas
Derive Zod validation schemas from your Drizzle tables
A schema describes the shape and rules your data must satisfy: which fields exist, their types, which are required, and what counts as valid. You use it to validate untrusted input, such as a form submission or a request body, before your code trusts it.
Zod is the TypeScript-first schema library Zeno uses for that.
You describe your data once and get two things from the same definition: runtime
validation (schema.parse(input) throws on bad data) and a static TypeScript
type (z.infer<typeof schema>).
Your Drizzle table already describes that shape for the database. Redeclaring it by hand for validation means two definitions that drift apart the moment you add a column. Instead, Zeno derives the Zod schema from the table, so the database shape, runtime validation at your trust boundaries, and the inferred TypeScript types all come from one definition. When you add a column to the table, the derived schema validates it and the inferred type includes it, with no other edit.
Installation
Install the schema package wherever you define Drizzle tables:
pnpm add @zeno-lib/schema drizzle-orm@1.0.0-rc.5 zodMost projects use it with the database and forms packages:
pnpm add @zeno-lib/db @zeno-lib/schema @zeno-lib/forms drizzle-orm@1.0.0-rc.5 postgres zod
pnpm add -D drizzle-kit@1.0.0-rc.5 dotenv@zeno-lib/schema builds on Drizzle's Zod bridge and takes drizzle-orm and
zod as peer dependencies. Import Drizzle table builders from Drizzle, and
import Zod itself directly from zod when you compose product-specific schemas.
Start from a table
You derive Zod schemas from a Drizzle table, so start with the table. It is the
database source of truth and lives in your database package under
{project}-db/src/schemas/.
Tables covers how to
define one and the Zeno helpers it uses (table, primaryId, authUserId,
auditColumns, RLS policies, …). The rest of this page builds on the example
below.
import { auditColumns, authUserId, primaryId, table } from "@zeno-lib/db/schema"
import { text } from "drizzle-orm/pg-core"
export const posts = table("posts", {
id: primaryId("uuid"),
slug: text("slug").notNull(),
title: text("title").notNull(),
userId: authUserId({ notNull: true }),
body: text("body").notNull(),
...auditColumns(),
})The Zod schemas you derive from it live next to your forms in {project}-forms,
so they stay free of database clients and are safe to import from Client
Components.
Derive Zod schemas
Use defineTableSchema(table) to create the three database variants Zeno
standardizes on. Import the table from your database package:
import { defineTableSchema } from "@zeno-lib/schema"
import { posts } from "{project}-db"
export const postSchema = defineTableSchema(posts)defineTableSchema takes a table from Zeno's table, unsecureTable or
schema(...).table, which record the column rules described
below. A table from Drizzle's own pgTable is a
type error, and throws at runtime, because its rules would be ignored without a
trace. For such a table, use the Drizzle helpers.
postSchema contains:
| Schema | Use it for |
|---|---|
postSchema.select | Data read from the database. Generated and audit columns are present. Nullable columns accept null. |
postSchema.insert | Data accepted before an insert. Generated, identity and managed columns, audit columns included, are omitted; defaulted columns are optional according to Drizzle metadata. |
postSchema.update | Data accepted before an update. Updatable fields are optional; generated, identity and managed columns, audit columns included, are omitted. |
Audit columns stay out of writes
The database fills the columns auditColumns(), timestamps() and
authorship() emit, through a column default and the triggers from
@zeno-lib/db/triggers. The helpers mark their columns databaseManaged, so
insert and update leave them out under any key. If a caller sends createdBy, the schema
strips it and nothing writes it. A column you declare yourself is writable,
even one named createdAt. When a trusted path needs to set an audit column (a
data import, say), build that schema with createInsertSchema(...) instead.
Dates and timestamps are checked as text
A date or timestamp column in string mode (date({ mode: "string" }),
timestamp({ mode: "string" })) holds text that Postgres has to parse, so
insert and update check its format. A date is a calendar date
(2026-09-17). A timestamp is a calendar date and a time, ISO 8601 with a T
or a space, or the text Postgres returns (2026-09-17 07:53:56.357127+00). One
withTimezone needs its offset, which would otherwise come from the database
session; one without refuses an offset, which Postgres would drop without a
word. Both take infinity and -infinity. An array column's elements go
unchecked. select reads back whatever is stored, unchecked.
Identity ids stay out of writes
An identity column, such as the one sequentialPrimaryId() creates, is filled by
its sequence, so insert and update leave it out, generated by default ones
included. A form or action that names a row takes the id from select, where an
identity counting up from 1 (Postgres's default) accepts only positive numbers:
export const updatePostSchema = postSchema.update.extend({
id: postSchema.select.shape.id,
})A function refinement on the id under select runs on top of the positive
check; a schema passed as the refinement replaces it.
These are plain Zod schemas. You can parse payloads in a Server Action or Route
Handler before querying through createAuthClient(...) (RLS-scoped) or
createAdminClient(...) (RLS bypass):
import { createAdminClient } from "@zeno-lib/db"
import * as schema from "{project}-db"
import { postSchema } from "{project}-forms/posts/schemas"
export async function createPost(input: unknown) {
const value = postSchema.insert.parse(input)
const db = createAdminClient()
await db.insert(schema.posts).values(value)
}Infer types from a schema
Each variant is a plain Zod schema, so its TypeScript type comes from z.infer:
export type InsertPost = z.infer<typeof postSchema.insert>
export type SelectPost = z.infer<typeof postSchema.select>Drizzle also exposes raw row types on the table object itself,
posts.$inferInsert and posts.$inferSelect (covered in
Tables). Those mirror the
table exactly. Prefer the Zod-inferred types once a schema diverges from the
table. When you refine, omit, extend, or coerce a variant (as in the sections
below), the $infer types no longer describe it, but z.infer of the actual
schema does.
Refine each variant
Pass refinement maps when a column needs rules its database type can't express, such as a minimum length or a pattern. The maps take the same form as the refinements in Drizzle's first-party Zod schema helpers.
export const postSchema = defineTableSchema(posts, {
insert: {
body: (schema) => schema.min(1),
slug: (schema) => schema.regex(/^[a-z0-9-]+$/),
title: (schema) => schema.min(3).max(120),
},
update: {
body: (schema) => schema.min(1),
slug: (schema) => schema.regex(/^[a-z0-9-]+$/),
title: (schema) => schema.min(3).max(120),
},
})Refinements are per variant. A rule under insert does not affect update or
select, so repeat a rule in each variant where the same constraint belongs, or
put it on the column.
Put rules on the column
A rule that holds wherever a client writes the column belongs on the column
itself. Wrap the builder in the table definition, and defineTableSchema
applies it to insert and update:
import {
authUserId,
databaseManaged,
primaryId,
serverManaged,
table,
withRule,
} from "@zeno-lib/db/schema"
import { sql } from "drizzle-orm"
import { numeric, text } from "drizzle-orm/pg-core"
export const posts = table("posts", {
id: primaryId("uuid"),
// A share between 0 and 1, wherever a client writes it.
rating: withRule(numeric({ mode: "number" }), (schema) =>
schema.min(0).max(1)
),
// A trigger derives it from the title.
slug: databaseManaged(text("slug").notNull()),
title: text("title").notNull(),
// Set by its default and never by a client.
userId: serverManaged(authUserId({ notNull: true }).default(sql`auth.uid()`)),
})An owner column like userId above has a shorthand that adds the default and
the marker together:
userId: authUserId({ defaultToCurrentUser: true, notNull: true })withRule(builder, refinement)takes a function that receives the schema the column generates, typed from the builder (z.ZodNumberfor anumeric({ mode: "number" }),z.ZodStringfor atext()), so it needs no annotation. It runs before.nullable()and.optional(), so a nullable column stays nullable. A function you pass for the same column in the options runs on top of it; a Zod schema you pass replaces it, rule included.@zeno-lib/dbimports Zod's types for this, so installzodnext to it when you use rules.- A rule checks one value, so an array column calls
.array()beforewithRule, and writes the rule for the array.percentage().array()is a type error, and throws. serverManaged(builder)leaves the column out ofinsertandupdate, for a column server code sets: a sync's rows, or a value an action sets itself.defineServerTableSchemakeeps it. A column a trigger also writes takes this one, so that server code can still set it.databaseManaged(builder)leaves the column out of everyinsertandupdate, the server-side ones too, for a column only a trigger, a default or a database function sets. The audit columns carry it already. One column can't take both: that is a type error, and throws.percentage(),year()andemail()are columns with their rule built in (Tables).selectkeeps every column, without the rules, because it describes the stored row, which a rule the database doesn't enforce may not hold for.- The markers only work inside Zeno's
table,unsecureTableandschema(...).table. Drizzle's ownpgTabledrops them.
Describe a column once
What a column means belongs on the column as well. described(builder, description) records it, and defineTableSchema puts it on the column's schema
in insert, update and select, so the JSON Schema an AI tool or an MCP
endpoint sends carries it. The SQL column is unchanged: Drizzle Kit sees the
same column and generates no migration.
import { described, primaryId, table } from "@zeno-lib/db/schema"
import { pgEnum, text } from "drizzle-orm/pg-core"
export const postStatus = pgEnum("post_status", ["draft", "review", "published"])
export const posts = table("posts", {
id: primaryId("uuid"),
status: described(
postStatus("status").notNull(),
"Where the post is in its review"
),
summary: described(text("summary"), "A one-line teaser shown in listings"),
title: text("title").notNull(),
})A schema you derive from a variant keeps the description, because .pick,
.omit, .extend and .partial() reuse the column's schema. A tool's filter
picks what it takes, with no description of its own:
export const postFiltersSchema = postSchema.select
.pick({ status: true })
.partial().partial() wraps each field, so its JSON Schema keeps the description but
the wrapped field's .description reads undefined; read it before.
A schema built anew around the column starts without it: z.array(...),
.array() on the field (which moves the description to the items), or
z.enum(posts.status.enumValues). Read the description back with
columnDescription(table, key) and describe the new schema with it:
import { columnDescription } from "@zeno-lib/schema"
import { posts } from "{project}-db"
import { z } from "zod"
export const postSearchSchema = z.object({
statuses: z
.array(postSchema.select.shape.status)
.describe(columnDescription(posts, "status")),
})columnDescriptiononly takes the key of a described column, so removing a description fails the build where it was read, instead of a prompt silently losing it.describedcomposes withwithRule,serverManagedanddatabaseManaged, in any order, and with.array(), which describes the array column.- A schema you pass as a refinement that has a description of its own keeps
it. To word a filter differently, call
.describe()on it yourself. - Zeno doesn't derive filter schemas or
whereclauses from a table. Pick what a filter takes from a variant, as above.
Review what clients may write
A column is writable unless something marks it, so adding a column to a table
also adds it to every form and action input derived from it. writableColumns
lists, for every Zeno table among a module's exports, the columns insert and
update accept. Snapshot it once, and a newly writable column shows up as a
diff in review:
import { writableColumns } from "@zeno-lib/schema"
import { expect, test } from "vitest"
import * as schema from "./schema"
test("the columns a client may write", () => {
expect(writableColumns(schema)).toMatchSnapshot()
})Server code that writes a server-managed column
serverManaged() keeps a column from clients, but server code may still set it:
a sync job that records when a payment cleared, say, or a seed that creates a
row for another user. defineServerTableSchema(table, options?) takes the same
options and returns the same three variants, with the server-managed columns
kept in insert and update. Identity, audit and databaseManaged() columns
stay out, because the database writes them. An upsert keyed on the id extends the schema with
select.shape.id.
import { defineServerTableSchema } from "@zeno-lib/schema"
const paymentSyncSchema = defineServerTableSchema(payments).update.pick({
paidAt: true,
})Never parse a client's payload with it. Every export of a "use server" file
is a public endpoint, so a Server Action's input is a client's, and it uses
defineTableSchema.
For cases such as coercion, pass Drizzle schema factory options through
factory:
export const postSchema = defineTableSchema(posts, {
factory: {
coerce: {
date: true,
},
},
})Derive form and action schemas
Zeno does not generate form-specific schemas. Forms are product workflows. They may omit server-managed fields, add UI-only values, or require cross-field validation that the database table should not know about.
Derive those schemas yourself with Zod, in the same schemas.ts as the
table-derived postSchema:
import { z } from "zod"
export const createPostFormSchema = postSchema.insert
.omit({
id: true,
slug: true,
})
.extend({
publishNow: z.boolean().default(false),
})
.refine((value) => value.title.trim() !== value.body.trim(), {
message: "Title and body should not be identical.",
path: ["body"],
})
export type CreatePostForm = z.infer<typeof createPostFormSchema>Then pass the derived schema to @zeno-lib/forms:
"use client"
import { Form, FormProvider, useForm } from "@zeno-lib/forms/create-form"
import { createPostFormSchema } from "./schemas"
export function CreatePostForm() {
const form = useForm({
defaultValues: {
body: "",
publishNow: false,
title: "",
},
onSubmit: async ({ value }) => {
// Call a Server Action with validated form data.
console.log(value)
},
schema: createPostFormSchema,
})
const { CheckboxField, InputField, SubmitButton, TextAreaField } = form
return (
<FormProvider form={form}>
<Form>
<InputField label="Title" name="title" />
<TextAreaField label="Body" name="body" />
<CheckboxField label="Publish now" name="publishNow" />
<SubmitButton>Save</SubmitButton>
</Form>
</FormProvider>
)
}Edit a parent's rows as a list
A form that edits a parent with its child rows, such as an order and its lines,
validates each row and sends back the whole list, which
syncRows
saves. ownedRows(schema, { parent }) describes those rows once, for both:
import { defineTableSchema, ownedRows } from "@zeno-lib/schema"
import { z } from "zod"
export const orderLinesOfOrder = ownedRows(defineTableSchema(orderLines), {
parent: "orderId",
})
const orderSchema = defineTableSchema(orders)
export const updateOrderSchema = orderSchema.update.extend({
id: orderSchema.select.shape.id,
lines: z.array(orderLinesOfOrder.row).max(100),
})rowis the table'sinsertcolumns without the parent's, which the sync writes, plus theidof a stored row, absent on a new one. Extend it with a row's own form-only fields.parentnames one column or several (["orderId", "kind"]).- The table needs a sequential
id. A link table told apart by a natural key goes tosyncRowswith itskeyoption instead.
Where each file lives
Zeno splits a feature across two packages plus your app, so server-only database
code never leaks into modules a Client Component imports. {project} is your
workspace name and {table} is the entity (here, posts).
| Path | Should contain |
|---|---|
{project}-db/src/schemas/{table}.ts | The Drizzle table: the database source of truth and the input to migrations. |
{project}-db/src/schema.ts | Barrel re-exporting every table, imported by queries to reference tables and passed to defineRelations(...) for the relational query API. |
{project}-forms/src/{table}/schemas.ts | Table-derived Zod variants (defineTableSchema) and the UI/form schemas built from them. Pure, safe to import from Client Components. |
{project}-forms/src/{table}/forms.tsx | @zeno-lib/forms components for the table. |
Server Actions and Route Handlers that parse a schema and call @zeno-lib/db
live in your app at the server boundary. They import tables from {project}-db
and schemas from {project}-forms.
Direct Drizzle helpers
@zeno-lib/schema also re-exports Drizzle's first-party helpers for cases where
you do not want the { select, insert, update } bundle:
import {
createInsertSchema,
createSchemaFactory,
createSelectSchema,
createUpdateSchema,
} from "@zeno-lib/schema"Prefer defineTableSchema(...) for application tables so teams use the same
variant names across forms, actions, and tests. The Drizzle helpers also take a
plain pgTable, which defineTableSchema refuses, and they know nothing of
column rules, identity ids or audit columns.
Pitfalls
- Keep the module that exports your Zod schemas pure. It can import table
builders and
defineTableSchema, but it must not create database clients or read server-only request state, because Client Components import this module. - Do not import
createAuthClient(...)or other server-only code from a module a Client Component imports for validation. Keep database clients at the action/route boundary. - Refinements are per variant. A rule under
insertdoes not apply toupdateorselect, so repeat it in each variant where the constraint belongs, or put it on the column withwithRule. - Once you omit, extend, or coerce a schema, infer its type from the Zod schema
(
z.infer<typeof schema>), not the table's$inferInsert/$inferSelect; the$infertypes only know the raw table.