Zod Schemas
turbine generate --zod writes a zod.ts file with a Zod schema per table. Use it to validate request bodies and other untrusted input before a write.
npm install zod
npx turbine generate --zodThe file sits next to types.ts, metadata.ts and index.ts. It imports zod; the Turbine runtime does not, so install Zod yourself.
Using the schemas#
import { PostCreateSchema } from './generated/turbine/zod.js';
const data = PostCreateSchema.parse(await req.json());
const post = await db.posts.create({ data });The three schemas#
For a posts table, generation emits:
import { z } from 'zod';
// Every column, as a read returns it
export const PostSchema = z.object({
id: z.number(),
title: z.string(),
views: z.number(),
published: z.boolean(),
createdAt: z.coerce.date(),
});
// Create input: generated, defaulted and nullable columns are optional
export const PostCreateSchema = z.object({
id: z.number().optional(),
title: z.string(),
views: z.number().optional(),
published: z.boolean(),
createdAt: z.coerce.date().optional(),
});
// Update input: every column optional, primary key omitted
export const PostUpdateSchema = z.object({
title: z.string().optional(),
views: z.number().optional(),
published: z.boolean().optional(),
createdAt: z.coerce.date().optional(),
});They match the generated *Create and *Update types. A primary key the database does not generate or default stays required in the create schema, such as a text natural key or a uuid with no default. STORED generated columns appear only in the row schema.
Type mapping#
| Column | Zod |
|---|---|
text, varchar, uuid | z.string() |
int, float | z.number() |
bigint | z.number(). Create and update also accept a string or a bigint. |
numeric | z.string(). Create and update also accept a number. |
boolean | z.boolean() |
timestamp, timestamptz, date | z.coerce.date(), which accepts a Date or a date string |
time, timetz | z.string(). Create and update also accept a Date. |
json, jsonb | z.unknown() |
bytea | z.instanceof(Uint8Array) |
| enum | z.enum([...labels]) |
vector | z.array(z.number()) |
| array column | the element schema with .array() |
| nullable column | the schema with .nullable() |