Database Engineering
Repository planning gate
When this repository's CLAUDE.md classifies the request as complex or high-impact, the primary agent must invoke plan-tasks before entering this workflow's Inspect, Model, or Contract phase. A subagent must return control to the primary agent rather than create a competing plan or edit target files. Resume this workflow only after an approved docs/plans/PLAN_<descriptive-name>.md maps the relevant A-* to database-engineering, its assigned role, worktree isolation, and verification. This skill's model and migration planning refine an approved action; they never replace user approval.
Use this skill for database design, schema implementation, migration planning, query optimization, and data integrity review.
Follow seven phases:
- Inspect
- Model
- Contract
- Implement
- Optimize
- Verify
- Report
Database changes define durable business facts. Ground decisions in product requirements, existing schema, migrations, ORM models, query code, data volume, access patterns, and explicit user confirmation. Do not invent tables, fields, relationships, enum values, retention rules, or performance requirements.
Resource Guide
Load these references only when needed:
references/project-recon.md: Use during Inspect to identify database engine, ORM, migration workflow, schemas, seeds, tests, and runtime commands.
references/data-modeling.md: Use when designing entities, fields, relationships, normalization, denormalization, snapshots, enums, and JSON columns.
references/schema-contract.md: Use before writing or changing tables, constraints, foreign keys, indexes, or ORM models.
references/migrations-and-evolution.md: Use whenever schema changes require migrations, backfills, compatibility, rollbacks, or large-table changes.
references/indexing-and-query-plans.md: Use for query performance, indexes, sorting, filtering, pagination, joins, and execution plans.
references/transactions-and-concurrency.md: Use when writes span multiple rows/tables, counters, inventory, balances, status transitions, idempotency, or locks.
references/security-and-compliance.md: Use when data includes users, tenants, permissions, PII, secrets, payments, audit logs, retention, or deletion.
references/optimization-workflow.md: Use for slow queries, high load, database bottlenecks, storage growth, or performance regressions.
references/verification-checklist.md: Use before final response.
Use these scripts as black-box helpers. Run each with --help before use:
scripts/inspect_database_project.py: Project reconnaissance report in JSON.
scripts/scan_schema_risks.py: Static scan for common schema, migration, and query risk patterns.
Phase 1: Inspect
Inspect before designing or editing. Do not guess the database engine, ORM, migration tool, naming style, ID strategy, tenant model, cascade behavior, or query patterns.
Find:
- Database engine and version when available
- ORM or query builder
- Schema/model definitions
- Migration files and migration command
- Seed, fixture, factory, and test data patterns
- Existing naming conventions for tables, columns, indexes, constraints, and timestamps
- Current primary key, foreign key, enum, soft-delete, audit, and tenant conventions
- Read/write access paths in routes, services, repositories, jobs, and reports
- Existing indexes and slow-query evidence when available
- Backup, retention, data deletion, or compliance constraints if documented
Run scripts/inspect_database_project.py for a first pass, then read the relevant files it identifies. For detailed guidance, read references/project-recon.md.
Phase 2: Model
Model the data before writing DDL or ORM code.
Define:
- Business entities and aggregate boundaries
- Attributes and which facts are canonical
- Entity relationships: one-to-one, one-to-many, many-to-many, optional, required
- Identity strategy: surrogate keys, natural keys, public IDs, tenant-scoped IDs
- Required fields, nullable fields, defaults, and generated fields
- Field types, precision, length, timezone, collation, and units
- Unique constraints and business invariants
- Lifecycle states and allowed transitions
- Historical snapshots needed for correctness
- Delete/archive behavior and retention requirements
- Expected read and write access patterns
For new designs, read references/data-modeling.md.
Phase 3: Contract
Create a schema contract before implementation.
For each table or collection, specify:
- Purpose and source of truth
- Columns with type, nullability, default, and validation rules
- Primary key and public identifier
- Foreign keys and relationship cardinality
- Unique constraints and check constraints
- Indexes justified by access patterns
- Ownership, tenant, and authorization fields
- Audit fields and soft-delete fields
- Migration/backfill requirements
- Example queries the schema must support
For detailed contract guidance, read references/schema-contract.md.
Phase 4: Implement
Implement using the project's established database layer.
Rules:
- Use existing migration, ORM, naming, timestamp, and test patterns.
- Prefer database constraints for invariants that must always hold.
- Use foreign keys unless the project deliberately avoids them and has a documented alternative.
- Use precise types for money, counts, timestamps, and identifiers.
- Avoid raw SQL string interpolation.
- Preserve existing data and application compatibility unless the user requested a breaking migration.
- Add focused tests, fixtures, or seed changes when the project has test infrastructure.
- Keep migrations reversible when the local migration system supports it.
For migration details, read references/migrations-and-evolution.md.
Phase 5: Optimize
Optimize from evidence, not intuition.
Use:
- Query plan
- Slow query log
- Reproduction query
- Endpoint benchmark
- Database metrics
- User report tied to a concrete access path
Prefer targeted fixes: query shape, correct indexes, pagination, batched loading, reduced overfetching, materialized summaries, partitioning, or caching with clear invalidation. For detailed guidance, read references/optimization-workflow.md and references/indexing-and-query-plans.md.
Phase 6: Verify
Do not finish after writing schema or query code. Verify with the strongest checks available.
Run applicable checks:
- Migration generation or dry-run
- Migration apply against a local/test database
- Migration rollback when supported
- ORM type generation
- Unit, integration, repository, or API tests
- Static schema risk scan
- Query plan review for changed high-traffic queries
- Data backfill validation
- Tenant/authorization tests for scoped data
Use scripts/scan_schema_risks.py for a first-pass risk scan. For detailed QA guidance, read references/verification-checklist.md.
Phase 7: Report
Final response should include:
- What data model or schema changed
- Key tables, columns, relationships, constraints, and indexes
- Migration/backfill behavior
- Query or performance implications
- Tests and checks run
- Any verification that could not run and why
- Remaining risks or assumptions
Keep the response concise and factual.
1---2name: database-engineering3description: End-to-end database engineering workflow for designing relational data models, writing schemas and migrations, reviewing constraints, creating indexes, optimizing queries, and hardening persistence behavior. Use when the user asks to design a database, create or change tables, choose fields/types/keys, model entity relationships, write SQL/ORM migrations, review database schema quality, improve slow queries, add indexes, plan transactions, handle multi-tenant data, or evaluate data integrity/security risks. Do NOT use for frontend-only work, one-off spreadsheet analysis, or high-level product brainstorming with no persisted data model.4---56# Database Engineering78## Repository planning gate910When this repository's `CLAUDE.md` classifies the request as complex or high-impact, the primary agent must invoke `plan-tasks` before entering this workflow's Inspect, Model, or Contract phase. A subagent must return control to the primary agent rather than create a competing plan or edit target files. Resume this workflow only after an approved `docs/plans/PLAN_<descriptive-name>.md` maps the relevant `A-*` to `database-engineering`, its assigned role, worktree isolation, and verification. This skill's model and migration planning refine an approved action; they never replace user approval.1112Use this skill for database design, schema implementation, migration planning, query optimization, and data integrity review.1314Follow seven phases:15161. Inspect172. Model183. Contract194. Implement205. Optimize216. Verify227. Report2324Database changes define durable business facts. Ground decisions in product requirements, existing schema, migrations, ORM models, query code, data volume, access patterns, and explicit user confirmation. Do not invent tables, fields, relationships, enum values, retention rules, or performance requirements.2526## Resource Guide2728Load these references only when needed:2930- `references/project-recon.md`: Use during Inspect to identify database engine, ORM, migration workflow, schemas, seeds, tests, and runtime commands.31- `references/data-modeling.md`: Use when designing entities, fields, relationships, normalization, denormalization, snapshots, enums, and JSON columns.32- `references/schema-contract.md`: Use before writing or changing tables, constraints, foreign keys, indexes, or ORM models.33- `references/migrations-and-evolution.md`: Use whenever schema changes require migrations, backfills, compatibility, rollbacks, or large-table changes.34- `references/indexing-and-query-plans.md`: Use for query performance, indexes, sorting, filtering, pagination, joins, and execution plans.35- `references/transactions-and-concurrency.md`: Use when writes span multiple rows/tables, counters, inventory, balances, status transitions, idempotency, or locks.36- `references/security-and-compliance.md`: Use when data includes users, tenants, permissions, PII, secrets, payments, audit logs, retention, or deletion.37- `references/optimization-workflow.md`: Use for slow queries, high load, database bottlenecks, storage growth, or performance regressions.38- `references/verification-checklist.md`: Use before final response.3940Use these scripts as black-box helpers. Run each with `--help` before use:4142- `scripts/inspect_database_project.py`: Project reconnaissance report in JSON.43- `scripts/scan_schema_risks.py`: Static scan for common schema, migration, and query risk patterns.4445## Phase 1: Inspect4647Inspect before designing or editing. Do not guess the database engine, ORM, migration tool, naming style, ID strategy, tenant model, cascade behavior, or query patterns.4849Find:5051- Database engine and version when available52- ORM or query builder53- Schema/model definitions54- Migration files and migration command55- Seed, fixture, factory, and test data patterns56- Existing naming conventions for tables, columns, indexes, constraints, and timestamps57- Current primary key, foreign key, enum, soft-delete, audit, and tenant conventions58- Read/write access paths in routes, services, repositories, jobs, and reports59- Existing indexes and slow-query evidence when available60- Backup, retention, data deletion, or compliance constraints if documented6162Run `scripts/inspect_database_project.py` for a first pass, then read the relevant files it identifies. For detailed guidance, read `references/project-recon.md`.6364## Phase 2: Model6566Model the data before writing DDL or ORM code.6768Define:6970- Business entities and aggregate boundaries71- Attributes and which facts are canonical72- Entity relationships: one-to-one, one-to-many, many-to-many, optional, required73- Identity strategy: surrogate keys, natural keys, public IDs, tenant-scoped IDs74- Required fields, nullable fields, defaults, and generated fields75- Field types, precision, length, timezone, collation, and units76- Unique constraints and business invariants77- Lifecycle states and allowed transitions78- Historical snapshots needed for correctness79- Delete/archive behavior and retention requirements80- Expected read and write access patterns8182For new designs, read `references/data-modeling.md`.8384## Phase 3: Contract8586Create a schema contract before implementation.8788For each table or collection, specify:8990- Purpose and source of truth91- Columns with type, nullability, default, and validation rules92- Primary key and public identifier93- Foreign keys and relationship cardinality94- Unique constraints and check constraints95- Indexes justified by access patterns96- Ownership, tenant, and authorization fields97- Audit fields and soft-delete fields98- Migration/backfill requirements99- Example queries the schema must support100101For detailed contract guidance, read `references/schema-contract.md`.102103## Phase 4: Implement104105Implement using the project's established database layer.106107Rules:108109- Use existing migration, ORM, naming, timestamp, and test patterns.110- Prefer database constraints for invariants that must always hold.111- Use foreign keys unless the project deliberately avoids them and has a documented alternative.112- Use precise types for money, counts, timestamps, and identifiers.113- Avoid raw SQL string interpolation.114- Preserve existing data and application compatibility unless the user requested a breaking migration.115- Add focused tests, fixtures, or seed changes when the project has test infrastructure.116- Keep migrations reversible when the local migration system supports it.117118For migration details, read `references/migrations-and-evolution.md`.119120## Phase 5: Optimize121122Optimize from evidence, not intuition.123124Use:125126- Query plan127- Slow query log128- Reproduction query129- Endpoint benchmark130- Database metrics131- User report tied to a concrete access path132133Prefer targeted fixes: query shape, correct indexes, pagination, batched loading, reduced overfetching, materialized summaries, partitioning, or caching with clear invalidation. For detailed guidance, read `references/optimization-workflow.md` and `references/indexing-and-query-plans.md`.134135## Phase 6: Verify136137Do not finish after writing schema or query code. Verify with the strongest checks available.138139Run applicable checks:140141- Migration generation or dry-run142- Migration apply against a local/test database143- Migration rollback when supported144- ORM type generation145- Unit, integration, repository, or API tests146- Static schema risk scan147- Query plan review for changed high-traffic queries148- Data backfill validation149- Tenant/authorization tests for scoped data150151Use `scripts/scan_schema_risks.py` for a first-pass risk scan. For detailed QA guidance, read `references/verification-checklist.md`.152153## Phase 7: Report154155Final response should include:156157- What data model or schema changed158- Key tables, columns, relationships, constraints, and indexes159- Migration/backfill behavior160- Query or performance implications161- Tests and checks run162- Any verification that could not run and why163- Remaining risks or assumptions164165Keep the response concise and factual.