new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Drizzle · MySQL · all subjects

validation/typebox

21 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

typebox integration for Drizzle ORM

Drizzle ORM provides a typebox integration that allows you to generate typebox schemas from Drizzle ORM schemas. Install both drizzle-orm@rc and typebox as dependencies.

typebox schema generation functions

Three functions are available from drizzle-orm/typebox: createInsertSchema creates insert schemas for tables, createUpdateSchema creates update schemas for tables, and createSelectSchema creates select schemas for tables and views.

createInsertSchema for API request validation

createInsertSchema generates a typebox schema suitable for validating API requests when inserting data. It can be created by calling createInsertSchema(table).

createUpdateSchema for API request validation

createUpdateSchema generates a typebox schema suitable for validating API requests when updating data. It can be created by calling createUpdateSchema(table).

createSelectSchema for API response validation

createSelectSchema generates a typebox schema suitable for validating API responses when selecting data. It can be created by calling createSelectSchema(table).

typebox schema field override

When calling createInsertSchema, createUpdateSchema, or createSelectSchema, you can pass a second object argument to override generated fields. Pass field names as keys with typebox Type definitions as values.

typebox schema field refinement

When calling createInsertSchema, createUpdateSchema, or createSelectSchema, you can pass a second object argument with functions that refine fields. Each function receives the generated schema as a parameter and returns a modified typebox Type, allowing changes before fields become nullable or optional in the final schema.

typebox schema validation with Value.Check

To validate data against a generated typebox schema, use Value.Check(schema, data) from the typebox/value module, which returns a boolean indicating whether the data is valid.

Complete typebox schema generation example

import { int, mysqlTable, text, timestamp } from 'drizzle-orm/mysql-core'; import { createInsertSchema, createSelectSchema, createUpdateSchema } from 'drizzle-orm/typebox'; import { Type } from 'typebox'; import { Value } from 'typebox/value'; const users = mysqlTable('users', { id: int().primaryKey().autoincrement(), name: text().notNull(), email: text().notNull(), role: text({ enum: ['admin', 'user'] }).notNull(), createdAt: timestamp('created_at').notNull().defaultNow(), }); // Schema for inserting a user - can be used to validate API requests const insertUserSchema = createInsertSchema(users); // Schema for updating a user - can be used to validate API requests const updateUserSchema = createUpdateSchema(users); // Schema for selecting a user - can be used to validate API responses const selectUserSchema = createSelectSchema(users); // Overriding the fields const insertUserSchemaOverride = createInsertSchema(users, { role: Type.String(), }); // Refining the fields - useful if you want to change the fields before they become nullable/optional in the final schema const insertUserSchemaRefined = createInsertSchema(users, { id: (schema) => Type.Number({ ...schema, minimum: 0 }), role: Type.String(), }); // Usage const isUserValid: boolean = Value.Check(insertUserSchema, { name: 'John Doe', email: 'johndoe@test.com', role: 'admin', });

createSelectSchema generates validation schema for SELECT queries

The createSelectSchema function generates a Typebox validation schema from a table definition that describes the shape of data returned by SELECT queries. It can be used to validate API responses. When using the schema, all columns must be present in the query result or validation will fail.

createInsertSchema for insert validation

The createInsertSchema function generates a Typebox validation schema from a table definition that describes the shape of data to be inserted. It can be used to validate API requests. Auto-increment primary keys are optional in the schema, and non-nullable columns without defaults are required.

createUpdateSchema for update validation

The createUpdateSchema function generates a Typebox validation schema from a table definition that describes the shape of data to be updated. It can be used to validate API requests. All columns are optional in the update schema since partial updates are allowed.

Schema refinements with callbacks or overwrites

Each create schema function (createSelectSchema, createInsertSchema, createUpdateSchema) accepts an optional parameter object to extend, modify, or overwrite field schemas. Providing a callback function extends or modifies a field's schema, while providing a Typebox schema directly overwrites it including its nullability.

createSchemaFactory for extended Typebox instances

The createSchemaFactory function allows creating schema generation functions that work with extended Typebox instances. It accepts a configuration object with a typeboxInstance property, enabling use of custom Typebox extensions like Elysia's extended instance.

View schema generation with createSelectSchema

The createSelectSchema function is also supported for MySQL views created with mysqlView, generating validation schemas for view query results.

Install typebox-legacy for schema generation

The typebox-legacy package provides schema generation functions for Drizzle with MySQL. Install using: drizzle-orm@rc @sinclair/typebox

Example: createInsertSchema validation

import { int, mysqlTable, text } from 'drizzle-orm/mysql-core'; import { createInsertSchema } from 'drizzle-orm/typebox-legacy'; import { Value } from '@sinclair/typebox/value'; const users = mysqlTable('users', { id: int().primaryKey().autoincrement(), name: text().notNull(), age: int().notNull() }); const userInsertSchema = createInsertSchema(users); const user = { name: 'John' }; const parsed: { id?: number | undefined, name: string, age: number } = Value.Parse(userInsertSchema, user); // Error: `age` is not defined const user = { name: 'Jane', age: 30 }; const parsed: { id?: number | undefined, name: string, age: number } = Value.Parse(userInsertSchema, user); // Will parse successfully await db.insert(users).values(parsed);

Example: createUpdateSchema validation

import { int, mysqlTable, text } from 'drizzle-orm/mysql-core'; import { createUpdateSchema } from 'drizzle-orm/typebox-legacy'; import { Value } from '@sinclair/typebox/value'; import { eq } from "drizzle-orm"; const users = mysqlTable('users', { id: int().primaryKey().autoincrement(), name: text().notNull(), age: int().notNull() }); const userUpdateSchema = createUpdateSchema(users); const user = { age: 35 }; const parsed: { id?: number | undefined, name?: string | undefined, age?: number | undefined } = Value.Parse(userUpdateSchema, user); // Will parse successfully await db.update(users).set(parsed).where(eq(users.name, 'Jane'));

Example: Schema refinements with callbacks and overwrites

import { int, json, mysqlTable, text } from 'drizzle-orm/mysql-core'; import { createSelectSchema } from 'drizzle-orm/typebox-legacy'; import { Type } from '@sinclair/typebox'; import { Value } from '@sinclair/typebox/value'; const users = mysqlTable('users', { id: int().primaryKey().autoincrement(), name: text().notNull(), bio: text(), preferences: json() }); const userSelectSchema = createSelectSchema(users, { name: (schema) => Type.String({ ...schema, maxLength: 20 }), // Extends schema bio: (schema) => Type.String({ ...schema, maxLength: 1000 }), // Extends schema before becoming nullable/optional preferences: Type.Object({ theme: Type.String() }) // Overwrites the field, including its nullability }); const parsed: { id: number; name: string, bio: string | null; preferences: { theme: string; }; } = Value.Parse(userSelectSchema, ...);

Example: createSchemaFactory with extended Typebox instance

import { int, mysqlTable, text } from 'drizzle-orm/mysql-core'; import { createSchemaFactory } from 'drizzle-orm/typebox'; import { t } from 'elysia'; // Extended Typebox instance const users = mysqlTable('users', { id: int().primaryKey().autoincrement(), name: text().notNull(), age: int().notNull() }); const { createInsertSchema } = createSchemaFactory({ typeboxInstance: t }); const userInsertSchema = createInsertSchema(users, { // We can now use the extended instance name: (schema) => t.Number({ ...schema, error: "`name` must be a string" }) });

Typebox validation package support added

Drizzle added support for the Typebox package in the drizzle-typebox package. Documentation is available in the /docs/typebox section.

Give your agent this brain