Skip to content

Pattern 4 — Native Enums, Timestamps & Declarative Defaults#

← Assimilation hub · Live test fixture: cases/04_types_defaults_and_constraints/

Legacy PostgreSQL tables frequently mix native CREATE TYPE ... AS ENUM, timezone-naive TIMESTAMP WITHOUT TIME ZONE, literal server defaults (DEFAULT 0, DEFAULT 'none'), and unvalidated (NOT VALID) check constraints.

What this pattern demonstrates#

  • Native PostgreSQL ENUMs: Bound cleanly via Annotated[str, pg.CustomType(pg_type="ticket_priority")] with zero forced column rewrites (if you later want to migrate a native ENUM to a pg.TypeTable, you can do it as a separate, controlled migration).
  • Naive vs. aware timestamps: TIMESTAMP WITHOUT TIME ZONE maps to pg.Timestamp, keeping TIMESTAMPTZ reserved for plain datetime.
  • Declarative server defaults: DEFAULT 0 and DEFAULT 'none' scaffold directly to bare Python defaults (pg.col(default=0) and pg.col(default="none")), emitting both the Python dataclass default and the PostgreSQL DEFAULT clause — never raw SQL strings.
  • Unvalidated constraints: CHECK (retries >= 0) NOT VALID is automatically scheduled for online VALIDATE CONSTRAINT in Phase 4 (SHARE UPDATE EXCLUSIVE lock, non-blocking for reads/writes).

Before & After — Table-by-Table Comparison#

tickets → ticket
id → ticket_id
CREATE TYPE ticket_priority AS ENUM ('low', 'high');

CREATE TABLE tickets (
    id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    title VARCHAR(120) NOT NULL,
    priority ticket_priority NOT NULL,
    created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT now(),
    retries INTEGER NOT NULL DEFAULT 0,
    note TEXT DEFAULT 'none'
);

ALTER TABLE tickets
    ADD CONSTRAINT chk_retries CHECK (retries >= 0) NOT VALID;
class Ticket(pg.Table):
    ticket_id: pg.Col[int] = pg.pk(default=pg.identity())
    title: pg.Col[str] = pg.col(max_len=120)
    priority: pg.Col[Annotated[str, pg.CustomType(pg_type='ticket_priority')]]
    created_at: pg.Col[pg.Timestamp] = pg.col(default=pg.now())
    retries: pg.Col[pg.Int4] = pg.col(default=0)
    note: pg.Col[str | None] = pg.col(default='none')

    @classmethod
    def __constraints__(cls) -> tuple[pg.TableConstraint, ...]:
        return (
            pg.Check(cls.retries >= 0),
        )
Generated by pgdorm scaffold · tests/integration/migrations/onboarding/cases/04_types_defaults_and_constraints/__captured__/scaffold.py.txt
from typing import Annotated

import pgdorm as pg
import pgdorm.migrate as pgm


class Ticket(pg.Table):
    ticket_id: pg.Col[int] = pg.pk(default=pg.identity())
    title: pg.Col[str] = pg.col(max_len=120)
    priority: pg.Col[Annotated[str, pg.CustomType(pg_type='ticket_priority')]]
    created_at: pg.Col[pg.Timestamp] = pg.col(default=pg.now())
    retries: pg.Col[pg.Int4] = pg.col(default=0)
    note: pg.Col[str | None] = pg.col(default='none')

    @classmethod
    def __constraints__(cls) -> tuple[pg.TableConstraint, ...]:
        return (
            pg.Check(cls.retries >= 0),
        )


ADOPTION_MAP = pgm.AdoptionMap(
    tables={
        'tickets': pgm.TableMapping(target='ticket', columns={'id': 'ticket_id'}, pk_strategy=pgm.enums.PkStrategy.RENAME),
    },
)


APP = pgm.MigrationApp(tables=(Ticket,))
tests/integration/migrations/onboarding/cases/04_types_defaults_and_constraints/schema.sql
CREATE TYPE ticket_priority AS ENUM ('low', 'high');

CREATE TABLE tickets (
    id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    title VARCHAR(120) NOT NULL,
    priority ticket_priority NOT NULL,
    created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT now(),
    retries INTEGER NOT NULL DEFAULT 0,
    note TEXT DEFAULT 'none'
);

ALTER TABLE tickets
    ADD CONSTRAINT chk_retries CHECK (retries >= 0) NOT VALID;
tests/integration/migrations/onboarding/cases/04_types_defaults_and_constraints/seed.sql
INSERT INTO tickets (title, priority, retries) VALUES ('Fix login', 'high', 1), ('Docs', 'low', 0);

Live audit#

migratable · exit 0
3 migration2 info
  • MIGRATIONUNVALIDATED_CONSTRAINT
    tickets · chk_retries
    CHECK 'chk_retries' on 'tickets' is NOT VALID.
  • MIGRATIONTABLE_NAME_PLURAL
    tickets
    Table 'tickets' appears plural; assimilate to singular snake_case.
  • MIGRATIONPK_NAME_MISMATCH
    tickets · id
    Table 'tickets' PK is 'id' instead of 'tickets_id'.
  • INFOTIMESTAMP_WITHOUT_TZ
    tickets · created_at
    Column tickets.created_at uses TIMESTAMP WITHOUT TIME ZONE.
  • INFOPG_NATIVE_ENUM
    tickets · priority
    Column tickets.priority uses native PG enum 'ticket_priority' (low, high).
Inspect raw machine-readable audit JSON (tests/integration/migrations/onboarding/cases/04_types_defaults_and_constraints/captured/audit.json)
{
  "counts": {
    "blocker": 0,
    "info": 2,
    "migration_required": 3,
    "unmanaged": 0
  },
  "findings": [
    {
      "auto_fixable": true,
      "category": "constraints",
      "code": "UNVALIDATED_CONSTRAINT",
      "doc_anchor": "constraints-and-indexes",
      "message": "CHECK 'chk_retries' on 'tickets' is NOT VALID.",
      "object_kind": "constraint",
      "object_name": "chk_retries",
      "severity": "migration_required",
      "suggestion": "Assimilation schedules online `VALIDATE CONSTRAINT` under SHARE UPDATE EXCLUSIVE.",
      "table": "tickets"
    },
    {
      "auto_fixable": true,
      "category": "naming",
      "code": "TABLE_NAME_PLURAL",
      "doc_anchor": "table-naming",
      "message": "Table 'tickets' appears plural; assimilate to singular snake_case.",
      "object_kind": "table",
      "object_name": "tickets",
      "severity": "migration_required",
      "suggestion": "Rename table to singular snake_case via AdoptionMap.",
      "table": "tickets"
    },
    {
      "auto_fixable": true,
      "category": "primary_key",
      "code": "PK_NAME_MISMATCH",
      "doc_anchor": "primary-keys-and-serials",
      "message": "Table 'tickets' PK is 'id' instead of 'tickets_id'.",
      "object_kind": "primary_key",
      "object_name": "id",
      "severity": "migration_required",
      "suggestion": "Rename single int/UUID PK to `<table_name>_id`, or add surrogate PK.",
      "table": "tickets"
    },
    {
      "auto_fixable": false,
      "category": "types",
      "code": "TIMESTAMP_WITHOUT_TZ",
      "doc_anchor": "column-types",
      "message": "Column tickets.created_at uses TIMESTAMP WITHOUT TIME ZONE.",
      "object_kind": "column",
      "object_name": "created_at",
      "severity": "info",
      "suggestion": "Scaffold emits `pg.Col[pg.Timestamp]` automatically.",
      "table": "tickets"
    },
    {
      "auto_fixable": true,
      "category": "types",
      "code": "PG_NATIVE_ENUM",
      "doc_anchor": "column-types",
      "message": "Column tickets.priority uses native PG enum 'ticket_priority' (low, high).",
      "object_kind": "column",
      "object_name": "priority",
      "severity": "info",
      "suggestion": "Use `mode='assimilate'` to migrate PG enums into seeded `IntEnum` `pg.TypeTable`s.",
      "table": "tickets"
    }
  ],
  "ignored_tables": [],
  "migratable": true,
  "schema": "public",
  "table_count": 1,
  "type_table_candidates": [],
  "unmanaged_objects": {
    "extensions": [],
    "indexes": [],
    "rls_policies": [],
    "routines": [],
    "triggers": [],
    "views": []
  },
  "workflow_steps": [
    {
      "detail": "Run `pgdorm scaffold` and `pgdorm adopt-plan` (use `execute_plan_tx` inside a psycopg3 transaction when recreating views/functions atomically).",
      "order": 1,
      "phase": "ddl",
      "summary": "Scaffold models, review AdoptionMap, and execute transactional DDL"
    },
    {
      "detail": "Run `finalize_external()` or `pgdorm upgrade`, then verify `pgdorm drift`.",
      "order": 2,
      "phase": "post_commit",
      "summary": "Run CONCURRENTLY indexes, VALIDATE constraints, and record ledger"
    }
  ]
}

Compiled assimilation SQL#

Generated by pgdorm adopt-plan --format sql · tests/integration/migrations/onboarding/cases/04_types_defaults_and_constraints/__captured__/plan.sql
-- pgdorm Assimilation Plan: 0001_assimilate (04_types_defaults_and_constraints)
-- Checksum: 0f204a390dc4e0c50fcc182e713f0291f9e98f9f05e9a197edcf0f0bfcb2129c
-- Ignored tables: (none)
-- Preserved unmanaged objects: 0

-- ===========================================================================
-- PHASE 2 (TRANSACTIONAL DDL): Atomic pgdorm compiled schema assimilation
-- ===========================================================================
BEGIN;

-- (Optional PRE-DDL hook: DROP blocking views/matviews here)

-- [1] (ACCESS EXCLUSIVE) Rename table tickets -> ticket
ALTER TABLE "public"."tickets" RENAME TO "ticket";
-- [2] (ACCESS EXCLUSIVE) Rename column ticket.id -> ticket_id
ALTER TABLE "public"."ticket" RENAME COLUMN "id" TO "ticket_id";

COMMIT;

-- ===========================================================================
-- PHASE 4 (POST-COMMIT ONLINE / AUTOCOMMIT): CONCURRENTLY & VALIDATE steps
-- Run outside any BEGIN ... COMMIT block (or call pgm.finalize_external()).
-- ===========================================================================
-- [post-1] (SHARE UPDATE EXCLUSIVE) Validate constraint chk_retries on ticket
ALTER TABLE "public"."ticket" VALIDATE CONSTRAINT "chk_retries";