Home

ORM Drizzle Overview

Drizzle structure in create-light-stack.

Directory Structure

packages/database/
├── src/
│   ├── db.ts
│   ├── index.ts
│   ├── validator/
│   │   └── example.ts
│   └── schema/
│       └── example.ts
├── .env
├── drizzle.config.ts
├── package.json
└── tsconfig.json    

Connection To Api

connectDB is exported to api to connect.
It takes DATABASE_URL from .env.

import { drizzle } from "drizzle-orm/node-postgres";
import pg from "pg";
import * as schema from "./schema/example.js";

const { Pool } = pg;

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
});

export const db = drizzle(pool, { schema });

export const connectDB = async () => {
  try {
    await pool.query("SELECT 1");
    console.log("Postgres connected");
  } catch (err) {
    console.error("Postgres connection failed", err);
    process.exit(1);
  }
};

Defining Tables

To add or modify tables, edit the files in src/schema/.
We use pgTable to define columns. Drizzle infers TypeScript types automatically from these definitions.

// src/schema/example.ts
import { pgTable, serial, varchar, text } from "drizzle-orm/pg-core";

export const example = pgTable("example", {
  id: serial("id").primaryKey(),
  title: varchar("title", { length: 200 }).notNull(),
  description: text("description"),
});

Exporting the Schema

Make sure to export your new table in packages/database/src/index.ts so your API can use it.

// packages/database/src/index.ts 
export * from "./schema/example.js";

Zod Integration (Validation)

We automatically generate Zod validation schemas from your database tables.

// packages/database/src/validators/example.ts 
import { createInsertSchema, createSelectSchema } from "drizzle-zod";
import { example } from "../schema/example";

export const insertExampleSchema = createInsertSchema(example, {
    title: s=>s.min(1), // add custom zod rules
    });

export const selectExampleSchema = createSelectSchema(example);

Migrations

Whenever you change a schema file, you must tell the database about it.

First generate

npm run generate --workspace=@light/database

Then Push

npm run migrate --workspace=@light/database

Useful Resources

On this page