Drizzle Util Guide
This guide covers the usage details of Drizzle Util.
Scaffold
A scaffold, in Drizzle Util, is the Drizzle ORM table definition generated by the CLI tool.
After the initial configuration is completed from running the init
command, you can create Drizzle ORM scaffolding with the scaffold
command.
The -c
option takes a space-separated string of column configurations in the following format: column_name:dataType
. The data types map directly to most of the available data types in Drizzle ORM. See Data Types for a list of supported data types.
The id
, created_at
, and updated_at
fields are automatically generated by Drizzle Express, and should be omitted from the command.
After scaffolding, you can review the schema and make any necessary changes before running the database migrations.
Example command:
npx drizzle-express@latest scaffold products -c title:text price:integer description:text
Example scaffold
This is an example schema scaffolded by Drizzle Util:
import { relations } from "drizzle-orm";
import { pgTable, text, integer, timestamp } from "drizzle-orm/pg-core";
import { createId } from "@paralleldrive/cuid2";
import { categories } from "@/schema/categories";
export const posts = pgTable("posts", {
id: text()
.primaryKey()
.$defaultFn(() => createId()),
categoryId: text().references(() => categories.id),
title: text(),
likes: integer(),
publishedAt: timestamp(),
content: text(),
createdAt: timestamp().notNull().defaultNow(),
updatedAt: timestamp()
.notNull()
.defaultNow()
.$onUpdate(() => new Date()),
});
export type SelectPost = typeof posts.$inferSelect;
export type InsertPost = typeof posts.$inferInsert;
export const postsRelations = relations(posts, ({ one, many }) => ({
category: one(categories, {
fields: [posts.categoryId],
references: [categories.id],
}),
}));
The table definition, inferred types, and relations are provided in a single file.
Data Types
See Data Types.
Primary key strategy
See Primary key strategy.
Foreign key constraints
Drizzle Util supports adding foreign key constraints using the following special references
data type.
For example, a one to many relationship where a post belongs to a category can be set up using the following scaffolds.
First, scaffold the one
side of the relationship.
npx drizzle-express@latest scaffold category -c title:text
Second, scaffold the many
side of the relationship:
npx drizzle-next@latest scaffold post -c category_id:references title:text
Project structure
Drizzle Express uses the following project structure:
- drizzle
- scripts
- src
- config
- schema