Rules for designing the database schema, writing migrations, and seeding data per target. Produces docs/schema.md and the data-layer code. Used by database-engineer only.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Db Schema?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/sayeed1999-db-schema)
---
name: db-schema
description: Rules for designing the database schema, writing migrations, and seeding data per target. Produces docs/schema.md and the data-layer code. Used by database-engineer only.
---
# db-schema
Output: `docs/schema.md`, and the data-layer paths of the confirmed stack in `skills/stack-defaults`: models, migrations, and seed.
## Steps
### 1. Read
- `docs/architecture.md`: target, database engine, section 5 entities, section 8 data flow.
- `contracts/api.md`: every field each table must serve, every list filter and sort.
- `contracts/ai.md`: tool queries, and the RAG storage when present.
- `docs/stories/R-NN.md` for your task's R-IDs: uniqueness, limits, deletes, ownership.
- Existing `docs/schema.md` and migrations. Extend them. Never rewrite applied ones.
### 2. Design the tables
- One table per entity in section 5. Apply the Naming, Keys, Columns, and Relations rules below.
- Map every contract field to a column, or mark it `computed` with the formula's source.
- Write `docs/schema.md` in the Format below before writing code.
### 3. Write the models and one migration
- Models in the stack's data-layer path. Use the ORM's portable types for `django` and `fastapi`.
- One migration per task. It runs `up` and `down` cleanly.
### 4. Write the seed
- Follow the Seed rules for the target.
### 5. Verify
- On an empty database: migrate up, down, up.
- Run the seed twice. The second run adds nothing.
- Print the row count per table. Put the counts in the RESULT Summary.
- Engine: SQLite runs locally. PostgreSQL runs in a throwaway container: `docker run --rm -d --name schema-check -e POSTGRES_PASSWORD=check -p 127.0.0.1:55432:5432 postgres:18`, then `docker stop schema-check`.
- Docker not available: raise an `env` blocker (`skills/flow`). Never mark the task `built` unverified.
## Naming
- Tables: plural `snake_case` (`products`, `stock_moves`).
- Columns: singular `snake_case`. Foreign keys: `<entity>_id`.
- Indexes: `<table>_<columns>_idx`. Unique: `<table>_<columns>_key`. Checks: `<table>_<rule>_check`.
## Keys
- Default primary key: `id`, UUIDv7.
- Why: not guessable, made in the app before insert, time-ordered so the index stays compact.
- PostgreSQL 18+: `uuid` with default `uuidv7()`. Also set it in the app.
- SQLite: the ORM's UUID type, value made in the app.
- Python: `uuid.uuid7()` on 3.14+, otherwise `uuid_utils.compat.uuid7()` (`uuid-utils`). Go: `uuid.NewV7()` (`github.com/google/uuid`).
- Use `bigint` identity instead only when both are true:
- The id never appears in `contracts/api.md` or a URL.
- The table is append-heavy: events, logs, ledger lines, messages.
- PostgreSQL: `bigint GENERATED ALWAYS AS IDENTITY`. SQLite: `INTEGER PRIMARY KEY`.
- SQLAlchemy: `BigInteger().with_variant(Integer, "sqlite")`, or SQLite will not autoincrement.
- Join tables: composite primary key of the two foreign keys. No `id`.
- Record the key choice per table in `docs/schema.md`.
## Columns
- `NOT NULL` by default. Nullable only when a story allows the value to be missing.
- Every table: `created_at` and `updated_at`, timestamp with time zone, UTC, not null.
- Money: integer minor units (`price_cents bigint`). Never float.
- Text: `text`. Enforce story length limits with a check.
- Fixed choices: `text` with a check listing the values. No database enum types.
- Booleans: not null with a default.
- JSON: only for data the app never filters or sorts on.
- Passwords: one `password_hash` column. Never the password.
## Relations
- Every foreign key has an index.
- Every foreign key states `ON DELETE`: `CASCADE` for owned children, `RESTRICT` otherwise.
- User-owned rows have an owner column (`user_id`) so the backend can check ownership.
- Soft delete (`deleted_at`) only when a story keeps deleted items visible or restorable.
## Constraints and indexes
- Every story rule the database can hold is a constraint: unique, check, not null.
- Case-insensitive uniqueness: PostgreSQL unique index on `lower(<column>)`. SQLite: `COLLATE NOCASE`.
- Target `mvp` or `production`: one index per list filter or sort in `contracts/api.md`.
- RAG with PostgreSQL: a `vector(<dims>)` column with an HNSW index. Dimensions come from `contracts/ai.md`.
- AI runtime `langgraph`: the checkpointer creates its own tables. List them in `docs/schema.md` as `managed by langgraph`. Never migrate them.
## Migrations
- One migration per task, named after it (`0003_products`).
- Never edit a migration that a `built` or `done` task shipped. Add a new one.
- Target `mvp` or `production`: only additive changes in one migration. Rename or drop in two steps: add and copy, then drop in a later task.
- Dropping a table or column that holds data: raise a `user` blocker first.
- Target `production`: create indexes on existing large tables concurrently (`CREATE INDEX CONCURRENTLY`).
## Seed
- One seed command per stack (`skills/stack-defaults`, Commands). Mode comes from `SEED_MODE`.
- Every mode is idempotent: insert by natural key, skip what exists.
- Fake people use `example.com` emails and invented names. Never real PII.
### Target `prototype`: `SEED_MODE=demo`
- Realistic data in the language and domain of the PRD. No `test1`, `foo`, or lorem ipsum.
- 20 to 50 rows per main entity. Enough to fill and scroll every list screen.
- Dates spread over the last 90 days, relative to the run time.
- One row per edge case in the stories: low stock, overdue, empty child list, longest allowed name.
- Fixed random seed, so the same facts appear every run.
- List the facts QA can rely on (counts, named rows) at the end of `docs/schema.md`.
### Target `mvp` or `production`: `SEED_MODE=reference`
- Only data the app needs to work: roles, categories, settings.
- The first admin account comes from env (`ADMIN_EMAIL`, `ADMIN_PASSWORD`) when accounts are admin-created.
- `SEED_MODE=demo` also works, for local runs only. Write that in `docs/schema.md`.
## Format: `docs/schema.md`
```
# Schema
- Engine: PostgreSQL 18 | SQLite
- Target: prototype | mvp | production
- Migrations: <tool and folder>
- Seed: <command>, mode <demo | reference>
## products
- R-IDs: R-01
- Key: id uuid v7
- Columns:
- id: uuid, pk
- name: text, not null, 1-120 chars
- price_cents: bigint, not null, >= 0
- owner_id: uuid, not null, fk users.id on delete restrict
- created_at: timestamptz, not null
- updated_at: timestamptz, not null
- Indexes:
- products_name_lower_key: unique (lower(name))
- products_owner_id_idx: (owner_id)
- Serves: GET /v1/products (id, name, price_cents)
## Seed facts
- products: 32 rows. "Rice 5kg" has stock 2 (low stock).
```
## MUST
- Map every contract field to a column or a recorded formula.
- Record every non-default choice with the R-ID or rule behind it.
- Keep `docs/schema.md` and the migrations in step.
## NEVER
- Add a table or column without an R-ID or a contract field that needs it.
- Store secrets, tokens, or passwords in plain text.
- Seed fake data into a production database.
- Use random UUIDv4 or `serial` as a primary key.
- Use an email, name, or other natural value as a primary key.