Skip to content

Introduction

What is mysql-to-zod?

mysql-to-zod is a tool that generates Zod type definitions from MySQL table definitions.

Usage

Terminal window
npx mysql-to-zod mysql://user:password@localhost:3306/dbname

The above command will generate a type definition of zod in . /mysqlToZod/schema.ts will generate a type definition for zod.

Example

Suppose DB: my_todo has the following table definitions.

CREATE TABLE todo (
id INT NOT NULL AUTO_INCREMENT,
task VARCHAR(255) NOT NULL,
completed BOOLEAN NOT NULL DEFAULT false,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id)
);

From the above table definition, the following zod schema is generated.

import { z } from "zod";
export const todoSchema = z.object({
id: z.number(),
task: z.string(),
completed: z.number(),
created_at: z.date().nullish(),
updated_at: z.date().nullish(),
});
export type Todo = z.infer<typeof todoSchema>;

These are the basic instructions for use. In many cases the above is all that is needed, but there are options that can be customized. For example, if you want the variable name to be TODO_SCHEMA instead of todoSchema.

For more detailed options, please see the next page.

Notice

If you have any questions about usage or suggestions for improvement, please visit disucussions. Disucussions