Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
paths: - "packages/database/**"
Database Conventions (Tables & Migrations)
The canonical TABLE + MIGRATION template for Carbon. Grounded in the newest
migrations (packages/database/supabase/migrations/) and the root package.json
scripts. Tables get renamed and functions get revised — read the NEWEST
migration touching a table for current truth, never the first match or this doc.
Related (do not duplicate here):
- DB access — clients (supabase-js vs Kysely), services, RPC, generated types:
database-patterns.md. - SQL-level migration conventions — enums, views, triggers, no-companyId RLS,
the real per-statement patterns:
database-migration-patterns.md. - Full step-by-step workflow (checklist,
.models.tsupdates):workflow-database-migration.md.
Commands (verified in root package.json)
| Command | Resolves to | Purpose |
|---|---|---|
pnpm db:migrate:new <name> |
supabase migration new |
Create a new timestamped migration file. |
pnpm db:migrate |
crbn migrate |
Apply pending migrations to the local DB; also regenerates types + swagger. |
pnpm db:types |
tsx scripts/generate-db-types.ts |
Regenerate generated DB types (after migrations). |
- There is NO
db:buildscript — older docs/cache told people to runnpm run db:buildto "test" a migration. That command does not exist (it was removed; see rootREADME.md). Usepnpm db:migrateto apply locally. - Migration creation is
db:migrate:new <name>, NOTdb:migrate <name>—db:migratetakes no name and applies everything pending. - Never rebuild the DB to test changes. Wait for the user to do it.
Timestamp warning: never use 000000 for the HHMMSS portion (e.g.
…000000_foo.sql). The timestamp is the migration's primary key; randomize HHMMSS
(e.g. 20260619142853_…) to avoid cross-branch collisions.
Table Template (canonical, from 20260609143732_document-template.sql)
CREATE TABLE "entityName" (
"id" TEXT NOT NULL DEFAULT id(),
"companyId" TEXT NOT NULL,
-- Business columns
"name" TEXT NOT NULL,
"description" TEXT,
"active" BOOLEAN NOT NULL DEFAULT TRUE,
-- Audit columns (required) — reference "user" INLINE, no named constraints
"createdBy" TEXT NOT NULL REFERENCES "user"("id"),
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedBy" TEXT REFERENCES "user"("id"),
"updatedAt" TIMESTAMP WITH TIME ZONE,
-- Optional extensibility
"customFields" JSONB,
"tags" TEXT[],
PRIMARY KEY ("id", "companyId"),
FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE
);
-- Required indexes: companyId and every FK
CREATE INDEX "entityName_companyId_idx" ON "entityName" ("companyId");
CREATE INDEX "entityName_createdBy_idx" ON "entityName" ("createdBy");
-- Named, company-scoped uniqueness via ALTER (not inline)
ALTER TABLE "entityName" ADD CONSTRAINT "entityName_companyId_name_key"
UNIQUE ("companyId", "name");
Required Patterns
| Pattern | Rule |
|---|---|
| Primary key value | id TEXT NOT NULL DEFAULT id() — bare id() or prefixed id('pr'), id('sh'), id('je')… both are current. Never a raw UUID. |
| Composite PK | PRIMARY KEY ("id", "companyId") |
| Multi-tenancy | companyId TEXT NOT NULL + FK to company ON DELETE CASCADE |
| Audit columns | createdBy (NOT NULL), createdAt, updatedBy, updatedAt — *By reference "user"("id") inline. MANDATORY: any table with createdBy MUST also have updatedBy (nullable TEXT REFERENCES "user"("id")). The shared audit-injection path stamps updatedBy on every write; a table with createdBy but no updatedBy breaks those callers with column "updatedBy" does not exist. This holds even for append-only ledger tables — the column stays NULL there, but it must exist. |
updatedAt |
Set by the app on write, not a DB trigger. Don't add a generic timestamp trigger. |
| Indexes | Index companyId and every FK (e.g. createdBy) |
| Never | An itemReadableId column; decimal places in a NUMERIC (use bare NUMERIC) |
| Naming | Never name a column, enum or field kind / *Kind, and never label a form field "Kind". Name what the value decides: revenueType (One-time / Recurring), entryType, billingFrequency. The enum takes the same name as the concept (contractRevenueType). "Kind" forces every reader to open the enum to learn what it means. |
Column Types
| Type | Use For |
|---|---|
TEXT |
IDs, names, strings |
NUMERIC |
Financial amounts / quantities needing fractions (no precision spec) |
INTEGER |
Whole counts |
TIMESTAMP WITH TIME ZONE |
Dates/times |
DATE |
Calendar dates (no time) |
BOOLEAN NOT NULL DEFAULT |
Flags |
JSONB |
Custom fields / structured config |
TEXT[] |
Tags / arrays of ids |
RLS Policies
Policies are not written in migrations. Add the table's rule to
packages/database/src/authz/manifest.ts — usually one line, entityName: company("<module>"),
which renders the four standard policies (SELECT any employee via
get_companies_with_employee_role(), writes via
get_companies_with_employee_permission('<module>_<action>')) — then pnpm db:migrate syncs it
locally and pnpm --filter @carbon/database authz migration <name> ships it to production.
Full guide, including tables without a companyId: authz-manifest.md.
- The old
has_role/has_company_permission/get_companies_with_permission/get_permission_companieshelpers are gone — dropped in20260927224314_retire-legacy-rls-helpers.sql(they admitted customer and supplier portal accounts);authz-fixes.test.sqlasserts they stay gone. - For tables without a
companyIdcolumn, reach the company through the parent (parent(...),viaParent,exists), gating writes on the write permission.
Views
Always SECURITY_INVOKER=true so the underlying tables' RLS applies to the caller:
CREATE OR REPLACE VIEW "module_entityView" WITH(SECURITY_INVOKER=true) AS
SELECT e.*, u."fullName" AS "createdByFullName"
FROM "entityName" e
LEFT JOIN "user" u ON u."id" = e."createdBy";
Triggers
There is no generic per-table boilerplate trigger (no updatedAt/companyId
trigger to add). Triggers here are purpose-built — status recomputation,
search-index sync, the event-system dispatch — and live in their own migrations
(e.g. update_picking_list_status_trigger in 20260601143527_picking-lists.sql).
Add a trigger only when there's real derived state to maintain. For async/event-driven
side effects use the event system (event-system.md), not ad-hoc triggers. See
database-migration-patterns.md for enum/trigger details.
Zod Validators
After the migration, update the module's {module}.models.ts (full pattern in
conventions-forms.md):
import { z } from "zod";
import { zfd } from "zod-form-data";
export const entityValidator = z.object({
id: z.string().optional(),
name: z.string().min(1),
description: z.string().optional(),
active: zfd.checkbox(),
});
Validate in route actions with validator(schema).validate(formData) from
@carbon/form — not schema.parse().
Migration Checklist
- File created with
pnpm db:migrate:new <name>(HHMMSS not000000) -
idusesid()(bare or prefixed) for the PK value — never a raw UUID -
companyIdpresent with composite PK("id", "companyId")+ FKON DELETE CASCADE - Audit columns;
*Byreference"user"("id")inline - Indexes on
companyIdand every FK - No
CREATE POLICYin the migration; the table's rule is inauthz/manifest.tsand shipped withpnpm --filter @carbon/database authz migration <name> - Zod validators in
{module}.models.ts - Applied locally with
pnpm db:migrate(regenerates types) — neverdb:build - A CHECK that needs one of several nullable FK columns set (
a IS NOT NULL OR b IS NOT NULL, a discriminator CHECK): if the demo datasets seed the table, add it toPARENT_CHECK_TABLESinpackages/database/src/datasets/wipe.ts. Re-applying demo data nulls every nullable FK into a table it clears, which trips that CHECK (pnpm db:check:datasetscatches it)