Turbine

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 --zod

The 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#

ColumnZod
text, varchar, uuidz.string()
int, floatz.number()
bigintz.number(). Create and update also accept a string or a bigint.
numericz.string(). Create and update also accept a number.
booleanz.boolean()
timestamp, timestamptz, datez.coerce.date(), which accepts a Date or a date string
time, timetzz.string(). Create and update also accept a Date.
json, jsonbz.unknown()
byteaz.instanceof(Uint8Array)
enumz.enum([...labels])
vectorz.array(z.number())
array columnthe element schema with .array()
nullable columnthe schema with .nullable()

See also#

  • CLI: turbine generate and its flags.
  • Schema: the column metadata these schemas come from.