Repository navigation
TML-2686: namespace-aware Postgres enum planner - #632
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughEnum verification and migration planning are now namespace-aware: issues include ChangesNamespace-qualified enum support
Sequence Diagram(s)sequenceDiagram
participant Client
participant verifySchema
participant verifySqlSchema
participant PostgresAdapter
participant Planner
Client->>verifySchema: invoke verifySchema(contract)
verifySchema->>verifySqlSchema: pass resolveExistingEnumValues (prefer contract-scoped)
verifySqlSchema->>PostgresAdapter: resolveExistingEnumValues(schema, enumType, namespaceId)
PostgresAdapter-->>verifySqlSchema: existing enum values (by schemaName+nativeType)
verifySqlSchema->>Planner: emit issues with namespaceId
Planner->>Planner: plan enum ops using compound-key (namespaceId + typeName)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/extension-cipherstash
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/emitter
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
size-limit report 📦
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
packages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.ts (1)
136-144: 💤 Low valueBare
ascast should useblindCastorcastAs.Per coding guidelines, the cast at line 143 should use
blindCastwith a reason string.♻️ Suggested fix
+import { blindCast } from '`@prisma-next/utils/casts`'; + function locateNamespaceType( storage: SqlStorage, namespaceId: string, typeName: string, ): PostgresEnumStorageEntry | undefined { const ns = storage.namespaces[namespaceId]; if (!ns || !('enum' in ns) || ns.enum == null) return undefined; - return (ns.enum as Record<string, PostgresEnumStorageEntry>)[typeName]; + return blindCast<Record<string, PostgresEnumStorageEntry>, 'namespace enum slot is untyped index-signature'>(ns.enum)[typeName]; }As per coding guidelines: "No bare
asin production code. UseblindCast<T, "Reason">orcastAs<T>from@prisma-next/utils/casts."🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.ts` around lines 136 - 144, Replace the bare TypeScript `as` cast in locateNamespaceType with the project's cast utility: use blindCast or castAs from `@prisma-next/utils/casts`; specifically, where the code currently does (ns.enum as Record<string, PostgresEnumStorageEntry>)[typeName], wrap the value with blindCast<Record<string, PostgresEnumStorageEntry>, "Describe reason here">(ns.enum) (or use castAs<Record<string, PostgresEnumStorageEntry>>(ns.enum)) and provide a short reason string explaining why the blind cast is safe; update the import if needed and keep the rest of locateNamespaceType (storage, namespaceId, typeName) unchanged.packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts (1)
70-78: 💤 Low valueBare
ascast should useblindCastorcastAs.Per coding guidelines, production code should avoid bare
ascasts. The cast at line 77 should useblindCastfrom@prisma-next/utils/castswith a reason string explaining why the cast is necessary.♻️ Suggested fix
+import { blindCast } from '`@prisma-next/utils/casts`'; + function locateNamespaceTypeInStorage( storage: SqlStorage, namespaceId: string, typeName: string, ): unknown { const ns = storage.namespaces[namespaceId]; if (!ns || !('enum' in ns) || ns.enum == null) return undefined; - return (ns.enum as Record<string, unknown>)[typeName]; + return blindCast<Record<string, unknown>, 'namespace enum slot is untyped index-signature'>(ns.enum)[typeName]; }As per coding guidelines: "No bare
asin production code. UseblindCast<T, "Reason">orcastAs<T>from@prisma-next/utils/casts."🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts` around lines 70 - 78, In locateNamespaceTypeInStorage replace the bare cast "(ns.enum as Record<string, unknown>)[typeName]" with a safe cast using blindCast from "`@prisma-next/utils/casts`" (import it) and provide a short reason string explaining why we trust ns.enum shape (e.g., "enum shape validated elsewhere"); ensure you call blindCast<Record<string, unknown>, "Reason">(ns.enum) before indexing by typeName so no bare "as" remains.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/2-sql/9-family/src/core/schema-verify/verify-sql-schema.ts`:
- Around line 139-146: The enum collection logic (involving allStorageTypesMap
and namespaceIdForEnumType) uses the bare enum name key (k/typeName), causing
collisions when different namespaces define the same enum; change the keys to a
namespace-qualified form (e.g., `${nsId}:${k}`) when inserting into
allStorageTypesMap and namespaceIdForEnumType and update any lookups that use
typeName (including the similar block around lines 172-181) to use the same
qualified key so enums from different namespaces are stored and verified
separately.
---
Nitpick comments:
In `@packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts`:
- Around line 70-78: In locateNamespaceTypeInStorage replace the bare cast
"(ns.enum as Record<string, unknown>)[typeName]" with a safe cast using
blindCast from "`@prisma-next/utils/casts`" (import it) and provide a short reason
string explaining why we trust ns.enum shape (e.g., "enum shape validated
elsewhere"); ensure you call blindCast<Record<string, unknown>,
"Reason">(ns.enum) before indexing by typeName so no bare "as" remains.
In
`@packages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.ts`:
- Around line 136-144: Replace the bare TypeScript `as` cast in
locateNamespaceType with the project's cast utility: use blindCast or castAs
from `@prisma-next/utils/casts`; specifically, where the code currently does
(ns.enum as Record<string, PostgresEnumStorageEntry>)[typeName], wrap the value
with blindCast<Record<string, PostgresEnumStorageEntry>, "Describe reason
here">(ns.enum) (or use castAs<Record<string,
PostgresEnumStorageEntry>>(ns.enum)) and provide a short reason string
explaining why the blind cast is safe; update the import if needed and keep the
rest of locateNamespaceType (storage, namespaceId, typeName) unchanged.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: c1f2993c-54bd-474d-bf82-9a9bbeb2c89a
⛔ Files ignored due to path filters (2)
projects/contract-ir-planes/slices/namespace-aware-enum-planning/plan.mdis excluded by!projects/**projects/contract-ir-planes/slices/namespace-aware-enum-planning/spec.mdis excluded by!projects/**
📒 Files selected for processing (14)
packages/1-framework/1-core/framework-components/src/control/control-result-types.tspackages/2-sql/9-family/src/core/control-adapter.tspackages/2-sql/9-family/src/core/control-instance.tspackages/2-sql/9-family/src/core/schema-verify/verify-sql-schema.tspackages/3-targets/3-targets/postgres/src/core/migrations/enum-planning.tspackages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner.tspackages/3-targets/3-targets/postgres/src/core/migrations/runner.tspackages/3-targets/3-targets/postgres/src/exports/enum-planning.tspackages/3-targets/3-targets/postgres/test/migrations/enum-collision.test.tspackages/3-targets/3-targets/postgres/test/migrations/issue-planner.test.tspackages/3-targets/6-adapters/postgres/src/core/control-adapter.tspackages/3-targets/6-adapters/postgres/test/control-adapter.test.ts
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@packages/3-targets/3-targets/postgres/test/migrations/enum-collision.test.ts`:
- Around line 336-337: The test currently only checks that a CreateEnumTypeCall
and a DropEnumTypeCall exist in the calls array; update the assertions to filter
for those call types and assert their schemaName is 'public' (e.g.,
calls.filter(c => c instanceof CreateEnumTypeCall) and check every
filteredCall.schemaName === 'public'), and likewise for DropEnumTypeCall; also
tighten the test by asserting expected counts (e.g., exact number of create and
drop calls) to prevent false positives from calls emitted for other schemas.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 867ec675-7964-41cc-a5c0-5f85806e8f79
📒 Files selected for processing (5)
packages/2-sql/9-family/src/core/migrations/contract-to-schema-ir.tspackages/2-sql/9-family/src/exports/control.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.tspackages/3-targets/3-targets/postgres/src/exports/control.tspackages/3-targets/3-targets/postgres/test/migrations/enum-collision.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.ts
f6389fd to
20c3f82
Compare
The replanned project plan runs S1.E parallel to S1.D (disjoint surfaces; the planner bug pre-dates the project). The slice spec B1 and plan D5 note still said "after S1.D" / "sequenced after S1.D for focus". Reframe B1 as a parallel slice whose only ordering lever is reviewer bandwidth, and update the PR-body sequencing note + Linear ref. Signed-off-by: Will Madden <[email protected]>
…at all enum verifier sites EnumValuesChangedIssue gains a required `namespaceId: string` field so the downstream planner can match the issue to the correct namespace's enum without re-scanning. The SQL family verifier's `verifyEnumType` now accepts and stamps the namespace coordinate on both `type_missing` and `enum_values_changed` issues. Existing tests updated to populate the field. Signed-off-by: Will Madden <[email protected]>
…ordinate directly Replace cross-namespace scan loops in locateNamespaceType (planner-strategies.ts) and locateNamespaceTypeInStorage (issue-planner.ts) with direct reads keyed by namespaceId. Both helpers now take (storage, namespaceId, typeName) and read storage.namespaces[namespaceId]?.enum?.[typeName] directly — no first-match-wins scan across all namespaces. Thread the namespace coordinate through all three callsites: - enumRebuildCallRecipe passes namespaceId (from outer loop) to locateNamespaceType - mapIssueToCall passes resolveNamespaceIdForIssue(issue) to locateNamespaceTypeInStorage - nativeEnumPlanCallStrategy uses a temporary scan loop (D3 will replace once collectPostgresEnumTypes returns compound-keyed entries) Column-ref walk in enumRebuildCallRecipe narrowed by nsId === namespaceId so columns in other namespaces sharing a typeRef name do not receive ALTER TYPE calls intended for a different namespace's enum. DDL schema resolution threaded via resolveDdlSchemaForNamespace(ctx, namespaceId) at each CreateEnumTypeCall, AddEnumValuesCall, DropEnumTypeCall, and RenameTypeCall site. Signed-off-by: Will Madden <[email protected]>
…typeName)
D3a (planner-side compound key). collectPostgresEnumTypes now returns a map
keyed by the serialised compound key ${namespaceId}\u0000${typeName} instead of
bare typeName, so two namespaces declaring an enum with the same NAME produce two
distinct entries — no last-write-wins collapse. NUL is the separator (invalid in
both Postgres identifiers and TS symbol names, so unambiguous).
nativeEnumPlanCallStrategy iterates compound entries; handledKeys / introducedKeys
/ rebuiltKeys are compound-key sets. The issue-matching filter resolves the issue
to its compound key via enumCompoundKey(resolveNamespaceIdForIssue(issue),
issue.typeName), relying on the D1 substrate guarantee that enum-related issues
carry namespaceId. The introduce-and-rebuild guard error displays keys with a
readable "ns.type" rendering.
This closes the same-NAME collision (the primary CodeRabbit finding) and satisfies
SDoD6/SDoD7. The same-nativeType collision (readExistingEnumValues schema axis,
spec edge case #3) is deferred to D3b: threading (schemaName, nativeType) through
readExistingEnumValues cascades into the schema-IR provider (the introspection
merge in 6-adapters/.../control-adapter.ts explicitly discards all-but-first
namespace enum storage types), which the D3 refusal trigger routes to a separate
dispatch rather than expanding scope here.
Signed-off-by: Will Madden <[email protected]>
…on merge Key live-schema enum lookup by (schemaName, nativeType) compound key. Merge per-schema storageTypes on multi-namespace introspection. Thread namespaceId through verifier resolveExistingEnumValues callback. Signed-off-by: Will Madden <[email protected]>
Exercise introduce, add_values, rebuild, same-nativeType, and drop paths under audit/public Status collision. Pre-fix regression asserts two CreateEnumTypeCall against empty schema. Signed-off-by: Will Madden <[email protected]>
… tests Signed-off-by: Will Madden <[email protected]>
The (schemaName, nativeType) enum lookup keyed the unbound namespace by its __unbound__ DDL-emit sentinel, but introspection keys storageTypes by the live current_schema() (public). The mismatch made the planner miss existing enums and re-emit CreateEnumTypeCall, failing reconciliation/storage-types integration. Resolve the read schema via resolveDdlSchemaForNamespaceStorage, which returns annotations.pg.schema for the unbound coordinate. Centralise pg-annotation access behind a typed readPgAnnotations helper using blindCast (clears lint:casts). Fix issue-planner test fixture to key storageTypes by the live schema. Signed-off-by: Will Madden <[email protected]>
…__ sentinel CreateEnumTypeCall / AddEnumValuesCall and the rebuild recipe resolved the enum type schema via resolveDdlSchemaForNamespace, which returns the __unbound__ DDL-emit sentinel for a pure-unbound contract — producing CREATE TYPE "__unbound__"."X" that fails with schema does not exist. Route enum type DDL through resolveDdlSchemaForNamespaceStorage so the unbound coordinate resolves to the introspected current_schema (matching the read-lookup key and post-apply verification); named namespaces are unchanged. Column-ref table qualification is left on resolveDdlSchemaForNamespace as before. Signed-off-by: Will Madden <[email protected]>
…lumn binding Contract-to-contract migration planning (migration plan) projects the prior contract to a schema IR via the family provider deriveAnnotations, which keyed enum storageTypes by bare nativeType. The compound-keyed readExistingEnumValues could not find them, so the planner took the introduce path instead of the rebuild recipe. deriveAnnotations now schema-qualifies namespace-scoped enum keys via an injected EnumStorageKeyResolver. The Postgres DDL-schema resolution and the compound-key format stay in target-postgres (control.ts wires the resolver from resolveDdlSchemaForNamespaceStorage + enumStorageCompoundKey); the family layer treats the returned string as opaque. Codec-typed storage types stay bare-keyed. lint:deps stays green — no family to target import. Also fix enumRebuildCallRecipe column-ref binding: a column carries a bare typeRef whose enum may live in a different namespace (the builder places contract-level types: enums in the default public namespace while a model table sits in the unbound namespace). Resolve the column to its own-namespace enum when present, else the ambient/public enum, replacing the over-narrow nsId === namespaceId filter that dropped the alterColumnType migration. Signed-off-by: Will Madden <[email protected]>
…lapse The family verifier aggregated every namespace enum into a bare-name-keyed map and ran verifyEnumType once per unique name, so two namespaces declaring the same enum name collapsed last-write-wins and only one was verified. Verify storage.types codec entries by name and namespace enums per (namespaceId, typeName) instead, each carrying its own namespace coordinate. The bare-keyed column typeRef resolution map (verifySchemaTables) is unchanged. Addresses a CodeRabbit major finding. Adds a verifier regression test (two namespaces, same enum name -> two distinct type_missing issues) and tightens the cross-namespace rebuild test to assert schemaName + exact call counts. Signed-off-by: Will Madden <[email protected]>
Use SqlStorage namespace indexing instead of Object.entries casts in schema verify, and replace control-adapter blindCast with a runtime- narrowed readPostgresSchemaIrAnnotations accessor exported from target-postgres enum-planning. Signed-off-by: wmadden-electric <[email protected]>
Signed-off-by: wmadden-electric <[email protected]>
20c3f82 to
ed49074
Compare
Linked issue
Refs TML-2686
Motivation
CodeRabbit flagged a Major-severity collision on PR #595 (S1.B enum-migration): Postgres enum planning keyed lookups by bare TypeScript name across namespaces, so
audit.Statusandpublic.Statuscollided silently. This slice threadsnamespaceIdthrough issue shapes, lookup helpers, collection, and live-schema reads so each namespace's enum plans independently.Spec:
projects/contract-ir-planes/slices/namespace-aware-enum-planning/spec.mdSequencing: parallel to S1.D — disjoint planner surfaces; no ordering dependency.
At a glance
Two namespaces declaring the same enum name now produce two distinct planner calls:
Before S1.E,
collectPostgresEnumTypeslast-write-wins andlocateNamespaceTypefirst-match-wins collapsed both into one entry.Changes
EnumValuesChangedIssue.namespaceIdrequired; verifier always populatesnamespaceIdon enum-relatedtype_missing/enum_values_changedissues.locateNamespaceType/locateNamespaceTypeInStoragetake(namespaceId, typeName); column-ref walk inenumRebuildCallRecipenarrowed by namespace.collectPostgresEnumTypescompound-keyed bynamespaceId\u0000typeName; strategy tracks compound handled keys;readExistingEnumValues(schema, schemaName, nativeType)with merged per-schema introspection.enum-collision.test.tscovers introduce / add_values / rebuild / same-nativeType/ drop / cross-namespace column binding.SDoD gates (evidence)
pnpm typecheckpnpm --filter @prisma-next/target-postgres testpnpm --filter @prisma-next/family-sql testpnpm lint:depsenum-collision.test.ts→ twoCreateEnumTypeCalllocateNamespaceType(storage, namespaceId, typeName)signatures carry namespaceIdpre-fix regression: two-namespace same enum nameinenum-collision.test.tspnpm test:integrationECONNRESET/ connection-terminated errors in PG integration harness (environmental; slice unit tests green)pnpm fixtures:checkprisma-nextCLI not on PATH during emit in examples packages (environmental)pnpm test:packagesSDoD4 Manual-QA: N/A — planner-internal correctness; no user-facing authoring API change.
SDoD5 out-of-scope: no domain-plane migration, cross-ref encoding, subsumed helper deletion, Mongo/SQLite enum planning, or on-disk contract format changes.
Edge-case disposition
enum-collision.test.tsintroduce + rebuildCreateEnumTypeCall(introduce test)nativeTypecollisionsame nativeType collisiondescribe blockissue-planner.test.tsenum tests greenAlterColumnTypeCalltoaudit.log_entryonlydrop scenariodescribe block"enum_values_changed"JSON/snap fixturesTesting performed
pnpm typecheckpnpm --filter @prisma-next/target-postgres testpnpm --filter @prisma-next/family-sql testpnpm lint:depspnpm test:packages,pnpm test:integration,pnpm fixtures:check(environment failures noted above)Checklist
Summary by CodeRabbit
New Features
Bug Fixes
Tests