Skip to content

Chapter 7 — The Foreman's Toolkit (CLI & CI)#

Act III · Chapter 7 Year 2 · Autumn · 15:00 6 min readDifficulty 2 of 5

Drive migrations from the pgdorm CLI in CI/CD with --json plans, exit-code-2 drift alarms, and static ReadPool checks.

pgdorm doctorplan / render / syncpgdorm drift (exit 2)--json & --pool-modeReadPool static guard
▶ Run it yourself · examples/103_mig_cli_and_ci_gates.py
Year 2 · Autumn, 15:00. Moby's test lab is humming with fresh containers. Maya wants every deploy pipeline — and every AI coding agent — to drive migrations from a single deterministic CLI.

Year 2 · Autumn, 15:00. Moby's test lab is humming with fresh containers. Maya wants every deploy pipeline — and every AI coding agent — to drive migrations from a single deterministic CLI.

Moby: Give me a [tool.pgdorm] section in pyproject.toml, and CI will run doctor, plan --json, upgrade, and a drift alarm automatically on every commit!

Maya: Wait — what exit code does pgdorm drift return when someone edits production behind our back?

Ferris: Exit code 2 — distinct from 0 (clean), 1 (error), and 3 (audit-schema blockers), and every single subcommand speaks --json!

The mission#

Interactive Python helpers are great inside scripts and tests, while production CI/CD pipelines and AI coding agents want a scriptable command-line interface with deterministic exit codes and --json output. In this renovation, Maya wires up the full pgdorm CLI lifecycle:

  1. configure [tool.pgdorm] in pyproject.toml once (app, dsn, ignore_tables),
  2. run pgdorm doctor --write-probe --json to verify PostgreSQL wire & write capabilities before deploying,
  3. preview diffs (plan --json), generate code-defined migrations (render), apply (sync / upgrade), and inspect _pgdorm (status, history),
  4. enforce CI drift gates with pgdorm drift (exit 0 clean, exit 2 drifted, exit 0 when isolated with --ignore-table),
  5. lock out accidental ReadPool migrations at type-check time.

The Panda's plan

Parse human-formatted CLI output with brittle regexes in bash scripts, ignore exit codes, and discover three weeks after deploy that someone ran a manual CREATE TABLE in production.

1. Zero-boilerplate configuration (pyproject.toml + MigrationApp)#

Export one MigrationApp constant from your database module:

examples/103_mig_cli_and_ci_gates.py · ShiftRoster
class ShiftRoster(pg.Table):
    shift_roster_id: pg.Col[int] = pg.pk(default=pg.identity())
    staff_name: pg.Col[str] = pg.col()
    wing_code: pg.Col[str] = pg.col()
examples/103_mig_cli_and_ci_gates.py · build_app
def build_app() -> pgm.MigrationApp:
    return pgm.MigrationApp(tables=(ShiftRoster,))

Then point [tool.pgdorm] in pyproject.toml at it so every CLI subcommand inherits your app, DSN fallback, and ignored tables automatically:

[tool.pgdorm]
app = "myapp.db:APP"
ignore_tables = ["unmanaged_note"]

2. Live CLI lifecycle (doctor → plan → render → sync → status → drift)#

Every pgdorm CLI command is also callable in-process via await pgm.run_cli(argv) (powering python -m pgdorm and the pgdorm console entry point). Global flags (--dsn, --schema, --app, --config, --ignore-table, --pool-mode, --json) precede the subcommand; subcommand flags follow it:

examples/103_mig_cli_and_ci_gates.py · run_cli_lifecycle
async def run_cli_lifecycle(pool: pg.Pool) -> None:
    dsn = os.environ.get("DATABASE_URL", DATABASE_URL)
    (schema_name,) = await pool.one(pg.select_expr(pg.func("current_schema")))
    assert isinstance(schema_name, str)
    common = ("--dsn", dsn, "--schema", schema_name, "--app", f"{__name__}:APP")

    # 1. Preflight PostgreSQL capability probe (works without --app!).
    rc_doc, out_doc = await _cli("--dsn", dsn, "--json", "doctor", "--write-probe")
    doc = json.loads(out_doc)
    print(f"doctor rc={rc_doc} ok={doc['ok']} major>={doc['server_version_num'] // 10000}")
    # => doctor rc=0 ok=True major>=18

    # 2. Dry-run JSON plan + render a reviewable Python Migration constant.
    rc_plan, out_plan = await _cli(*common, "--json", "plan", "--name", "init_roster")
    plan_json = json.loads(out_plan)
    rc_ren, out_ren = await _cli(
        *common, "render", "--version", "0001", "--name", "init_roster", "--var-name", "M_0001"
    )
    ren_head = next(ln for ln in out_ren.splitlines() if ln.startswith("M_0001"))
    print(f"plan rc={rc_plan} steps={len(plan_json['steps'])} | render rc={rc_ren} ({ren_head})")
    # => plan rc=0 steps=1 | render rc=0 (M_0001 = pgm.Migration()

    # 3. Sync via CLI, then inspect status + history in --json mode.
    rc_sync, out_sync = await _cli(*common, "--json", "sync", "--name", "init_roster")
    sync_json = json.loads(out_sync)
    rc_stat, out_stat = await _cli(*common, "--json", "status")
    stat_json = json.loads(out_stat)
    rc_hist, out_hist = await _cli(*common, "--json", "history")
    hist_json = json.loads(out_hist)
    assert rc_stat == 0 and rc_hist == 0
    print(
        f"sync rc={rc_sync} status={sync_json['status']} | "
        f"in_sync={stat_json['in_sync']} pending={stat_json['pending_ops']} | "
        f"history={len(hist_json)}"
    )
    # => sync rc=0 status=APPLIED | in_sync=True pending=0 | history=1

    # 4. CI drift gate: exit 0 when clean, exit 2 the instant out-of-band DDL appears!
    rc_clean, _ = await _cli(*common, "drift")
    await pool.create_all(UnmanagedNote)
    rc_drifted, _ = await _cli(*common, "drift")
    rc_ignored, _ = await _cli(*common, "--ignore-table", "unmanaged_note", "drift")
    print(f"drift exit codes: clean={rc_clean} drifted={rc_drifted} ignored={rc_ignored}")
    # => drift exit codes: clean=0 drifted=2 ignored=0

Exit code contract for CI & agents

Exit code Meaning
0 Clean / succeeded (no drift, or audit-schema found zero blockers)
1 Configuration error, missing DSN/--app, failed doctor probe, or MigrationError
2 pgdorm drift detected live pg_catalog divergence from _pgdorm
3 pgdorm audit-schema found blocking legacy patterns (migratable == false)

3. Static safety in CI: ReadPool rejected before tests even run#

Because migration functions accept Pool (never ReadPool), a strict type checker catches anyone trying to run DDL against a read-only replica at static analysis time:

tests/integration/migrations/test_versioned_and_evolution.py · test_migration_functions_reject_read_pool_statically_in_ty
def test_migration_functions_reject_read_pool_statically_in_ty(tmp_path: Path) -> None:
    bad = tmp_path / "bad_migrator.py"
    bad.write_text(
        "\n".join(
            [
                "import pgdorm as pg",
                "import pgdorm.migrate as pgm",
                "from tests.integration.migrations.schema import Account",
                "",
                "async def bad(ro: pg.ReadPool) -> None:",
                "    await pgm.sync_schema(ro, (Account,))",
                "    await pgm.upgrade_schema(ro, ())",
            ]
        ),
        encoding="utf-8",
    )
    proc = subprocess.run(
        [
            sys.executable,
            "-m",
            "ty",
            "check",
            "--extra-search-path",
            str(_REPO_ROOT / "python"),
            "--extra-search-path",
            str(_REPO_ROOT),
            str(bad),
        ],
        capture_output=True,
        text=True,
        check=False,
    )
    assert proc.returncode != 0
    assert "invalid-argument-type" in (proc.stdout + proc.stderr)

What PostgreSQL actually received#

🔭 What PostgreSQL received: 4 statements in 3 round trips (captured live on PostgreSQL)
-- ── round trip 1 ──
SELECT current_schema();
-- → 1 row

-- ── round trip 2 · 2 statements pipelined ──
BEGIN;
CREATE TABLE IF NOT EXISTS "unmanaged_note" ("unmanaged_note_id" BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL, "body" TEXT NOT NULL, CONSTRAINT "pk_nkyqdvrr" PRIMARY KEY ("unmanaged_note_id"));

-- ── round trip 3 ──
COMMIT;

Shift report

  • Probed live PostgreSQL wire & write capabilities with pgdorm doctor --write-probe --json
  • Executed plan, render, sync, status, and history in machine-readable --json mode
  • Enforced CI drift gates (exit 0 clean, exit 2 drifted, --ignore-table isolation)
  • Verified the type checker rejects ReadPool in migration APIs

Try it yourself

Run uv run --no-sync pgdorm --dsn "$DATABASE_URL" --pool-mode transaction --json doctor --write-probe against PgBouncer — notice --pool-mode transaction skips session startup options cleanly! See the full flag table in the CLI Reference.

Go deeper: tests/integration/migrations/test_cli.py · tests/integration/migrations/test_versioned_and_evolution.py (live PostgreSQL test suites & snapshots)

Sticky note from Management

"CI is airtight! One last renovation for Year 2: we just bought the legacy hostel next door — plural tables, BIGSERIAL PKs, an alembic_version table, and a live SQL view. Bring it cleanly under pgdorm!"