Repository navigation
refactor(postgres): schema-node tree restructure — database→namespace→table→policy diff tree - #894
Conversation
Reshape the forward slice sequence and shape slice 2: replace the conflated PostgresSchemaIR with a single-purpose schema-node tree (database → namespace → table → policy; roles on the root), split the diff nodes from the Contract-IR entities, make introspect return the tree (a node; consumers ensure + walk), and move database→PSL inference onto the Postgres target. Behaviour-neutral. spec.md is the prescriptive build (R1–R9, 7 units, alternatives); design.md is the durable architecture reference. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
… schema-diff nodes Slice 2 (schema-node-tree-restructure), unit 1 of 7. PostgresRlsPolicy / PostgresRole were doing two jobs: authored, serialized Contract-IR entities AND diff-tree leaves. Split them: - The entities keep their names, lose DiffableNode (id/children/ isEqualTo gone), and move out of schema-ir/ to core/ alongside the other contract-IR / entity-kind definitions. - New PostgresPolicySchemaNode / PostgresRoleSchemaNode in schema-ir/ are the diff-tree leaves (DiffableNode, static is() guards). Tables already split this way (StorageTable vs PostgresTableIR). Intermediate unit: the differ/planner still reference the entity as a node and break here; they are rewired in unit 6. The branch goes green across the unit sequence; the new-node tests pass (37/37). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Slice 2 (schema-node-tree-restructure), unit 2 of 7. Mechanical rename of the table diff-node to the …SchemaNode scheme, and point its policy children at the Unit-1 node type: - PostgresTableIR → PostgresTableSchemaNode (file, class, Input). - Free guard isPostgresTableIR → static PostgresTableSchemaNode.is(). - Field rlsPolicies → policies: readonly PostgresPolicySchemaNode[]; children() returns this.policies (resolves the Unit-1 DiffableNode type break on the table node). Still extends SqlSchemaIRNode, freezeNode, isEqualTo => true. Intermediate unit: the projection/introspection still pass entity instances where policy nodes are now expected (Unit 5 fixes construction) and the differ/planner still use the entity guard (Unit 6). Table-node tests pass (11/11). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Slice 2 (schema-node-tree-restructure), units 3 and 4 of 7. - PostgresNamespaceSchemaNode: one node per Postgres schema; children() = its tables; satisfies the per-schema SqlSchemaIR shape so the legacy per-schema consumers take it unchanged in unit 6. - PostgresDatabaseSchemaNode: the real tree root; children() = namespaces (roles held, not yet diffed); static is()/assert()/ensure(); narrows on nodeTarget + a nodeKind discriminant that survives the projectSchemaToSpace spread. Additive — does not yet wire/retire PostgresSchemaIR (units 5-6). New-node tests pass; reviewer SATISFIED. Also closes the carried cast/lint findings from rounds 1-2 (bare casts in postgres-rls-policy.ts removed by narrowing; root is()/assert() use blindCast like ensure(); vitest imports merged). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…nit-6 requirement Surfaced by the unit-3/4 review: verify-postgres-namespaces reads existingSchemas off the flat schema via isPostgresSchemaIR, so handing it a namespace node would silently fall back to the [public] default and regress R9. Pinned into the spec so unit 6 rewires the consumer to read existingSchemas from the database root. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Collapse the 164-line plan to a status table + brief notes for the not-yet-done slices + compact locked decisions. Mark slice 1 (select-policies-dependable, #771) and slice 1.5 (#868) as merged; slice 2 as in progress. Implementation detail lives in the slice specs, not the plan. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Slice 2 (schema-node-tree-restructure), unit 5 of 7. Both derivations now build PostgresDatabaseSchemaNode and introspect() returns the root: - Projection (contract-to-postgres-schema-ir.ts → contract-to-postgres- database-schema-node.ts): tables grouped by owning namespace; policies built as PostgresPolicySchemaNode from the contract entities; roles + existingSchemas + pgVersion on the root. Malformed-contract assert strengthened to per-namespace. - Introspection: the flat bare-keyed introspectNamespaces merge (silent cross-schema table collision; kept only the first schema name) is gone, replaced by one namespace node per schema; cluster roles collected once. Intermediate unit: the build is red on the consumers and the family introspect() return-type seam (Promise<SqlSchemaIR>, shared with SQLite) — both rewired in unit 6 (introspect returns a node per design §5). SQLite and CF-1 untouched here. Producer tests pass (8 projection + 121 introspection); reviewer SATISFIED. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
introspect()/verifySchema/planner-options/toSchemaView/collectSchemaDiffIssues now type the schema as the family-base SqlSchemaIRNode. The relational verify walks one per-schema namespace node at a time (namespaceSchemaNodes), never a flat merge — single-schema is one pass, byte-identical to the pre-tree verify; multi-schema contract scoping is CF-2. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…SchemaIR The differ + planner ensure the PostgresDatabaseSchemaNode root and walk the tree; guards switch to PostgresPolicySchemaNode.is/.assert. collectSchemaIssues verifies per namespace node (empty root → one empty pass so contract tables surface as missing). CF-1: existingSchemasFromSchema reads existingSchemas off the database root, never the public default. PostgresSchemaIR + its is/assert/ensure are deleted; consumers use PostgresDatabaseSchemaNode statics. Node ensure() deep-reconstructs namespace/table/policy nodes from the projectSchemaToSpace spread so the differ always sees real DiffableNodes. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
SQLite planner/runner resolve the single flat namespace from the introspected node (sqliteFlatSchema). The aggregate projectSchemaToSpace + the verifier-s orphan detection learn the namespaced tree shape: they prune / enumerate tables inside each namespace node rather than a flat tables record, keeping per-space isolation without flattening namespaces. New project-schema-to-space tests cover the namespaced-tree branch. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Fixtures build PostgresDatabaseSchemaNode roots (namespace nodes holding table nodes holding policy nodes) instead of the deleted flat PostgresSchemaIR; introspection tests narrow the result with PostgresDatabaseSchemaNode.assert and navigate namespaces[…].tables / .roles; policy diff paths gain the namespace segment. Covers diff-postgres-schema, rls-planner, verify-postgres-namespaces, the 6-adapters planner/introspection suites, pgvector planner suites, and the family.introspect / referential-actions integration tests. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
pruneNamespaceTables narrows with a local isRecord type predicate instead of four bare `as` casts, mirroring the predicate already used in verifier.ts. Net casts return below the pre-unit-6 baseline (lint:casts delta=-2). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
The unit-6 relational verify ran verifySqlSchema once per actual namespace node but passed the WHOLE contract each time, so a multi-schema database reported every contract table as missing_table from the N-1 namespaces it does not belong to. Replace verifyContractAgainstNamespaceNodes with a per-namespace pairing: resolve each contract namespace to its live DDL schema (via the target-s expected-tree projection) and check that namespace-s tables against the matching actual node. verifySqlSchema gains an optional restrictToNamespaceIds so the full contract is still consulted for value-set / control-policy resolution while only the paired namespace-s tables are checked. Single-schema and SQLite are one pairing — byte-identical to before; multi-schema is correct. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
… planner + verify The planner and the family schema verify must run the same diffing operation. Extract the per-namespace pairing into a single shared verifySqlSchemaTree in @prisma-next/family-sql/schema-verify (the relational verifySqlSchema paired by namespace identity to the actual nodes). Verify now calls it and rejects when the issues are non-empty — it owns no pairing/scoping logic of its own. The planner collectSchemaIssues calls the same function instead of its old whole-contract-per-node loop, so the planner picks up the multi-schema fix too (its flat loop had the same latent false-missing bug). Behaviour-neutral: single-schema is one pairing, byte-identical; multi-schema is correct. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
The migration planner and the schema verify now run ONE combined database-schema diff instead of each composing the relational + policy strategies themselves. `diffPostgresDatabaseSchema(...)` (new `diff-database-schema.ts`, Postgres target) composes, once each: the per-namespace-paired relational diff (`verifySqlSchemaTree` → table/column/constraint `SchemaIssue`s + the verification-tree root/counts) and the RLS policy diff (`diffPostgresSchema` → ownership-filtered `SchemaDiffIssue`s). It returns a `VerifyDatabaseSchemaResult` whose `schema` carries both shapes — exactly the existing verify-result schema shape, so nothing downstream changes. The two issue shapes stay separate (the relational findings are stringly `SchemaIssue`s, the policy findings carry the live policy nodes the planner needs to build ops); merging them onto one type is the follow-on relational port, not here. The control adapter exposes it as the `diffDatabaseSchema` seam (replacing `collectSchemaDiffIssues`). The family verify calls `controlAdapter.diffDatabaseSchema` and rejects on non-empty — composing no diff itself (SQLite, which has no structural diff, falls back to the relational diff alone). The planner calls the same `diffPostgresDatabaseSchema` and maps `schema.issues` (+ planner-only namespace presence) to DDL ops and `schema.schemaDiffIssues` to RLS ops — no re-diff. Behaviour-neutral: planner ops byte-identical, verify accept/reject and result shape unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Database→PSL inference is target logic (it owns the dialect type/default maps and walks its own schema tree), so it moves off the SQL family onto the Postgres target descriptor — clearing the layering violation and the last expected-red. - The Postgres target descriptor gains `inferPslContract(tree)`, beside `contractSerializer`. New `core/psl-infer/infer-psl-contract.ts` (`inferPostgresPslContract`) walks the `PostgresDatabaseSchemaNode` tree and owns the Postgres maps (`postgres-type-map` / `postgres-default-mapping`, moved from the family). The enum diagnostic now reads each namespace node-s `nativeEnumTypeNames`; tables are gathered across namespaces into the model set and emitted as the single `__unspecified__` bucket — byte-identical PSL. - The shape-neutral leaf transforms (name transforms, relation inference, `mapDefault`, raw-default parser, the `PslTypeMap`/printer-config types) stay in the family and are exported from the new `@prisma-next/family-sql/psl-infer` entrypoint, which the target imports. - The family instance `inferPslContract` delegates to `target.inferPslContract` (read off the descriptor like `contractSerializer`); absent ⇒ a clear error (Mongo). The flat `sqlSchemaIrToPslAst` + `buildPslDocumentAst` are deleted. - The inference tests move to the target (`test/psl-infer/`), retargeted to `inferPostgresPslContract` via tree fixtures; their inline PSL snapshots are unchanged (byte-identity). The neutral-utility tests stay in the family. No SQL-family file imports the Postgres maps; `contract infer` output is byte-identical; the full repo typecheck and `fixtures:check` are green. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
… diff
The migration runner held a third, private copy of the whole-contract-against-
each-namespace-node verify loop that the diffDatabaseSchema unification missed —
the same multi-schema false-missing bug already fixed in the family verify and
the planner. For an auth.user + public.note contract the runner-s post-apply
verify reported public.note missing because it checked the full contract against
the auth namespace node, failing db init. The slice-DoD e2e gate caught it
(multi-namespace-runtime).
The runner now delegates to the family `verifySchema`, the single shared
per-namespace-paired diff (diffDatabaseSchema / verifySqlSchemaTree) the CLI
verify and planner already use — no private per-namespace loop remains. Also
update the control-api integration test: introspect() returns the
PostgresDatabaseSchemaNode tree (namespaces), not the old flat { tables }; the
assertion now checks the real tree shape.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… flatten The expected-side projection called `contractToSchemaIR` once on the whole contract, collapsing every namespace into one bare-keyed `Record<string, SqlTableIR>` that throws on a cross-namespace table-name collision. So a contract with `public.thing` + `auth.thing` could not be projected — the residual flatten the tree restructure was meant to remove. New family helper `contractNamespaceToSchemaIR(storage, namespaceId, options)` converts only one namespace-s tables, keyed within that namespace, passing the full storage so cross-namespace type/value-set/enum resolution is unaffected (and cross-namespace FKs survive — `convertForeignKey` builds purely from `fk.target`). The Postgres projection now calls it per namespace instead of flattening. New test proves same-named cross-schema tables project into distinct namespace nodes without throwing. `verifySqlSchemaTree`-s `restrictToNamespaceIds` stays — it scopes the relational `verifySqlSchema`-s contract-table iteration to one namespace while keeping the full contract available for cross-namespace value-set resolution; the projection fix is on the diff-s expected tree, not what `verifySqlSchema` consumes. Behaviour-neutral: planner ops byte-identical, multi-schema + e2e green. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
|
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:
📝 WalkthroughWalkthroughThis large PR replaces the flat Postgres schema IR ( ChangesPostgres schema IR tree and family diff/verify
AggregateContractSpace rename and unclaimed elements
Estimated code review effort: 5 (Critical) | ~150 minutes Sequence Diagram(s)sequenceDiagram
participant verifyMigration
participant verifySchemaForSpace
participant stripExtraFindings
participant collectExtraElementNames
verifyMigration->>verifySchemaForSpace: verify(schemaIntrospection, space, mode)
verifySchemaForSpace-->>verifyMigration: VerifyDatabaseSchemaResult
verifyMigration->>stripExtraFindings: strip per-space extras
stripExtraFindings-->>verifyMigration: schemaPerSpace entry
verifyMigration->>collectExtraElementNames: gather extra names across spaces
collectExtraElementNames-->>verifyMigration: unclaimed names
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
…sions + D1 follow-on Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@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/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/extension-supabase
@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/config-loader
@prisma-next/emitter
@prisma-next/language-server
@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: 9
🧹 Nitpick comments (4)
packages/1-framework/3-tooling/migration/src/aggregate/verifier.ts (1)
237-240: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winPrefer
blindCastover a bareasfor this structural read.As per coding guidelines: "No bare
asin production code. UseblindCast<T, \"Reason\">orcastAs<T>".🤖 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/1-framework/3-tooling/migration/src/aggregate/verifier.ts` around lines 237 - 240, The structural read in verifier.ts uses a bare `as` cast, which violates the casting guideline. Update the schema narrowing in the verifier logic to use `blindCast<T, "Reason">` or `castAs<T>` instead of the direct assertion, keeping the existing `schemaIntrospection` handling and the `schema` variable in the same flow.Source: Coding guidelines
packages/1-framework/3-tooling/migration/src/aggregate/project-schema-to-space.ts (1)
68-72: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winPrefer
blindCastover a bareasfor this structural read.The repo convention (and the sibling
namespaceSchemaNodeshelper this tree feeds) usesblindCast<T, "reason">for exactly this kind of duck-typed structural read rather than a bareas.
As per coding guidelines: "No bareasin production code. UseblindCast<T, \"Reason\">orcastAs<T>".🤖 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/1-framework/3-tooling/migration/src/aggregate/project-schema-to-space.ts` around lines 68 - 72, Replace the bare structural cast in the schema reader with the repo-standard blindCast pattern. In project-schema-to-space’s schema normalization logic, update the schemaObj assignment to use blindCast with an explicit reason instead of a plain as cast, matching the convention used by namespaceSchemaNodes and other duck-typed reads. Keep the inferred shape the same while making the cast intent explicit and consistent with the coding guidelines.Source: Coding guidelines
packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts (1)
597-602: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value
getPostgresVersionruns once per namespace though it's cluster-scoped.
introspectSchemacallsgetPostgresVersionat Line 1202, so a multi-namespace walk issues aSELECT version()per schema and the loop just overwritespgVersionkeeping only the last (Line 601). Consider hoisting the version query out of the per-namespace loop inintrospectand dropping it fromintrospectSchema.Also applies to: 1202-1202
🤖 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/6-adapters/postgres/src/core/control-adapter.ts` around lines 597 - 602, `introspect` is doing a cluster-scoped PostgreSQL version lookup once per schema and then overwriting the result in the `pgVersion` accumulator. Hoist the `getPostgresVersion` call out of `introspectSchema` into `introspect` so it runs once before the `resolvedSchemas` loop, pass the version through as needed, and remove the version query from `introspectSchema` so it only handles per-namespace introspection. Ensure the `introspect` and `introspectSchema` flow still returns the same `pgVersion` value for all namespaces.packages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-namespace-schema-node.ts (1)
54-62: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueMinor:
annotations.pg.nativeEnumTypeNamesreuses the raw input array, not the frozen copy.Line 54 stores a defensively-copied, frozen
nativeEnumTypeNameson the instance, but Lines 58-59 embed the originalinput.nativeEnumTypeNamesreference insideannotations.pg. Depending onfreezeNode's depth, this either leaves the annotation array externally mutable (shallow freeze) or mutates the caller's array to frozen as a side effect (deep freeze). Consider reusingthis.nativeEnumTypeNamesfor the annotation to keep both consistent.Proposed tweak
this.nativeEnumTypeNames = Object.freeze([...input.nativeEnumTypeNames]); this.annotations = { pg: { schema: input.schemaName, - ...(input.nativeEnumTypeNames.length > 0 && { - nativeEnumTypeNames: input.nativeEnumTypeNames, + ...(this.nativeEnumTypeNames.length > 0 && { + nativeEnumTypeNames: this.nativeEnumTypeNames, }), }, };🤖 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/schema-ir/postgres-namespace-schema-node.ts` around lines 54 - 62, `PostgresNamespaceSchemaNode` is putting the raw `input.nativeEnumTypeNames` array into `annotations.pg` instead of the class’s frozen copy. Update the constructor logic to reuse `this.nativeEnumTypeNames` when building `annotations`, so `nativeEnumTypeNames` stays consistent with the defensively copied instance state and avoids leaking the caller’s array reference.
🤖 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/1-framework/3-tooling/migration/src/aggregate/verifier.ts`:
- Around line 241-254: The table-name collection in the schema helper is
returning duplicates when the same table exists under multiple namespaces, which
later causes duplicate orphan entries. Update the logic in the schema table-name
gathering path used by detectOrphanElements to dedupe names as they are
collected, ideally by switching the local accumulator from an array to a Set and
returning unique table names while preserving the existing
namespaces/schema.tables fallback behavior.
In `@packages/2-sql/9-family/src/core/control-adapter.ts`:
- Around line 212-218: The diffDatabaseSchema input currently omits
normalizeDefault and normalizeNativeType, so the shared diff path compares raw
defaults and types and can produce false drift. Update the diffDatabaseSchema
signature in control-adapter and any implementations/callers to accept these two
normalizer fields, then thread them through to the shared diff logic used by
diffDatabaseSchema so the target diff applies the normalizations consistently.
In `@packages/2-sql/9-family/src/core/control-instance.ts`:
- Around line 730-737: After `filterSchemaDiffIssues` removes structural issues
in `control-instance.ts`, recompute the `ok` state for the returned `sqlResult`
instead of returning it unchanged. Update the
`schemaDiffIssues`/`schema.counts.fail` branch so that `ok` reflects the
filtered schema issues, especially when the original failure was caused only by
suppressed structural diffs, and keep the logic localized around the
`schemaDiffIssues` and `relationalFails` handling.
- Around line 947-955: The table flattening in toSchemaView is dropping the
namespace identity, which causes duplicate SchemaTreeNode IDs for tables with
the same name in different schemas. Update the tableEntries construction in
control-instance.ts so each entry carries the namespace/schema name from
namespaceSchemaNodes, then use that namespace when building the table-level
nodes and IDs in the subsequent tableNodes mapping. Ensure the resulting
SchemaTreeNode labels and IDs stay unique for cases like public.users and
auth.users.
In `@packages/2-sql/9-family/src/core/schema-verify/verify-sql-schema.ts`:
- Around line 340-343: The strict extra-table claim check in verify-sql-schema
should be limited to the paired namespace set, not all contract namespaces.
Update the claimed-table scan in verifySqlSchema (including the same logic used
around the missing-table handling and the matching block at the later location)
so it skips namespaces not present in restrictToNamespaceIds when that set is
provided. This will keep tree verification from letting a table claimed in auth
mask an unexpected same-named table in the public actual node.
- Around line 1407-1426: `mergeVerifyResults` is merging `schema.counts`
correctly but leaving `summary` from the first result, which can make
multi-namespace failures report stale counts. Update `mergeVerifyResults` in
`verify-sql-schema.ts` so the merged result recomputes `summary` from the
combined `a.schema` and `b.schema` data after summing counts, rather than
reusing `a.summary`; use the existing `mergeVerifyResults` flow and the
`schema`/`counts` fields to keep the summary consistent with the merged totals.
In `@packages/3-targets/3-targets/postgres/package.json`:
- Line 38: The dependency entry for `@prisma-next/psl-printer` in the postgres
package.json uses workspace:* instead of the repo’s pinned internal version
convention. Update this package’s internal `@prisma-next/`* dependency to use the
same literal workspace version string as the other internal deps in this
manifest, keeping the existing dependency naming intact.
In `@packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts`:
- Around line 393-400: The namespace selection logic in namespaceSchemaNode is
too permissive because it falls back to namespaceNodes[0] even when multiple
namespaces exist and none match schemaName. Update the helper so it only returns
the first namespace for the single-namespace case, and otherwise returns no
match or raises the appropriate ambiguity handling for relational planning. Keep
the lookup tied to namespaceSchemaNodes and the byName selection so ambiguous
schema matches do not silently probe the wrong namespace.
In `@packages/3-targets/3-targets/postgres/test/rls-diffable-nodes.test.ts`:
- Around line 60-77: The role fixture in the Postgres diffable nodes tests is
using the wrong namespace coordinate for PostgresRole. Update the relevant role
assertions and any similar fixtures to use the cluster-scoped namespace sentinel
UNBOUND_NAMESPACE_ID instead of public, so the tests match the PostgresRole
contract while still verifying kind and name through the PostgresRole
constructor-based fixtures.
---
Nitpick comments:
In
`@packages/1-framework/3-tooling/migration/src/aggregate/project-schema-to-space.ts`:
- Around line 68-72: Replace the bare structural cast in the schema reader with
the repo-standard blindCast pattern. In project-schema-to-space’s schema
normalization logic, update the schemaObj assignment to use blindCast with an
explicit reason instead of a plain as cast, matching the convention used by
namespaceSchemaNodes and other duck-typed reads. Keep the inferred shape the
same while making the cast intent explicit and consistent with the coding
guidelines.
In `@packages/1-framework/3-tooling/migration/src/aggregate/verifier.ts`:
- Around line 237-240: The structural read in verifier.ts uses a bare `as` cast,
which violates the casting guideline. Update the schema narrowing in the
verifier logic to use `blindCast<T, "Reason">` or `castAs<T>` instead of the
direct assertion, keeping the existing `schemaIntrospection` handling and the
`schema` variable in the same flow.
In
`@packages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-namespace-schema-node.ts`:
- Around line 54-62: `PostgresNamespaceSchemaNode` is putting the raw
`input.nativeEnumTypeNames` array into `annotations.pg` instead of the class’s
frozen copy. Update the constructor logic to reuse `this.nativeEnumTypeNames`
when building `annotations`, so `nativeEnumTypeNames` stays consistent with the
defensively copied instance state and avoids leaking the caller’s array
reference.
In `@packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts`:
- Around line 597-602: `introspect` is doing a cluster-scoped PostgreSQL version
lookup once per schema and then overwriting the result in the `pgVersion`
accumulator. Hoist the `getPostgresVersion` call out of `introspectSchema` into
`introspect` so it runs once before the `resolvedSchemas` loop, pass the version
through as needed, and remove the version query from `introspectSchema` so it
only handles per-namespace introspection. Ensure the `introspect` and
`introspectSchema` flow still returns the same `pgVersion` value for all
namespaces.
🪄 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: 28eb30df-16d3-4255-8569-8ba7e658c740
⛔ Files ignored due to path filters (4)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamlprojects/postgres-rls/plan.mdis excluded by!projects/**projects/postgres-rls/slices/schema-node-tree-restructure/design.mdis excluded by!projects/**projects/postgres-rls/slices/schema-node-tree-restructure/spec.mdis excluded by!projects/**
📒 Files selected for processing (97)
packages/1-framework/3-tooling/migration/src/aggregate/project-schema-to-space.tspackages/1-framework/3-tooling/migration/src/aggregate/verifier.tspackages/1-framework/3-tooling/migration/test/aggregate/project-schema-to-space.test.tspackages/2-sql/1-core/schema-ir/src/ir/sql-schema-ir.tspackages/2-sql/9-family/package.jsonpackages/2-sql/9-family/src/core/control-adapter.tspackages/2-sql/9-family/src/core/control-instance.tspackages/2-sql/9-family/src/core/migrations/contract-to-schema-ir.tspackages/2-sql/9-family/src/core/migrations/types.tspackages/2-sql/9-family/src/core/psl-contract-infer/printer-config.tspackages/2-sql/9-family/src/core/schema-verify/verify-sql-schema.tspackages/2-sql/9-family/src/exports/control.tspackages/2-sql/9-family/src/exports/psl-infer.tspackages/2-sql/9-family/src/exports/schema-verify.tspackages/2-sql/9-family/test/psl-contract-infer/default-mapping.test.tspackages/2-sql/9-family/tsdown.config.tspackages/3-extensions/pgvector/test/migrations/planner.behavior.test.tspackages/3-extensions/pgvector/test/migrations/planner.contract-to-schema-ir.test.tspackages/3-extensions/pgvector/test/migrations/planner.storage-types.test.tspackages/3-targets/3-targets/postgres/package.jsonpackages/3-targets/3-targets/postgres/src/core/authoring.tspackages/3-targets/3-targets/postgres/src/core/entity-kinds.tspackages/3-targets/3-targets/postgres/src/core/migrations/contract-to-postgres-database-schema-node.tspackages/3-targets/3-targets/postgres/src/core/migrations/contract-to-postgres-schema-ir.tspackages/3-targets/3-targets/postgres/src/core/migrations/diff-database-schema.tspackages/3-targets/3-targets/postgres/src/core/migrations/diff-postgres-schema.tspackages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.tspackages/3-targets/3-targets/postgres/src/core/migrations/operations/rls.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/core/migrations/verify-postgres-namespaces.tspackages/3-targets/3-targets/postgres/src/core/postgres-rls-policy.tspackages/3-targets/3-targets/postgres/src/core/postgres-role.tspackages/3-targets/3-targets/postgres/src/core/postgres-schema.tspackages/3-targets/3-targets/postgres/src/core/psl-infer/infer-psl-contract.tspackages/3-targets/3-targets/postgres/src/core/psl-infer/postgres-default-mapping.tspackages/3-targets/3-targets/postgres/src/core/psl-infer/postgres-type-map.tspackages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-database-schema-node.tspackages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-namespace-schema-node.tspackages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-policy-schema-node.tspackages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-role-schema-node.tspackages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-schema-ir-annotations.tspackages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-schema-ir.tspackages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-table-schema-node.tspackages/3-targets/3-targets/postgres/src/exports/control.tspackages/3-targets/3-targets/postgres/src/exports/planner.tspackages/3-targets/3-targets/postgres/src/exports/types.tspackages/3-targets/3-targets/postgres/test/migrations/contract-to-postgres-database-schema-node.test.tspackages/3-targets/3-targets/postgres/test/migrations/contract-to-postgres-schema-ir.test.tspackages/3-targets/3-targets/postgres/test/migrations/diff-postgres-schema.test.tspackages/3-targets/3-targets/postgres/test/migrations/rls-ops.test.tspackages/3-targets/3-targets/postgres/test/migrations/rls-planner.test.tspackages/3-targets/3-targets/postgres/test/migrations/verify-postgres-namespaces.test.tspackages/3-targets/3-targets/postgres/test/postgres-contract-serializer.test.tspackages/3-targets/3-targets/postgres/test/postgres-database-schema-node.test.tspackages/3-targets/3-targets/postgres/test/postgres-namespace-schema-node.test.tspackages/3-targets/3-targets/postgres/test/postgres-table-ir.test.tspackages/3-targets/3-targets/postgres/test/postgres-table-schema-node.test.tspackages/3-targets/3-targets/postgres/test/psl-infer/fixtures.tspackages/3-targets/3-targets/postgres/test/psl-infer/infer-psl-contract.test.tspackages/3-targets/3-targets/postgres/test/psl-infer/postgres-type-map.test.tspackages/3-targets/3-targets/postgres/test/psl-infer/print-psl/print-psl.core.test.tspackages/3-targets/3-targets/postgres/test/psl-infer/print-psl/print-psl.defaults-and-types.test.tspackages/3-targets/3-targets/postgres/test/psl-infer/print-psl/print-psl.enums.test.tspackages/3-targets/3-targets/postgres/test/psl-infer/print-psl/print-psl.naming-and-constraints.test.tspackages/3-targets/3-targets/postgres/test/psl-infer/print-psl/print-psl.relations.test.tspackages/3-targets/3-targets/postgres/test/psl-policy-authoring.test.tspackages/3-targets/3-targets/postgres/test/rls-diffable-nodes.test.tspackages/3-targets/3-targets/postgres/test/rls-ir-kinds.test.tspackages/3-targets/3-targets/postgres/test/schema-ir-leaf-nodes.test.tspackages/3-targets/3-targets/sqlite/src/core/migrations/planner.tspackages/3-targets/3-targets/sqlite/src/core/migrations/runner.tspackages/3-targets/6-adapters/postgres/src/core/control-adapter.tspackages/3-targets/6-adapters/postgres/test/control-adapter.check-constraints.test.tspackages/3-targets/6-adapters/postgres/test/control-adapter.defaults.test.tspackages/3-targets/6-adapters/postgres/test/control-adapter.test.tspackages/3-targets/6-adapters/postgres/test/migrations/array-column-introspection.integration.test.tspackages/3-targets/6-adapters/postgres/test/migrations/fixtures/runner-fixtures.tspackages/3-targets/6-adapters/postgres/test/migrations/index-introspection.integration.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.authoring-surface.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.codec-field-event.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.cross-space-fk-ddl.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.fk-config.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.integration.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.reconciliation.integration.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.reconciliation.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.referential-actions.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.semantic-satisfaction.test.tspackages/3-targets/6-adapters/postgres/test/migrations/rls-collect-extension-issues.test.tspackages/3-targets/6-adapters/postgres/test/migrations/rls-introspection.integration.test.tspackages/3-targets/6-adapters/postgres/test/migrations/rls-lifecycle-e2e.integration.test.tspackages/3-targets/6-adapters/postgres/test/migrations/rls-migration-plan.integration.test.tstest/integration/test/control-api.test.tstest/integration/test/cross-package/postgres-control-policy-planner.test.tstest/integration/test/family.introspect.integration.test.tstest/integration/test/family.introspect.test.tstest/integration/test/referential-actions.integration.test.ts
💤 Files with no reviewable changes (4)
- packages/3-targets/3-targets/postgres/test/migrations/contract-to-postgres-schema-ir.test.ts
- packages/3-targets/3-targets/postgres/test/postgres-table-ir.test.ts
- packages/3-targets/3-targets/postgres/src/core/migrations/contract-to-postgres-schema-ir.ts
- packages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-schema-ir.ts
…PSL slice; note the fail-loud guard) Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The inference gather flattens the tree-s tables into one bucket for the
single-namespace `__unspecified__` PSL output. It did a silent last-wins
overwrite if two namespaces held the same table name — unreachable today
(`contract infer` introspects a single namespace) but a new silent-lossy path on
this branch. It now throws an actionable error naming the table, mirroring the
`contractToSchemaIR` duplicate-name throw: same-named cross-schema tables are not
yet supported for `contract infer` (multi-namespace `namespace { … }` output is a
later slice). New test proves the tree with two same-named tables throws instead
of dropping one. Behaviour-neutral: unreachable on all single-namespace paths —
psl-infer suite, contract-infer e2e, and fixtures:check stay green.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…tor operation The combined database-schema diff was an optional method on the SQL control adapter. Move it to the SQL target descriptor and make it required: schema comparison is target logic (dialect type/default maps, schema-tree walk), not adapter I/O, so it belongs on the descriptor alongside contractSerializer and inferPslContract. - Relocate the relational diffing code from core/schema-verify/ to core/diff/ (verify-sql-schema.ts -> sql-schema-diff.ts, plus the sibling files) with no logic changes. The family entrypoint moves from ./schema-verify to ./diff. - Add diffDatabaseSchema to SqlControlTargetDescriptor as a required operation. Postgres provides relational + policy diffing (diffPostgresDatabaseSchema); SQLite provides relational-only diffing via a new diffSqliteDatabaseSchema. - The family verifier (verifySchema) becomes a thin consumer: it introspects the actual schema, calls target.diffDatabaseSchema, applies control-policy suppression as a post-step, and fails when a surviving issue remains. It no longer composes any diffing itself and has no SQLite fallback branch. - Drop the now-dead diffDatabaseSchema method and orphaned imports from the Postgres control adapter; update importers and test fixtures accordingly. Behavior-neutral: planner op-assertions are unchanged and pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ff flatten helper
The schema view and SQLite reached into namespaceSchemaNodes — a diff-internal
flatten helper — to walk the schema IR. Decouple both so the helper is used only
inside the diff module.
- toSchemaView now walks the schema-IR tree own structure (root -> namespaces ->
tables) directly instead of calling namespaceSchemaNodes, and drops that
import from control-instance.ts. A multi-namespace test locks the flatten
output.
- SQLite post-apply verify (runner) and the planner schema-issue collection now
go through diffSqliteDatabaseSchema (added in the prior unit) rather than
namespaceSchemaNodes(x)[0] ?? { tables: {} } + a direct verifySqlSchema call.
The duplicated empty-schema fallback is gone; the planner narrows the flat
SQLite node directly when building ops.
Behavior-neutral: schema-view output and SQLite db verify verdicts are
unchanged; the SQLite planner op-assertions are unaffected.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… flatten helper relationalNamespaceNode was the last consumer of namespaceSchemaNodes outside the diff module. The Postgres planner always holds a PostgresDatabaseSchemaNode, so it does not need the generic flatten helper: ensure the node and read its .namespaces directly to select the namespace by schemaName. namespaceSchemaNodes is now used only inside the diff module (and re-exported from exports/diff). Behavior-neutral: planner ops byte-identical (planner/rls-planner op-assertions unmodified and passing). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ld, never a string convention Will's review: filtering on kind-string enumeration invents a string convention for a structural characteristic. Every diff issue fails an expectation one of three ways — not-expected, not-found, not-equal — carried as reason: ExpectationFailureReason on both issue types and grafted verify nodes (comparison-relative, so contract-vs-DB and contract-vs-contract stay unambiguous). SchemaDiffIssue keeps legacy outcome alongside until the slice-2.5 issue-type merge; the framework never matches family-invented kind/code strings. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…d; the framework filters structurally
Every diff finding now carries reason: ExpectationFailureReason
("not-expected" | "not-found" | "not-equal") — the three ways an actual state
can fail an expectation, comparison-relative (expected = desired side, actual =
current side), so the vocabulary never anchors to a base that flips between
contract-vs-database and contract-vs-contract comparisons.
SchemaDiffIssue gains reason alongside its legacy outcome; both are stamped at
the one producer (diffSchemas), so they cannot drift, and outcome retires with
the issue-type merge. The family verifiers stamp reason on every relational
issue at construction (SQL walk, verify helpers, Mongo, the namespace check),
and on the verify-tree nodes they graft for live entities no contract expects.
The aggregate strip and unclaimed-elements collection are now structural
filters: the tree strip keeps root children without reason "not-expected"; the
issue strip narrows by the framework-declared extra_table kind (on the legacy
coordinate-based issue the entity level is not yet a structural field — a pure
coordinate-shape check would wrongly strip extra_primary_key and Mongo
extra_validator, which carry no finer coordinate). The kind-enumeration and
family node-code helpers (isExtraIssue, isEntityNode, isExtraTableNode) are
deleted; no "table"/"collection"/"EXTRA_COLLECTION" strings remain. The synth
keep-predicate keys on reason. The diff-extras path in the unclaimed collection
stays: in a tolerant verify the relational walk emits no extra_table issue, so
an undeclared table carrying an RLS policy is only nameable through the
policy node — removing it would change lenient output.
Code comments describe behaviour in plain terms; design-document section
labels are gone. CodeRabbit round: role fixtures use the cluster-scoped
namespace sentinel.
Behaviour-neutral: fixtures byte-identical, verify verdicts and planner ops
unchanged.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…delete the CLI fold Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…idental The per-pr-declaration check requires every PR touching packages/3-extensions/ to record intent in the in-flight extension-author upgrade instructions. This slice touches extension test files only (pgvector planner fixtures rebuilt for the schema-node tree, a supabase test comment); no extension-author API changed, so the declaration is an incidental note per the established pattern. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…estructure Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> # Conflicts: # skills/extension-author/prisma-next-extension-upgrade/upgrades/0.14-to-0.15/instructions.md
The combined-summary fallback read firstFailure through a bare `as`. When `okAll` is false the loop assigned `firstFailure`, so an optional read with the app summary as the (unreachable) fallback expresses the same invariant without a cast. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
… basis The Mongo runner scoping recomputed counts with a tree walk that counted the synthetic root, while diffMongoSchemas tallies per collection and never counts the root — an off-by-one in pass/totalNodes after a prune. The walk now covers the root's subtrees only; the tests pin exact counts (one surviving collection => totalNodes 1, not 2), red before the fix. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
toSchemaView flattened every namespace's tables into ids/labels built from the bare table name, so same-named tables in different namespaces (public.thing and auth.thing) collided in the rendered tree. A multi-namespace root now qualifies each table's display name with its namespace key through the table/columns/column/primary-key/unique/index node ids and the table label; a single-namespace root and a flat SQLite root render exactly as before. Synthesized constraint/index fallback names keep the bare table name — the name the database derives them from. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
|
toSchemaView namespace collision (re-raised across rounds): fixed in 338c1e9 — a multi-namespace root now qualifies table ids/labels with the namespace key (table-public.thing vs table-auth.thing) through the table/columns/column/primary-key/unique/index nodes; single-namespace and flat roots render as before, and synthesized fallback constraint names keep the bare table name. Test with public.thing + auth.thing asserts distinct ids. Covers the same re-raise in the round-3 review body. |
…ggregate namespaces collectAggregateNamespaces replaced the whole namespace object per key, so two contract spaces legitimately sharing a namespaceId had the earlier space's tables silently dropped from the object handed to introspect — skewing extra/unclaimed detection in a multi-extension aggregate. Shared namespaces now merge per entity kind (element disjointness is already enforced by checkIntegrity, so kind maps cannot collide on a name). Red-first tests cover the shared-namespace union, per-kind union, and the disjoint case. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
The schema-only render passed --quiet through to the failure output, so `db verify --schema-only --quiet` against a failing schema exited 1 with zero diagnostics. The failure render now overrides quiet, the same policy the full-mode failure branch already applies. Red-first integration test pins diagnostics + exit 1 for a missing table under --quiet. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…rral Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
… describe (prisma#919) ## What `contract infer` now writes a `contract.prisma` containing only what the stack's contract spaces don't already account for. When a stack extension pack's contract space declares a DB element (e.g. the Supabase pack's tables), the inferrer omits it — a brownfield app on top of an extension gets a contract of *its own* tables. Slice G of the extension-supabase project (decision C16). Independent of RLS, native enums, and the complete-contract work (Slice F): it subtracts whatever the packs declare today, and deepens automatically as they declare more. Also carries the plan-expansion docs (Slices F/G, C16, un-defers) from the closed prisma#899, so the plan travels with the work. ## How The match reuses the framework's existing coordinate primitive — nothing new is minted. - The Postgres inferrer runs `elementCoordinates` (from `@prisma-next/framework-components/ir` — the same coordinate walk the contract-space aggregate and cross-space collision check already use) over each pack's contract storage, building a set of declared `(namespaceId, entityKind, entityName)` coordinates. - While gathering the `PostgresDatabaseSchemaNode` tree (prisma#894's substrate), it omits any node whose coordinate is in that set. A table lives at `(schemaName, 'table', tableName)`; the match is **entity-agnostic** (enums/roles/policies covered for free as they enter the tree) and **coordinate-precise** (a pack's `auth.users` cannot suppress an app's `public.users`). - The family instance forwards the packs' already-assembled contracts (`readonly Contract<SqlStorage>[]`) through a widened `inferPslContract` hook param — no new type, nothing added to `migrations/types.ts`. - Omission happens **before** the cross-schema duplicate-name check and relation inference; surviving tables' foreign keys are dropped only when the referenced name was omitted **and** has no surviving table (so no dangling `@relation`, and a legitimate same-named relation elsewhere is never stripped). - Empty/absent input → byte-identical output (`fixtures:check` clean). The framework capability, CLI, introspection scope, and `db verify` are untouched. SQLite doesn't bind the hook; Mongo has no infer. ## Follow-on The ownership query has no named home yet. TML-2977 extracts a framework-level `ContractSpaceAggregate` base (pure aggregation of contract spaces + coordinate-precise ownership) that today's migration-state aggregate extends as `MigrationSpaceAggregate`; this slice's inline `elementCoordinates` call then collapses to a one-line delegation, and re-infer (reconcile the app space via the schema diff) rides the same base. Not gating this slice. ## Tests Omission by coordinate + byte-identity; namespace-correctness (`auth`-declared name doesn't omit a `public` table); entity-kind precision (a same-named non-table entity never suppresses a table — proves the key isn't table-typed); dangling-FK both directions (strip vs keep-a-surviving-same-name); duplicate-name-before-throw; and a real end-to-end test (real `postgresTargetDescriptor` + real family instance). ## Verification build · typecheck (143/143) · family-sql + target-postgres suites · fixtures:check byte-identical · lint:deps · lint:casts delta 0 · check:upgrade-coverage — all green locally. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * `contract infer` now omits DB tables already covered by stack extension-pack contract spaces. * Cross-space foreign keys are now qualified with the owning pack’s namespace and contract-space identifiers for clearer relation fields and printed PSL. * **Bug Fixes** * Omission is scoped to the exact coordinate (avoiding suppression across different namespaces/same-named entities). * Filters only dangling foreign keys that target omitted tables while preserving valid relationships. * **Tests** * Added unit and integration coverage for described-contract omission, cross-space FK inference, and malformed-pack error handling. * **Documentation** * Updated upgrade guidance to reflect the new omission/qualification behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]> Co-authored-by: Claude Fable 5 <[email protected]>
What this delivers
Retires the conflated
PostgresSchemaIR(a diff-tree node, a Postgres schema, and the tree root at once) for a single-purposedatabase → namespace → table → policyschema-node tree, and — through three rounds of review — restructures schema diffing anddb verify/planaround it. Foundation for slice 3 (@@rls, managed/external grading, policy rename).The architecture (as landed)
Authoritative design:
design-diff-and-verify.md. Four actors, cleanly separated:SchemaDiff<SqlSchemaDiffNode>; the planner builds ops from the typed nodes, no casts). Internals private.declaresEntity/declaringSpaces); it diffs, verifies, and classifies nothing.keepDiffIssuepredicate (built over the passive aggregate); the planner applies it verbatim before op-building. No schema pruning, no "other spaces' names", no post-scoping —scope-schema-result,entitiesOwnedByOtherSpaces, and the set-subtraction helper are deleted.…SchemaNodeclasses with definednodeKinds; staticis/assertguards (noinstanceof, no node-constructingensure());isEqualTois identity; the vocabulary is contract space throughout the aggregate.Review response
nodeKindguards.SchemaDifferSPI +SchemaDiffresult; node-guard consistency; file dedup (one diff module; diff-SPI types out of the catch-alltypes.ts); planner cleanups; transient IDs removed.5e3673318); the two-part verify (9e2e80f0f+8c3d4a10b+9309fd00d); the plan collapse deleting the cross-space plumbing (14f5b7a73); the contract-space rename retiring "member" and "schema result" (9d56e8eba).reason: ExpectationFailureReason('not-expected' | 'not-found' | 'not-equal') on both issue types and grafted verify nodes, stamped at the producers — so the framework filters structurally, with zero family-invented strings (32ad8f571). Legacyoutcomestays alongside until the slice-2.5 issue-type merge. Theplan(start, end)planner reshape is scheduled as slice 2.5 (one-differ-two-ir-planner) in the project plan.Confirmed non-duplicates from review:
contract-to-postgres-database-schema-nodebuilds the Postgres tree atop the shared per-namespace table conversion (contractToSchemaIR's flat map is SQLite-only);verify-postgres-namespacesis live (itsmissing_schemaissues drive multi-schemaCREATE SCHEMAplanning).Verification
Planner ops byte-identical throughout (
fixtures:checkclean at every unit);contract inferunchanged; the runner's post-apply verify and single-space family verify preserved; multi-space guards green (cross-namespace-fk, supabaseclassification.e2e+cross-contract-fk,multi-namespace-runtime).lint:depsclean;lint:castsnet −11. The deliberate output change is confined todb verify's unclaimed-element reporting (two-part model above). CI on the merge ref arbitrates the full suites.Follow-ons (out of scope)
SchemaIssuenode-typing and liftsroot/countsoff the relational walk.annotations.pgretirement.🤖 Generated with Claude Code