Skip to content

feat(sql): @effect/sql-pg client, Effect Migrator and test layer - #83

Merged
allisonmahmood merged 2 commits into
mainfrom
feat/sql-package
Aug 29, 2026
Merged

allisonmahmood merged 2 commits into
mainfrom
feat/sql-package

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

packages/db hand-rolls the Postgres client, the migration runner and a text-id schema_migrations ledger. The Effect port wants those on @effect/sql-pg and Effect's Migrator, owned by a package that holds no tables, so auth and patches can each bring their own migrations.

New packages/sql: PgClient from DATABASE_URL (a Redacted Config), migrate(record) over Migrator.fromRecord composing per-package records into one global integer id sequence, and @patchy/sql/testing — a Layer.unwrap + acquireRelease test layer so an it.layer block gets a fresh migrated database dropped with the layer. Today's SCHEMA_MIGRATIONS run unchanged through sql.unsafe; packages/db keeps only a migrateDatabase Promise seam, which the server, the dev runner and the vitest template migrate through. The driver's own runner, advisory lock and text ledger are deleted, and the language-service warnings are error for the new package.

Two behaviour changes from today:

  • Ledger: schema_migrations is now Effect's (migration_id integer, name, created_at) rather than text ids; no production database exists, so nothing is renamed or marked applied (a dev instance needs pnpm dev reset).
  • Transactions: all pending steps run in one transaction under ACCESS EXCLUSIVE and a failing step rolls the whole batch back, instead of one transaction per step. Steps lost their IF NOT EXISTS guards; the ledger is the guard.

Also dropped the pnpm db:migrate script: the server migrates on startup, before it listens.

Closes #72

Built by Claude Fable 5 via Claude Code.

packages/db hand-rolled the Postgres client, the migration runner and a
text-id ledger. A new packages/sql owns the PgClient layer from
DATABASE_URL, Effect's Migrator over fromRecord (one global integer id
sequence, duplicates fail, all pending steps in one transaction under
ACCESS EXCLUSIVE) and a migrated-database test layer for it.layer.

Today's SCHEMA_MIGRATIONS run unchanged through sql.unsafe, without the
IF NOT EXISTS guards: the schema_migrations ledger is the guard now.
packages/db keeps a thin migrateDatabase seam; the server, the dev runner
and the vitest template migrate through it, and the driver's own runner,
advisory lock and text ledger are gone.
@github-actions github-actions Bot added area:server Touches the server area area:ci CI, shared testing infrastructure, development scripts and tooling area:docs Touches the docs area size:l 501-1,000 changed lines labels Aug 29, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Code review — PR 83 vs issue 72

Reviewed origin/main...ddc9210 (feat/sql-package). Spec source is #72. Axes are kept separate on purpose: a change can follow every convention and still miss the ticket, or implement the ticket and still fight the Effect rules.


Intent vs delivery

#72 asked for a package that owns the Postgres client and Effect’s Migrator, not tables. Production PgClient from a Redacted DATABASE_URL, Migrator.make({}) + fromRecord over one global integer id sequence, a migrated it.layer database, today’s SCHEMA_MIGRATIONS through sql.unsafe behind a Promise seam, and the hand-rolled runner / text ledger deleted.

That is what landed. packages/sql/src/index.ts is the client + migrate(record). Query code stays in packages/db on pg, which is the Done-when line (“keeps only the query code the auth and patches tickets will take”), not a miss. The two named behaviour changes (integer ledger; one transaction under ACCESS EXCLUSIVE, no IF NOT EXISTS) are real library defaults, not comments pretending to be config.

Two places the ticket text and the PR drift:

  1. Neon prepare: false knob — named in Do, not in the diff. This RC’s PgClientConfig has no prepare field (@effect/sql-pg is pg, not postgres.js), so a reserved Config would have been a dead switch. Still a named ask with no acknowledgement on the PR.
  2. pnpm db:migrate is gone; the server migrates on startup. Done-when says the server migrates through the Migrator; deleting the CLI is extra. SELF_HOSTING.md still says create the schema “before starting the server” while the snippet starts the long-lived process.

Standards

No hard Effect-service violations.

  • packages/sql/src/index.ts: composes PgClient / Migrator; no invented Context.Service. Helpers do not need the errors → tag → make → layer shape. Namespace Effect imports are correct. LEDGER_TABLE, Migrations, layer / layerFromUrl, Migrator.make({}) match CONTEXT.md and the port shapes.
  • packages/db/src/migrate.ts: Effect.runPromise + Sql.layerFromUrl is the documented migration seam (ported ↔ unported).
  • packages/sql/src/testing.ts: @effect/vitest Layer.unwrap + acquireRelease. Fine.
  • Package existence: port-map override — do not flag the one-consumer-module rule.

Soft (named whole-package imports) — packages/db/src/migrate.ts:

import * as Sql from "@patchy/sql";

The service-conventions skill prefers named imports for whole packages (e.g. @patchy/api); namespace is for service modules (tag / make / layer). Prefer { migrate, layerFromUrl, type Migrations }. Judgement; only consumer. (A second pass treating @patchy/sql as a layer-shaped capability surface can keep the namespace — callers use Sql.migrate / Sql.layerFromUrl.)

Smells (all judgement)

  • Duplicated Code: identical @effect/language-service diagnosticSeverity map in packages/sql/tsconfig.json vs scripts/dev/tsconfig.json (comment: keep in sync). Tooling config, not runtime.
  • Speculative Generality (weak): exported Config layer is unused in-repo this PR; port-map / README intend it as the production client — suppress if treated as package surface.

No HTML/UI. Pre-port packages/db Promise/pg left alone. Vocabulary Migration / Ledger / Migration seam aligned.


Spec

(a) Missing / partial

  • prepare: false Neon knob — Do: *"PgClient.layer from a Config slice (DATABASE_URL as Redacted; a prepare: false knob reserved for the Neon pooler)"*. Diff has only PgClient.layerConfig({ url: Config.redacted("DATABASE_URL") })/layerFromUrl; no prepareanywhere underpackages/sql. Current @effect/sql-pg PgClientConfig` also has no such field — still a named ask with no reserved knob.

(b) Scope creep

  • Drop pnpm db:migrate + server migrates on startup — Done when: "Server and tests migrate through Effect's Migrator"; interim only names "dev runner and vitest globalSetup". start.ts calling migrateDatabase satisfies Done when; deleting db:migrate / turbo task and rewriting docs/DEVELOPMENT.md / docs/SELF_HOSTING.md is PR “Also”, not in Do.

(c) Looks implemented but wrong

  • None material. ACCESS EXCLUSIVE: Do requires pending steps "in one transaction under ACCESS EXCLUSIVE". Code uses Migrator.make({}) with no lock option; Effect’s migrator defaults do LOCK TABLE … IN ACCESS EXCLUSIVE MODE inside sql.withTransaction — comments match behaviour, not vapour.

Verified OK

Migrator.make({}) + fromRecord (not PgMigrator); ledger schema_migrations; duplicate-id + empty-DB it.layer tests; IF NOT EXISTS gone; migrateDatabase seam used by supervisor / test/postgres.ts / start; db text runner deleted; pg Pool kept for query code per Done when; README decode convention; CONTEXT.md; language-service severities match scripts/dev/tsconfig.json; both behaviour changes named in the PR body.


Method

The method is right: a thin packages/sql facade over Effect’s client and Migrator, with a Promise seam in db, is the smallest model that matches the port map without inventing ownership sql does not have.

layer + one-line migrate(record) is the correct grain. A Sql Context.Service would be ceremony when PgClient already provides SqlClient. layerFromUrl is a justified second constructor: Config for the process, concrete URL for the seam and tests. Keeping SCHEMA_MIGRATIONS as the dual-driver array and adapting Postgres via Object.fromEntries → fromRecord is the right interim — moving the record into sql would steal table ownership. Dual client (@effect/sql-pg for migrate, pg Pool for queries) is correct for this ticket; query porting is auth/patches, not a half-cut here.

Fragile, not wrong: pnpm dev still migrates twice (supervisor, then server) — harmless via the ledger. The test admin path uses per-statement Effect pools instead of the slice’s shared Promise/pg helper; same layer shape, slightly more machinery. Operators lose an offline migrate script; for this product that was mostly a duplicate of start.

I would not have invented a Sql service or moved migrations into sql early.


YAGNI

This is the small model. Index is obvious; the dead runner stayed dead.

export const layer = PgClient.layerConfig({ url: Config.redacted("DATABASE_URL") });
export const layerFromUrl = (url: Redacted.Redacted<string>) => PgClient.layer({ url });
export const migrate = (migrations: Migrations) =>
  Migrator.make({})({ loader: Migrator.fromRecord(migrations), table: LEDGER_TABLE });

Real deletions made the system smaller: hand-rolled migrate(), advisory lock, text ledger, IF NOT EXISTS, db:migrate, Postgres adoption/probe SQL fixtures. sql.test.ts is three contract cases. The upload-contract rewrite is a consequence of killing the old runner (JSON ledger stays, Postgres harness helpers die) — net shrink, not churn.

Mild glue, not speculative: Migrations alias, LEDGER_TABLE, promoting SQL onto CONTEXT-MAP.md (issue asked for CONTEXT.md; the map line is the domain convention). Test ddl vs seam sql.unsafe is the same shape twice; sharing would be premature.

The missing Neon knob is an incomplete reservation, not a YAGNI win.


Tests

Done-when is covered: empty it.layer, duplicate id fails with MigrationError / kind: "Duplicates", batch rollback leaves no sprockets table.

Soft spots: remigrate asserts [] but does not re-read the ledger for “once”; rollback only checks Exit.isFailure, not the error tag.

Postgres tests that #72 allowed us to drop: pre-ledger adoption, IF NOT EXISTS probes, predecessor-never-ran DDL. JSON ledger/resume/adoption/guard-inversion still live under "JSON schema migrations" and json-db.test.ts.

Coverage that is gone and still useful for the interim: resume from a partly-applied Postgres ledger, and a happy-path pending step on an already-migrated database (only fail+rollback is covered). The vitest template is Migrator-built (test/postgres.ts → migrateDatabase), so the dual-driver contract suite still runs against the new schema.


Docs / operators

  • docs/SELF_HOSTING.md § Database migration still says create the schema “before starting the server”, then the snippet is pnpm --filter @patchy/server start — a long-lived process, not a one-shot migrator. Prose that migrate-on-start is safe is correct; the heading and the old one-shot contract are not.
  • CONTEXT-MAP.md lists SQL as a peer of Hosting/Publishing; docs/agents/domain.md still says “two halves” and ### Contexts only names Hosting / Publishing / Shared kernel. Keep packages/sql/CONTEXT.md; the map promotion wants the prose finished or demoted.
  • README decoding sample uses Schema.Date next to “timestamps → epoch milliseconds”, and SqlSchema does not itself Effect.die on SchemaError — that die is a caller convention, not implemented here.
  • PR body says a existing dev instance needs pnpm dev reset. docs/DEVELOPMENT.md documents the command, not the ledger-shape cutover.

Standards: 1 soft finding (namespace import of @patchy/sql; worst: that import). Spec: 1 missing + 1 scope (worst: no reserved prepare: false knob, even as a named deviation). Method and YAGNI are the right grain — I would not send this back for architecture.

Named imports from @patchy/sql at the seam, a happy-path pending-step
test and a defect check on the rollback case, the reserved Neon prepare
switch acknowledged in the README, and the self-hosting, domain and dev
docs brought in line with migrate-on-start and the SQL context.
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Thanks for the review. Addressed in 68d2396:

Fixed

  • prepare: false (spec, missing): named as a deviation in packages/sql/README.md — this RC's pg-backed PgClientConfig has no such field, so a Config switch would be dead; it lands with the deployment work.
  • import * as Sql from "@patchy/sql" → named imports at the seam, per the whole-package rule.
  • Tests: added the happy-path pending step on an already-migrated database (ledger reads [1, 2, 3]), and the rollback case now asserts a defect (Cause.hasDies), not just failure.
  • Docs: SELF_HOSTING.md no longer says "create the schema before starting the server"; docs/agents/domain.md prose and ### Contexts now include SQL; DEVELOPMENT.md notes pnpm dev reset for the ledger cutover; README sample flags the Schema.Date line as the one that moves when the client goes to epoch ms, and says the Effect.die on SchemaError is the capability module's rule, not SqlSchema's.

Kept as is

  • pnpm db:migrate removal: its only entry (migrate.ts) became the library seam, self-hosting is over per the port spec, and the server migrating on startup is the Done-when. Keeping a script would have been a second migrate path to maintain.
  • Duplicated language-service severity map: tooling config with a keep-in-sync comment; a shared tsconfig fragment can come when a third package ports.
  • layer unused in-repo: it is the production client the serving/apps/server ticket wires; package surface.
  • Postgres "resume from partial ledger": that is Effect's Migrator behaviour, covered upstream; re-proving it here is the kind of test we avoid.

Lint, typecheck and 458 tests green.

@allisonmahmood
allisonmahmood merged commit e4325de into main Aug 29, 2026
7 checks passed
@allisonmahmood
allisonmahmood deleted the feat/sql-package branch August 29, 2026 22:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:ci CI, shared testing infrastructure, development scripts and tooling area:docs Touches the docs area area:server Touches the server area size:l 501-1,000 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(sql): @effect/sql-pg client, Effect Migrator and test layer

1 participant