---
name: db-schema
description: "Use when adding or changing PostgreSQL tables, columns, constraints, indexes, enums, foreign keys or relations with Drizzle, the Zod schema and type derived from a table, validation messages, or when a migration is asked for."
metadata:
  type: convention
  library: wcz-layout
---

Migration commands and drizzle-kit output: load `drizzle-kit#drizzle-migrations` and
`drizzle-kit#drizzle-generate`.

## Rules

- One table per file in `src/server/db/schemas/`, named after it (`bookTable` in `book.ts`),
  even for a parent and its children. Tables use `snakeCase.table("<plural>", …)`.
- Primary key `id: uuid().primaryKey()` with no default: the client creates the id with
  `uuidv7()`.
- Timestamps: `timestamp({ withTimezone: true })`.
- Foreign keys declare `onDelete` from the business rule: `"cascade"` when the child is
  meaningless without the parent, `"restrict"` when the parent must outlive its children,
  `"set null"` for optional references. Index every foreign key column; Postgres does not.
- Enums: `pgEnum` in the table's file, exported; everything else reads `.enumValues`, never
  a second list.
- Relations live in the one `relations.ts` (`defineRelations`), never in table files.
- The entity's Zod schema is `createSelectSchema(table, refinements)` from `drizzle-orm/zod`
  in `src/lib/schemas/<entity>.ts`, with `export type <Entity> = z.infer<…>`. The client builds
  whole rows, id included, so this one schema validates the form, the collection and the
  server function input.
- Refinements tighten existing columns only (an unknown key is a type error): text gets
  `.trim()`, `.min(1)` when required, `.max(n)`. Add related or derived fields with `.extend()`.
- Messages are lazy: `{ error: () => t("Validation.Required") }`. A plain `t(...)` runs once at
  import, before the user's language is known, and never follows a language switch.
- Every table is audited: startup runs `attach_audit_triggers_all()` and `databaseMiddleware`
  sets the acting user. Never add history tables or audit triggers.
- Migrations apply at startup.

## Examples

```ts
// src/server/db/schemas/library.ts
import { snakeCase, text, uuid } from "drizzle-orm/pg-core";

export const libraryTable = snakeCase.table("libraries", {
  id: uuid().primaryKey(),
  name: text().notNull(),
});
```

```ts
// src/server/db/schemas/book.ts
import { index, pgEnum, snakeCase, text, timestamp, uuid } from "drizzle-orm/pg-core";
import { libraryTable } from "./library";

export const bookStatusEnum = pgEnum("book_status", ["draft", "published"]);

export const bookTable = snakeCase.table(
  "books",
  {
    id: uuid().primaryKey(),
    title: text().notNull(),
    status: bookStatusEnum().notNull().default("draft"),
    libraryId: uuid()
      .notNull()
      .references(() => libraryTable.id, { onDelete: "cascade" }),
    createdAt: timestamp({ withTimezone: true }).defaultNow().notNull(),
  },
  (table) => [index().on(table.libraryId)],
);
```

```ts
// src/server/db/schemas/relations.ts
import { defineRelations } from "drizzle-orm";
import { bookTable } from "./book";
import { libraryTable } from "./library";

export const relations = defineRelations(
  { libraryTable, bookTable },
  ({ one, many, libraryTable: library, bookTable: book }) => ({
    libraryTable: {
      books: many.bookTable(),
    },
    bookTable: {
      library: one.libraryTable({ from: book.libraryId, to: library.id }),
    },
  }),
);
```

```ts
// src/lib/schemas/<entity>.ts
import { createSelectSchema } from "drizzle-orm/zod";
import { t } from "wcz-layout/utils";
import type { z } from "zod";
import { bookTable } from "~/server/db/schemas/book";

export const BookSchema = createSelectSchema(bookTable, {
  title: (schema) =>
    schema
      .trim()
      .min(1, { error: () => t("Validation.Required") })
      .max(255, { error: () => t("Validation.MaxLength", { length: 255 }) }),
});

export type Book = z.infer<typeof BookSchema>;
```
