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 Zod-specific type definitions of all tables in “dbname”, saving the new TypeScript code in ./mysqlToZod/schema.ts.

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

Summary

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

Please visit Discussions for all questions about usage, and suggestions for improvement.