PostgreSQL Migration & Schema Standards
Purpose
Defines the strict enterprise standards for writing PostgreSQL database migration scripts, ensuring multi-tenancy, soft-deletes, auditability, performance (partitioning/indexes), and mandatory documentation via COMMENT ON. Responsibility boundary: authors or edits migration scripts only; does NOT run migrations against any database and does NOT edit already-applied migrations.
When to Use / When NOT to Use
- Use: Writing new Flyway/Liquibase migration scripts (
VXXX__name.sql), designing PostgreSQL tables, adding columns to existing tables.
- NOT: NoSQL databases, simple SQLite prototypes, or ORM-only auto-migrations in production.
- NOT: Zero-downtime rollout and rollback strategy (use
database-migrations).
- NOT: Query tuning or EXPLAIN analysis (use
database-query-optimization).
- NOT: Conceptual schema modelling or ERDs (use
database-schema-design).
Prerequisites & Assumptions
- PostgreSQL 12+ (for declarative partitioning and JSONB features).
- Migration tool (Flyway, Liquibase, or golang-migrate) managing versioned SQL files.
Scope & Context Resolution
- Supported scopes: project/repository, migration directory, migration script file, table, column, index/constraint. Default when none is given: the single new migration script for the table(s) the user names.
- Rule 1 - Explicit context in the prompt: the user's stated requirements, constraints, versions, targets and scope are authoritative. Apply this skill strictly within them. MUST NOT add assumptions or expand beyond them. If a user instruction conflicts with a skill rule, follow the user and state the deviation in one line, EXCEPT security/data-loss rules(never drop data or edit applied migrations without confirmation), which stay mandatory: flag the conflict instead.
- Rule 2 - No extra context: use this skill's Purpose, workflow and rules as the sole context, at the default scope. MUST NOT import unrelated requirements or assumptions.
- Rule 3 - Explicit scope: operate ONLY inside the named scope. Out-of-scope files may be READ as evidence but MUST NOT be modified; report out-of-scope observations as notes, never as changes. Widening scope requires explicit user approval.
- Mutation boundary: edits limited to new or explicitly named migration files; MUST NOT modify applied migrations, execute SQL against a database, or alter application code.
Step-by-Step Workflow
- Resolve scope and context: apply the section above; state the resolved scope and mutation boundary in one line at the start of the output.
- Create a new migration file with sequential versioning (e.g.,
V001__add_carrier_domain.sql).
- Define tables with standard audit, multi-tenant, and soft-delete columns.
- Add explicit constraints (PK, UK, FK, CHECK) using
ALTER TABLE after creation.
- Create targeted indexes for performance and soft-delete filtering.
- Apply declarative partitioning for high-volume/audit tables.
- Write
COMMENT ON TABLE and COMMENT ON COLUMN for every single entity.
Enterprise Rules & Standards (MUST / SHOULD / MUST NOT)
0. Scope
- MUST: Stay within the resolved scope; MUST NOT modify or expand beyond it without explicit user approval.
- MUST NOT: Alter tables, columns or data outside the named scope, or edit already-applied migration files (add a new versioned script instead).
1. Naming Conventions
- MUST: Use
snake_case for all tables, columns, and constraints.
- MUST: Prefix domain tables (e.g.,
crr_orders, iam_users, audit_ffm_batches).
- MUST: Name indexes
idx_{table}_{column}, UKs uk_{table}_{column}, FKs fk_{table}_{ref}, Checks chk_{table}_{column}.
2. Standard Columns (Boilerplate)
- MUST: Include
id SERIAL PRIMARY KEY (or BIGSERIAL for partitioned/high-volume).
- MUST: Include
tenant_id INTEGER NOT NULL for multi-tenancy.
- MUST: Include
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() and updated_at TIMESTAMPTZ.
- MUST: Include
created_by INTEGER and updated_by INTEGER (FK to users).
- MUST: Include
archived BOOLEAN NOT NULL DEFAULT FALSE and deleted_at TIMESTAMPTZ for soft-deletes.
3. Data Types
- MUST: Use
TIMESTAMPTZ for all timestamps. NEVER use TIMESTAMP without timezone.
- MUST: Use
NUMERIC(15, 4) for financial amounts, paired with a VARCHAR(10) currency code.
- MUST: Use
JSONB DEFAULT '{}' for flexible metadata, never JSON or TEXT.
4. Constraints & Indexes
- MUST: Define Foreign Keys, Unique Constraints, and Check Constraints explicitly via
ALTER TABLE.
- MUST: Add
CHECK constraints for numeric bounds (e.g., quantity >= 0).
- MUST: Create a composite index on
(archived, deleted_at) for all soft-deletable tables.
- MUST: Index all Foreign Key columns and frequent query filters.
5. Partitioning (High-Volume/Audit Tables)
- MUST: Use Declarative Range Partitioning (
PARTITION BY RANGE (created_at)) for audit trails and history tables.
- MUST: Include the partition key in the Primary Key (
PRIMARY KEY (id, created_at)).
- MUST: Pre-create monthly partitions (
_YYYYMM) and a DEFAULT partition.
6. Documentation (Zero Exceptions)
- MUST: Add
COMMENT ON TABLE immediately after table creation.
- MUST: Add
COMMENT ON COLUMN for every single column explaining its purpose, especially JSONB, timestamps, and foreign keys.
Examples (good vs. bad, with realistic code or output)
Bad:
CREATE TABLE orders (
id INT PRIMARY KEY,
created_at TIMESTAMP,
amount FLOAT,
metadata TEXT
);
Good:
CREATE TABLE crr_orders (
id SERIAL PRIMARY KEY,
tenant_id INTEGER NOT NULL,
amount NUMERIC(15, 4) NOT NULL DEFAULT 0,
currency VARCHAR(10) DEFAULT 'USD',
metadata JSONB DEFAULT '{}',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ,
archived BOOLEAN NOT NULL DEFAULT FALSE,
deleted_at TIMESTAMPTZ
);
ALTER TABLE crr_orders ADD CONSTRAINT chk_crr_orders_amount CHECK (amount >= 0);
CREATE INDEX idx_crr_orders_archived_deleted ON crr_orders(archived, deleted_at);
COMMENT ON TABLE crr_orders IS 'Delivery orders for last-mile logistics';
COMMENT ON COLUMN crr_orders.metadata IS 'Additional metadata for the order, stored as JSONB';
COMMENT ON COLUMN crr_orders.deleted_at IS 'Soft delete timestamp; deleted orders are not visible';
Scope handling
- Prompt: "Add a
carrier_id column to crr_orders only."
- Good: New
V0xx__add_carrier_id_to_crr_orders.sql with the column, FK via ALTER TABLE, index and COMMENT ON COLUMN; notes other tables lacking comments.
- Bad: Edits the original
V001 script and adds comments/indexes to unrelated tables.
Checklist (verifiable, copy-pasteable)
Common Pitfalls
- Using
TIMESTAMPT instead of TIMESTAMPTZ, causing timezone shift bugs across regions.
- Forgetting to include
created_at in the Primary Key of a partitioned table (PostgreSQL requirement).
- Missing
COMMENT ON for JSONB columns, leaving future devs guessing the internal schema.
- Using
FLOAT or REAL for currency, leading to precision loss.
- Editing an applied migration or touching neighbouring tables when only one change was requested.
References (official docs, standards)
1---2name: database-postgres-migrations3description: 'Standardizes PostgreSQL migration scripts (Flyway/Liquibase) with strict schema design, partitioning, and mandatory documentation. Trigger: "write postgres migration", "create sql script", "design postgres schema", "flyway migration", "add COMMENT ON".'4metadata:5 source: https://skillmd.com/skills/pnguyen215/database-postgres-migrations6 category: database7 tags: "postgresql, migrations, flyway, liquibase, partitioning"8---910# PostgreSQL Migration & Schema Standards1112## Purpose1314Defines the strict enterprise standards for writing PostgreSQL database migration scripts, ensuring multi-tenancy, soft-deletes, auditability, performance (partitioning/indexes), and mandatory documentation via `COMMENT ON`. Responsibility boundary: authors or edits migration scripts only; does NOT run migrations against any database and does NOT edit already-applied migrations.1516## When to Use / When NOT to Use1718- **Use**: Writing new Flyway/Liquibase migration scripts (`VXXX__name.sql`), designing PostgreSQL tables, adding columns to existing tables.19- **NOT**: NoSQL databases, simple SQLite prototypes, or ORM-only auto-migrations in production.20- **NOT**: Zero-downtime rollout and rollback strategy (use `database-migrations`).21- **NOT**: Query tuning or EXPLAIN analysis (use `database-query-optimization`).22- **NOT**: Conceptual schema modelling or ERDs (use `database-schema-design`).2324## Prerequisites & Assumptions2526- PostgreSQL 12+ (for declarative partitioning and JSONB features).27- Migration tool (Flyway, Liquibase, or golang-migrate) managing versioned SQL files.2829### Scope & Context Resolution3031- **Supported scopes**: project/repository, migration directory, migration script file, table, column, index/constraint. Default when none is given: the single new migration script for the table(s) the user names.32- **Rule 1 - Explicit context in the prompt**: the user's stated requirements, constraints, versions, targets and scope are authoritative. Apply this skill strictly within them. MUST NOT add assumptions or expand beyond them. If a user instruction conflicts with a skill rule, follow the user and state the deviation in one line, EXCEPT security/data-loss rules(never drop data or edit applied migrations without confirmation), which stay mandatory: flag the conflict instead.33- **Rule 2 - No extra context**: use this skill's Purpose, workflow and rules as the sole context, at the default scope. MUST NOT import unrelated requirements or assumptions.34- **Rule 3 - Explicit scope**: operate ONLY inside the named scope. Out-of-scope files may be READ as evidence but MUST NOT be modified; report out-of-scope observations as notes, never as changes. Widening scope requires explicit user approval.35- **Mutation boundary**: edits limited to new or explicitly named migration files; MUST NOT modify applied migrations, execute SQL against a database, or alter application code.3637## Step-by-Step Workflow38391. **Resolve scope and context**: apply the section above; state the resolved scope and mutation boundary in one line at the start of the output.402. Create a new migration file with sequential versioning (e.g., `V001__add_carrier_domain.sql`).413. Define tables with standard audit, multi-tenant, and soft-delete columns.424. Add explicit constraints (PK, UK, FK, CHECK) using `ALTER TABLE` after creation.435. Create targeted indexes for performance and soft-delete filtering.446. Apply declarative partitioning for high-volume/audit tables.457. Write `COMMENT ON TABLE` and `COMMENT ON COLUMN` for _every single entity_.4647## Enterprise Rules & Standards (MUST / SHOULD / MUST NOT)4849### 0. Scope5051- **MUST**: Stay within the resolved scope; MUST NOT modify or expand beyond it without explicit user approval.52- **MUST NOT**: Alter tables, columns or data outside the named scope, or edit already-applied migration files (add a new versioned script instead).5354### 1. Naming Conventions5556- **MUST**: Use `snake_case` for all tables, columns, and constraints.57- **MUST**: Prefix domain tables (e.g., `crr_orders`, `iam_users`, `audit_ffm_batches`).58- **MUST**: Name indexes `idx_{table}_{column}`, UKs `uk_{table}_{column}`, FKs `fk_{table}_{ref}`, Checks `chk_{table}_{column}`.5960### 2. Standard Columns (Boilerplate)6162- **MUST**: Include `id SERIAL PRIMARY KEY` (or `BIGSERIAL` for partitioned/high-volume).63- **MUST**: Include `tenant_id INTEGER NOT NULL` for multi-tenancy.64- **MUST**: Include `created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()` and `updated_at TIMESTAMPTZ`.65- **MUST**: Include `created_by INTEGER` and `updated_by INTEGER` (FK to users).66- **MUST**: Include `archived BOOLEAN NOT NULL DEFAULT FALSE` and `deleted_at TIMESTAMPTZ` for soft-deletes.6768### 3. Data Types6970- **MUST**: Use `TIMESTAMPTZ` for all timestamps. NEVER use `TIMESTAMP` without timezone.71- **MUST**: Use `NUMERIC(15, 4)` for financial amounts, paired with a `VARCHAR(10)` currency code.72- **MUST**: Use `JSONB DEFAULT '{}'` for flexible metadata, never `JSON` or `TEXT`.7374### 4. Constraints & Indexes7576- **MUST**: Define Foreign Keys, Unique Constraints, and Check Constraints explicitly via `ALTER TABLE`.77- **MUST**: Add `CHECK` constraints for numeric bounds (e.g., `quantity >= 0`).78- **MUST**: Create a composite index on `(archived, deleted_at)` for all soft-deletable tables.79- **MUST**: Index all Foreign Key columns and frequent query filters.8081### 5. Partitioning (High-Volume/Audit Tables)8283- **MUST**: Use Declarative Range Partitioning (`PARTITION BY RANGE (created_at)`) for audit trails and history tables.84- **MUST**: Include the partition key in the Primary Key (`PRIMARY KEY (id, created_at)`).85- **MUST**: Pre-create monthly partitions (`_YYYYMM`) and a `DEFAULT` partition.8687### 6. Documentation (Zero Exceptions)8889- **MUST**: Add `COMMENT ON TABLE` immediately after table creation.90- **MUST**: Add `COMMENT ON COLUMN` for _every single column_ explaining its purpose, especially JSONB, timestamps, and foreign keys.9192## Examples (good vs. bad, with realistic code or output)9394**Bad**:9596```sql97CREATE TABLE orders (98 id INT PRIMARY KEY,99 created_at TIMESTAMP,100 amount FLOAT,101 metadata TEXT102);103```104105**Good**:106107```sql108CREATE TABLE crr_orders (109 id SERIAL PRIMARY KEY,110 tenant_id INTEGER NOT NULL,111 amount NUMERIC(15, 4) NOT NULL DEFAULT 0,112 currency VARCHAR(10) DEFAULT 'USD',113 metadata JSONB DEFAULT '{}',114 created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),115 updated_at TIMESTAMPTZ,116 archived BOOLEAN NOT NULL DEFAULT FALSE,117 deleted_at TIMESTAMPTZ118);119ALTER TABLE crr_orders ADD CONSTRAINT chk_crr_orders_amount CHECK (amount >= 0);120CREATE INDEX idx_crr_orders_archived_deleted ON crr_orders(archived, deleted_at);121COMMENT ON TABLE crr_orders IS 'Delivery orders for last-mile logistics';122COMMENT ON COLUMN crr_orders.metadata IS 'Additional metadata for the order, stored as JSONB';123COMMENT ON COLUMN crr_orders.deleted_at IS 'Soft delete timestamp; deleted orders are not visible';124```125126**Scope handling**127128- **Prompt**: "Add a `carrier_id` column to `crr_orders` only."129- **Good**: New `V0xx__add_carrier_id_to_crr_orders.sql` with the column, FK via `ALTER TABLE`, index and `COMMENT ON COLUMN`; notes other tables lacking comments.130- **Bad**: Edits the original `V001` script and adds comments/indexes to unrelated tables.131132## Checklist (verifiable, copy-pasteable)133134- [ ] Scope and context resolved and stated.135- [ ] No changes outside the resolved scope.136- [ ] File named correctly (`VXXX__description.sql`).137- [ ] Standard audit/tenant/soft-delete columns present.138- [ ] `TIMESTAMPTZ` and `NUMERIC` used correctly.139- [ ] Constraints added via `ALTER TABLE`.140- [ ] Indexes created for FKs and `(archived, deleted_at)`.141- [ ] `COMMENT ON` applied to Table and ALL Columns.142- [ ] Partitioning applied if table is high-volume/audit.143144## Common Pitfalls145146- Using `TIMESTAMPT` instead of `TIMESTAMPTZ`, causing timezone shift bugs across regions.147- Forgetting to include `created_at` in the Primary Key of a partitioned table (PostgreSQL requirement).148- Missing `COMMENT ON` for JSONB columns, leaving future devs guessing the internal schema.149- Using `FLOAT` or `REAL` for currency, leading to precision loss.150- Editing an applied migration or touching neighbouring tables when only one change was requested.151152## References (official docs, standards)153154- [PostgreSQL Declarative Partitioning](https://www.postgresql.org/docs/current/ddl-partitioning.html)155- [Flyway SQL Migration Syntax](https://flywaydb.org/documentation/concepts/migrations.html#sql-based-migrations)